[AIX 성능 도구 6] perfstat API (1) 특징과 전역 인터페이스

핵심 정리

  • perfstat API는 사용자 공간에서 쓰는 C 서브루틴 모음(libperfstat.a)으로, perfstat 커널 확장으로 AIX 성능 지표를 꺼냅니다. 스레드 안전이고 root 권한이 필요 없습니다. vmstat, iostat, lparstat 같은 명령을 직접 만들 수 있습니다.
  • 인터페이스 종류: 전역(global) 집합 지표, 구성 요소별(component-specific) 개별 지표, (6.1) WPAR, RSET, NODE(6.1 TL6, 클러스터 원격 노드).
  • 값은 누적 카운터 원래 값이므로, 비율을 구하려면 일정 간격으로 두 번 불러 차이를 계산합니다. 너무 자주 부르면 성능에 영향이 있습니다.
  • 전역 인터페이스 공통 형태: perfstat_xxx_total(NULL, &buf, sizeof(buf), 1). 실패하면 -1, 성공하면 1을 돌려줍니다.
  • ODM에서 얻는 정보는 캐시되므로 시스템 구성이 바뀌면 perfstat_reset(또는 perfstat_partial_reset)을 부릅니다. 예제는 /usr/samples/libperfstat에 있고 Makefile.samples로 컴파일합니다.
항목 내용
버전 AIX 5.3, AIX 6.1 (6.1에서 WPAR·RSET·NODE 유형, perfstat_partition_config, 페이지 병합(coalescing) 필드가 더해짐)
원문 Performance Tools Guide and Reference — 5.3판 6장(143154쪽), 6.1판 8099쪽
파일 세트 bos.perf.libperfstat(라이브러리·헤더·예제), bos.perf.perfstat(커널 확장)
파일 /usr/lib/libperfstat.a, /usr/include/libperfstat.h, /usr/samples/libperfstat
관련 명령어 lparstat, vmstat, iostat, mpstat, topas

perfstat 응용 프로그래밍 인터페이스(API)는 사용자 공간에서 쓰는 C 언어 서브루틴 모음입니다. perfstat 커널 확장을 써서 여러 AIX 성능 지표를 꺼냅니다.

시스템 구성 요소 정보는 ODM(Object Data Manager)에서도 가져와 성능 지표와 함께 돌려줍니다.

perfstat API는 스레드 안전(thread-safe)하며 root 권한이 필요 없습니다.

API는 확장을 지원하므로 모든 AIX 릴리스에서 바이너리 호환성이 유지됩니다. 모든 API 호출의 매개변수 하나로 돌려받을 데이터 구조체의 크기를 지정해 이를 이룹니다. 라이브러리는 이 값으로 사용 중인 버전을 판단하고, 커지는 구조체를 그에 맞게 다룹니다. 그래서 사용자는 버전 차이에 매이지 않습니다. 이전 AIX 버전의 확장 목록은 변경 이력 절을 봅니다.

perfstat API 서브루틴은 bos.perf.libperfstat 파일 세트에 속한 libperfstat.a 라이브러리에 있습니다. 이 파일 세트는 AIX 기본 설치 매체에서 설치할 수 있으며, bos.perf.perfstat 파일 세트가 설치되어 있어야 합니다. bos.perf.perfstat에는 커널 확장이 들어 있고 AIX와 함께 자동으로 설치됩니다.

/usr/include/libperfstat.h 파일에는 인터페이스를 부를 때 쓰는 인터페이스 선언과 데이터 구조체 형 정의가 들어 있습니다. 이 포함 파일도 bos.perf.libperfstat 파일 세트에 속합니다. 예제 소스 코드도 bos.perf.libperfstat 파일 세트와 함께 제공되며 /usr/samples/libperfstat 디렉터리에 있습니다.

관련 정보

libperfstat.h 파일

영어 원문

Perfstat API programming

The perfstat application programming interface (API) is a collection of C programming language subroutines that is used in user space. It uses the perfstat kernel extension to extract various AIX performance metrics.

System component information is also retrieved from the Object Data Manager (ODM) and returned with the performance metrics.

The perfstat API is thread–safe, and does not require root authority.

The API supports extensions so binary compatibility is maintained across all releases of.AIX This interface is accomplished by using one of the parameters in all the API calls to specify the size of the data structure to be returned. The interface permits the library to determine the version is use, using the structures that are growing. It helps the user from being dependent on the different versions. For the list of extensions in earlier versions of,AIX see the Change History section.

The perfstat API subroutines are present in the libperfstat.a library that are part of the bos.perf.libperfstat file set, which is installable from the AIX base installation media and requires that the bos.perf.perfstat file set is installed. The latter contains the kernel extension and is automatically installed with.AIX

The /usr/include/libperfstat.h file contains the interface declarations and type definitions of the data structures to use when calling the interfaces. The include file is also part of the bos.perf.libperfstat file set. Sample source code is provided with bos.perf.libperfstat file set and is present in the /usr/samples/libperfstat directory.

Related information

libperfstat.h command

API의 특징

다섯 가지 API가 있습니다. 전역(global) 유형은 구성 요소 집합에 관한 전역 지표를, 개별(individual) 유형은 개별 구성 요소에 관한 지표를 돌려줍니다. 두 유형은 형태(signature)가 비슷하지만 동작이 조금 다릅니다.

(6.1) AIX는 WPAR와 RSET 같은 다른 유형의 API도 지원합니다. WPAR 유형은 워크로드 파티션(WPAR)에 해당하는 구성 요소 집합이나 개별 구성 요소의 사용 지표를 돌려줍니다. RSET 유형은 RSET에 속한 프로세서의 사용 지표를 돌려줍니다. AIX 6.1 TL(Technology Level) 6부터는 NODE라는 새 유형의 API가 생겼습니다. NODE 유형은 클러스터의 원격 노드에 해당하는 구성 요소 집합이나 개별 구성 요소의 사용 지표를 돌려줍니다. (클러스터 환경에서 쓸 수 있는) 원격 노드 통계 수집을 켜려면 perfstat_config(PERFSTAT_ENABLE | PERFSTAT_CLUSTER_STATS, NULL)을 불러야 합니다.

모든 인터페이스는 원래 데이터, 곧 계속 올라가는 카운터 값을 돌려줍니다. 비율을 계산하려면 일정한 간격으로 여러 번 불러야 합니다.

몇몇 인터페이스는 ODM(object data manager) 데이터베이스에서 가져온 데이터를 돌려줍니다. 이 정보는 자동으로 사전(dictionary)에 캐시되며, 한 번 적재되면 "고정"된 것으로 봅니다. 시스템 구성이 바뀔 때마다 perfstat_reset 서브루틴을 불러 사전을 비워야 합니다. 더 골라서 초기화하려면 perfstat_partial_reset 함수를 씁니다. 자세한 것은 "캐시된 지표 인터페이스" 절을 봅니다.

돌려주는 형은 대부분 unsigned long long, 곧 부호 없는 64비트 데이터입니다.

(6.1) 짧은 시간에 perfstat API를 지나치게, 중복해서 부르면 성능에 영향을 줄 수 있습니다. 시간이 많이 드는 통계는 캐시되지 않기 때문입니다.

API 특징의 예는 /usr/samples/libperfstat 디렉터리의 예제 프로그램을 봅니다. 모든 예제 프로그램은 함께 제공되는 makefile(/usr/samples/libperfstat/Makefile.samples)로 컴파일할 수 있습니다.

영어 원문

API characteristics

Five types of APIs are available. Global types return global metrics related to a set of components, while individual types return metrics related to individual components. Both types of interfaces have similar signatures, but slightly different behavior.

AIX supports different types of APIs such as WPAR and RSET. WPAR types return usage metrics related to a set of components or individual components specific to a workload partition (WPAR). RSET types return usage metrics of processors that belong to an RSET. With AIX Version 6.1 Technology Level (TL) 6, a new type of APIs, called as NODE is available. The NODE types return usage metrics that re related to a set of components or individual components specific to a remote node in a cluster. The perfstat_config (PERFSTAT_ENABLE | PERFSTAT_CLUSTER_STATS, NULL) must be used to enable the remote node statistics collection (that is available in a cluster environment).

All the interfaces return raw data; that is, values of running counters. Multiple calls must be made at regular intervals to calculate rates.

Several interfaces return data retrieved from the ODM (object data manager) database. This information is automatically cached into a dictionary that is assumed to be "frozen" after it is loaded. The perfstat_reset subroutine must be called to clear the dictionary whenever the system configuration has changed. In order to do a more selective reset, you can use the perfstat_partial_reset function. For more details, see the Cached metrics interfaces section.

Most types returned are unsigned long long; that is, unsigned 64 bit data.

Excessive and redundant calls to Perfstat APIs in a short time span can have a performance impact because time-consuming statistics collected by them are not cached.

For examples of API characteristics, see the sample programs in the /usr/samples/libperfstat directory. All of the sample programs can be compiled using the provided makefile (/usr/samples/libperfstat/ Makefile.samples).

전역 인터페이스

전역 인터페이스는 시스템의 구성 요소 집합(프로세서, 디스크, 메모리 등)에 관한 지표를 보고합니다.

전역 인터페이스는 다음과 같습니다.

인터페이스 설명
perfstat_cpu_total 전역 프로세서 사용 지표를 가져옵니다.
perfstat_memory_total 전역 메모리 사용 지표를 가져옵니다.
perfstat_disk_total 전역 디스크 사용 지표를 가져옵니다. 참고: WPAR 안에서 실행하는 응용 프로그램에서 부르면 데이터를 돌려주지 않습니다.
perfstat_netinterface_total 전역 네트워크 인터페이스 지표를 가져옵니다. 참고: WPAR 안에서 부르면 데이터를 돌려주지 않습니다.
perfstat_partition_config (6.1) 운영 체제와 파티션 관련 정보를 가져옵니다.
perfstat_partition_total 전역 파티션 지표를 가져옵니다.
perfstat_tape_total 전역 테이프 사용 지표를 가져옵니다. 참고: WPAR 안에서 부르면 데이터를 돌려주지 않습니다.

모든 전역 인터페이스가 쓰는 공통 형태는 다음과 같습니다.

text
int perfstat_subsystem_total(perfstat_id_t *name,
                             perfstat_subsystem_total_t *userbuff,
                             int sizeof_struct,
                             int desired_number);

모든 인터페이스의 매개변수 사용법은 다음과 같습니다.

매개변수 설명
perfstat_id_t *name 나중을 위해 남겨 둔 것. NULL이어야 합니다.
perfstat_subsystem_total_t *userbuff 돌려받을 구조체가 들어갈 공간이 충분한 메모리 영역의 포인터
int sizeof_struct sizeof(perfstat_subsystem_t)로 설정합니다.
int desired_number 나중을 위해 남겨 둔 것. 0이나 1로 설정해야 합니다.

오류가 나면 -1을 돌려줍니다. 그렇지 않으면 복사한 구조체 수를 돌려주며, 늘 1입니다.

다음 절들에서 인터페이스마다 돌려주는 데이터의 종류와 코드 예를 보여 줍니다.

다음 코드는 perfstat_netinterface_total을 쓰는 예입니다.

text
#include <stdio.h>
#include <libperfstat.h>
int main(int argc, char* argv[]) {
    perfstat_netinterface_total_t ninfo;
    int rc;
    rc = perfstat_netinterface_total(NULL, &ninfo, sizeof(perfstat_netinterface_total_t), 1);
    if (rc != 1)
    {
    perror("perfstat_netinterface_total");
    exit(-1);
    }
    perfstat_netinterface_total(NULL, &ninfo, sizeof(perfstat_netinterface_total_t), 1);
    printf("Network interfaces statistics\n");
    printf("-----------------------------\n");
    printf("number of interfaces : %d\n",   ninfo.number);
    printf("\ninput statistics:\n");
    printf("number of packets    : %llu\n", ninfo.ipackets);
    printf("number of errors     : %llu\n", ninfo.ierrors);
    printf("number of bytes      : %llu\n", ninfo.ibytes);
    printf("\noutput statistics:\n");
    printf("number of packets    : %llu\n", ninfo.opackets);
    printf("number of bytes      : %llu\n", ninfo.obytes);
    printf("number of errors     : %llu\n", ninfo.oerrors);
}

이 프로그램은 다음과 비슷한 출력을 냅니다.

text
Network interfaces statistics
-----------------------------
number of interfaces : 2
input statistics:
number of packets    : 306688
number of errors     : 0
number of bytes      : 24852688
output statistics:
number of packets    : 63005
number of bytes      : 11518591
number of errors     : 0

위 프로그램은 ifstat의 동작을 흉내 내며 perfstat_netinterface_total을 쓰는 방법을 보여 줍니다.

영어 원문

Global interfaces

Global interfaces report metrics related to a set of components on a system (such as processors, disks, or memory).

The following are the global interfaces:

  • perfstat_cpu_total — Retrieves global processor usage metrics
  • perfstat_memory_total — Retrieves global memory usage metrics
  • perfstat_disk_total — Retrieves global disk usage metrics Note: This API does not return any data when started from an application running inside WPAR.
  • perfstat_netinterface_total — Retrieves global network interfaces metrics Note: This API does not return any data when started from an application running inside WPAR.
  • perfstat_partition_config — Retrieves Operating System and partition related information
  • perfstat_partition_total — Retrieves global partition metrics
  • perfstat_tape_total — Retrieves global tape usage metrics Note: This API does not return any data when started from an application running inside WPAR.

The common signature used by all of the global interfaces is as follows:

text
int perfstat_subsystem_total(perfstat_id_t *name,
                             perfstat_subsystem_total_t *userbuff,
                             int sizeof_struct,
                             int desired_number);

The usage of the parameters for all of the interfaces is as follows:

  • perfstat_id_t *name — Reserved for future use, must be NULL
  • perfstat_subsystem_total_t *userbuff — A pointer to a memory area with enough space for the returned structure
  • int sizeof_struct — Should be set to sizeof(perfstat_subsystem_t)
  • int desired_number — Reserved for future use, must be set to 0 or 1

The return value is -1 in case of errors. Otherwise, the number of structures copied is returned. This is always 1.

The following sections provide examples of the type of data returned and code using each of the interfaces.

The following code shows an example of how perfstat_netinterface_total is used:

(24줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The program produces output similar to the following:

text
Network interfaces statistics
-----------------------------
number of interfaces : 2
input statistics:
number of packets    : 306688
number of errors     : 0
number of bytes      : 24852688
output statistics:
number of packets    : 63005
number of bytes      : 11518591
number of errors     : 0

The preceding program emulates ifstat's behavior and also shows how perfstat_netinterface_total is used.

perfstat_cpu_total 인터페이스

perfstat_cpu_total 인터페이스는 libperfstat.h 파일에 정의된 perfstat_cpu_total_t 구조체를 돌려줍니다.

perfstat_cpu_total_t 구조체의 주요 필드는 다음과 같습니다.

필드 설명
purr_coalescing (6.1) 호출한 파티션이 풀 전체 통계를 볼 권한이 있으면 병합(coalescing) 데이터에 쓴 PURR 사이클, 없으면 0
spurr_coalescing (6.1) 호출한 파티션이 풀 전체 통계를 볼 권한이 있으면 병합 데이터에 쓴 SPURR 사이클, 없으면 0
processorHz 프로세서 속도(Hz, ODM에서)
description 프로세서 종류(ODM에서)
ncpus 현재 활성 프로세서 수
ncpus_cfg 구성된 프로세서 수. 곧 이 AIX가 동시에 다룰 수 있는 최대 프로세서 수
ncpus_high 최대 활성 프로세서 수. 곧 마지막 재부팅 이후 활성 프로세서 수의 최댓값
user 사용자 모드에서 쓴 클록 틱 수
sys 시스템(커널) 모드에서 쓴 클록 틱 수
idle 대기 중인 I/O 없이 유휴 상태로 쓴 클록 틱 수
wait 대기 중인 I/O가 있는 채 유휴 상태로 쓴 클록 틱 수

참고: 페이지 병합(page coalescing)은 하이퍼바이저가 중복 페이지를 찾아 모든 사용자 읽기를 사본 하나로 보내고 나머지 중복 물리 메모리 페이지를 회수하는 작업으로, 사용자는 알아채지 못합니다.

이 밖에도 프로세서 관련 카운터(시스템 호출 수, 읽기·쓰기 수, fork·exec 수, 부하 평균 등)를 돌려줍니다. 전체 목록은 libperfstat.h 헤더 파일의 perfstat_cpu_total_t 부분을 봅니다.

다음 프로그램은 lparstat의 동작을 흉내 내며 perfstat_cpu_total 인터페이스를 쓰는 방법을 보여 줍니다.

text
#include <stdio.h>
#include <sys/time.h>
#include <sys/errno.h>
#include <sys/proc.h>
#include <wpars/wparcfg.h>
#include <libperfstat.h>
#include <stdlib.h>
/* default values for interval and count */
#define INTERVAL_DEFAULT  1
#define COUNT_DEFAULT     1
/* values for wpar status */
#define ACTIVE     0
#define NOTACTIVE   1
/* Check value returned by malloc for NULL */
#define CHECK_FOR_MALLOC_NULL(X) {  if ((X) == NULL) {\
                                       perror ("malloc");\
                                       exit(2);\
                                        }\
                                  }
/* Non zero WPAR ID indicates WPAR */
#define IS_WPAR(X) ((X))
 /* stores wpar id for perfstat library */
perfstat_id_wpar_t     wparid;
perfstat_wpar_total_t  wparinfo;
perfstat_wpar_total_t *wparlist;
 /*Corral id for WPAR */
cid_t cid;
int interval = INTERVAL_DEFAULT, count = COUNT_DEFAULT;
int totalwpar, activewpar;   /* to store and number of wpars available and active wpars */
/*
 *Name: do_cleanup
 *      free all allocated data structures
 */
void do_cleanup(void)
{
   if (wparlist)
       free(wparlist);
}
/*
 *Name: display_global_sysinfo_stat
 *      Function used when called from global.
 *      Gets all the system metrics using perfstat APIs and displays them
 *
 */
void display_global_sysinfo_stat(void)
{
   perfstat_cpu_total_t *cpustat,*cpustat_last;
   perfstat_id_t first;
   /* allocate memory for data structures and check for any error */
   cpustat = (perfstat_cpu_total_t *)malloc(sizeof(perfstat_cpu_total_t));
   CHECK_FOR_MALLOC_NULL(cpustat);
   cpustat_last = (perfstat_cpu_total_t *)malloc(sizeof(perfstat_cpu_total_t));
   CHECK_FOR_MALLOC_NULL(cpustat_last);
   /* get the system wide statistics */
   if (perfstat_cpu_total(NULL , cpustat_last, sizeof(perfstat_cpu_total_t), 1) <= 0){
       perror("perfstat_cpu_total ");
       exit(1);
   }
   printf ("%10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s\n", "cswch", "scalls", "sread", "swrite", "fork", "exec",
       "rchar", "wchar", "deviceint", "bwrite", "bread", "phread");
   printf ("%10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s\n", "=====", "======", "=====", "======", "====", "====",
       "=====", "=====", "=========", "======", "=====", "======");
   while (count > 0){
       sleep(interval);
       if (perfstat_cpu_total(NULL ,cpustat, sizeof(perfstat_cpu_total_t), 1) <= 0){
           perror("perfstat_cpu_total ");
           exit(1);
       }
       /* print the difference between the old structure and new structure */
       printf("%10llu %10llu %10llu %10llu %10llu %10llu %10llu %10llu %10llu %10llu %10llu %10llu\n",(cpustat->pswitch - cpustat_last->pswitch),
                                                         (cpustat->syscall - cpustat_last->syscall), (cpustat->sysread - cpustat_last->sysread ),
                                                         (cpustat->syswrite - cpustat_last->syswrite),(cpustat->sysfork - cpustat_last->sysfork),
        (cpustat->sysexec - cpustat_last->sysexec ), (cpustat->readch - cpustat_last->readch),
        (cpustat->writech - cpustat_last->writech ),(cpustat->devintrs - cpustat_last->devintrs),
                                                         (cpustat->bwrite - cpustat_last->bwrite), (cpustat->bread - cpustat_last->bread ),
                                                         (cpustat->phread - cpustat_last->phread ));
       count--;
       /*copy the present structure to the old structure */
       memcpy(cpustat_last , cpustat , sizeof(perfstat_cpu_total_t));
   }
   /* free the memory allocated for the data structures */
   free(cpustat);
   free(cpustat_last);
}
/*
 *Name: display_wpar_sysinfo_stat
 *      Displays both wpar and global metrics
 *
 */
void display_wpar_sysinfo_stat(void)
{
   perfstat_wpar_total_t wparinfo;
   perfstat_cpu_total_wpar_t cinfo_wpar, cinfo_wpar_last;
   perfstat_cpu_total_t sysinfo, sysinfo_last;
   /* ste the spec and pass the wparname */
   wparid.spec = WPARNAME;
   strcpy(wparid.u.wparname, NULL);
   /* save the number of wpars which are active */
   activewpar = perfstat_wpar_total( NULL , &wparinfo ,sizeof(perfstat_wpar_total_t), 1);
   /* if the activewpar is less than zero exit with a perror */
   if (activewpar < 0){
       perror("perfstat_wpar_total :");
       exit(1);
   }
   /* if the wpar is not active exit with a message */
   if (activewpar == 0){
       printf("wpar not active \n");
       exit(1);
   }
   /* get the wpar wide cpu information */
   if (perfstat_cpu_total_wpar(NULL, &cinfo_wpar_last, sizeof(perfstat_cpu_total_wpar_t), 1) <=0){
       perror("perfstat_cpu_total_wpar :");
       exit(1);
   }
   if (perfstat_cpu_total(NULL , &sysinfo_last, sizeof(perfstat_cpu_total_t), 1) <=0){
       perror("perfstat_cpu_total_wpar :");
       exit(1);
   }
   printf("%10s %10s %10s %10s %10s %10s %10s %10s\n","wparname ", "cswch" , "syscalls", "fork","runque", "swpque", "runocc", "swpocc" );
   printf("%10s %10s %10s %10s %10s %10s %10s %10s\n","======== ", "=====" , "========", "====","======", "======", "======", "======" );
   while (count > 0){
       sleep(interval);
       if (perfstat_cpu_total_wpar( NULL,&cinfo_wpar,  sizeof(perfstat_cpu_total_wpar_t), 1) <=0){
           perror("perfstat_cpu_total_wpar :");
           exit(1);
       }
       if (perfstat_cpu_total(NULL, &sysinfo, sizeof(perfstat_cpu_total_t), 1) <=0){
           perror("perfstat_cpu_total :");
           exit(1);
       }
       /* display the difference between the current and old structure for the current wpar and system wide values*/
       printf("%10s %10llu %10llu %10llu %10llu %10llu %10llu %10llu\n",wparinfo.name, (cinfo_wpar.pswitch - cinfo_wpar_last.pswitch),
    (cinfo_wpar.syscall - cinfo_wpar_last.syscall), (cinfo_wpar.sysfork - cinfo_wpar_last.sysfork),
    (cinfo_wpar.runque - cinfo_wpar_last.runque), (cinfo_wpar.swpque - cinfo_wpar_last.swpque),
    (cinfo_wpar.runocc - cinfo_wpar_last.runocc), (cinfo_wpar.swpocc - cinfo_wpar_last.swpocc));
       printf("%10s %10llu %10llu %10llu %10llu %10llu %10llu %10llu\n\n", "Global", (sysinfo.pswitch - sysinfo_last.pswitch),
    (sysinfo.syscall - sysinfo_last.syscall), (sysinfo.sysfork - sysinfo_last.sysfork),
    (sysinfo.runque - sysinfo_last.runque), (sysinfo.swpque - sysinfo_last.swpque),
    (sysinfo.runocc - sysinfo_last.runocc), (sysinfo.swpocc - sysinfo_last.swpocc));
       count--;
       /* copy the data to the old structure */
       memcpy(&cinfo_wpar_last, &cinfo_wpar, sizeof(perfstat_wpar_total_t));
       memcpy(&sysinfo_last , &sysinfo , sizeof(perfstat_cpu_total_t));
   }
}
/* Name: display_wpar_total_sysinfo_stat
 *       displays statistics of individual wpar
 *
 */
int display_wpar_total_sysinfo_stat(void)
{
   int i, *status;
   perfstat_wpar_total_t *wparinfo;
   perfstat_cpu_total_wpar_t *cinfo_wpar, *cinfo_wpar_last;
   /* allocate memory for the datastructures and check for any error */
   status = (int *) calloc(totalwpar ,sizeof(int));
   CHECK_FOR_MALLOC_NULL(status);
   cinfo_wpar = (perfstat_cpu_total_wpar_t *) malloc(sizeof (perfstat_cpu_total_wpar_t) * totalwpar);
   CHECK_FOR_MALLOC_NULL(cinfo_wpar);
   cinfo_wpar_last = (perfstat_cpu_total_wpar_t *) malloc(sizeof (perfstat_cpu_total_wpar_t) * totalwpar);
   CHECK_FOR_MALLOC_NULL(cinfo_wpar_last);
   wparlist = (perfstat_wpar_total_t *) malloc(sizeof(perfstat_wpar_total_t) * totalwpar);
   CHECK_FOR_MALLOC_NULL(wparlist);
   activewpar = perfstat_wpar_total(&wparid, wparlist, sizeof(perfstat_wpar_total_t), totalwpar);
   if (activewpar < 0){
       perror("perfstat_wpar_total :");
       exit(1);
   }
   /* If no active wpars exit with a message */
   if (activewpar == 0){
       printf("no active wpars found \n");
       exit(1);
   }
   for (i = 0; i < activewpar; i++){
        /* copy the wparname into wparid and collect the data for all active wpars */
        strcpy(wparid.u.wparname, wparlist[i].name);
        if (perfstat_cpu_total_wpar(&wparid, &cinfo_wpar_last[i], sizeof(perfstat_cpu_total_wpar_t), 1) <= 0){
            status[i] = NOTACTIVE;
            continue;
        }
   }
   /*print the headers */
   printf("%20s %12s %12s %12s %12s %12s %12s %12s\n","wparname", "cswitch", "fork", "runque", "swpque", "runocc", "swpocc", "syscalls");
   printf("%20s %12s %12s %12s %12s %12s %12s %12s\n","========", "=======", "====", "======", "======", "======", "======", "========");
   while (count > 0){
         sleep(interval);
         for (i = 0; i < activewpar; i++){
              strcpy(wparid.u.wparname, wparlist[i].name);
              if (perfstat_cpu_total_wpar(&wparid, &cinfo_wpar[i], sizeof(perfstat_cpu_total_wpar_t), 1) <= 0){
                  status[i] = NOTACTIVE;
                  continue;
              }
         }
  /* print the data for all active wpars */
         for (i = 0; i < activewpar; i++){
              if(status[i] == ACTIVE)
              printf("%20s %12llu %12llu %12llu %12llu %12llu %12llu %12llu\n", wparlist[i].name,
   (cinfo_wpar[i].pswitch - cinfo_wpar_last[i].pswitch), (cinfo_wpar[i].sysfork - cinfo_wpar_last[i].sysfork),
   (cinfo_wpar[i].runque - cinfo_wpar_last[i].runque), (cinfo_wpar[i].swpque - cinfo_wpar_last[i].swpque),
   (cinfo_wpar[i].runocc - cinfo_wpar_last[i].runocc), (cinfo_wpar[i].swpocc - cinfo_wpar_last[i].swpocc),
   (cinfo_wpar[i].syscall- cinfo_wpar_last[i].syscall));
         }
         printf("\n");
         count--;
         memcpy(cinfo_wpar_last,cinfo_wpar,(totalwpar * sizeof(perfstat_cpu_total_wpar_t)));
   }
   /* free all the memory structures */
   free(cinfo_wpar);
   free(cinfo_wpar_last);
   free(status);
}
/*
 *Name: showusage
 *      displays the usage message
 *
 */
void showusage()
{
   if (!cid)
       printf("Usage:simplesysinfo [-@ { ALL | WPARNAME }] [interval] [count]\n ");
   else
       printf("Usage:simplesysinfo [interval] [count]\n");
   exit(1);
}
/* NAME: main
 *       This function determines the interval, iteration count.
 *       Then it calls the corresponding functions to display
 *       the corresponding metrics
 */
int main(int argc, char* argv[])
{
   int rc ,atflag = 0, c;
   char wpar[MAXCORRALNAMELEN+1];
   strcpy(wpar, NULL);
   cid = corral_getcid();
   while((c = getopt(argc, argv, "@:"))!= EOF){
        if (c == ’@’){
            if (IS_WPAR(cid))
                showusage();
            atflag = 1;
            strcpy(wpar, optarg);
        }
   }
   argc -= optind;
   argv += optind;
   if (argc > 2)
       showusage();
   if (argc){
       if ((interval = atoi(argv[0])) <= 0)
           showusage();
       argc--;
   }
   if (argc){
       if ((count = atoi(argv[1])) <= 0)
           showusage();
   }
 /* If no -@ flag call display_global_sysinfo_stat function */
   if (!atflag ){
       if (!cid)
           /*display global values */
           display_global_sysinfo_stat();
       else
           /* display wpar values */
           display_wpar_sysinfo_stat();
   }
   else{
       /* if the argument to -@ is not ALL set the totalwpars to 1 */
       if (strcmp(wpar, "ALL")) {
           strcpy(wparid.u.wparname, wpar);
           wparid.spec = WPARNAME;
           totalwpar = 1;
       }
       else{
    totalwpar = perfstat_wpar_total(NULL, NULL, sizeof(perfstat_wpar_total_t), 0);
           if (totalwpar < 0){
               perror("perfstat_wpar_total : ");
               exit(1);
           }
           if (totalwpar == 0){
               printf("No wpars found");
               exit(1);
           }
           wparid.spec = WPARNAME;
           strcpy(wparid.u.wparname, NULL);
      }
      display_wpar_total_sysinfo_stat();
   }
   do_cleanup();
   return(0);
}

이 프로그램은 다음과 비슷한 출력을 냅니다.

text
cswch     scalls      sread     swrite       fork       exec      rchar      wchar  deviceint     bwrite      bread     phread
=====     ======      =====     ======       ====       ====      =====      =====  =========     ======      =====     ======
 83        525        133          2          0          1       1009462      264      27           0           0          0
영어 원문

perfstat_cpu_total Interface

The perfstat_cpu_total interface returns a perfstat_cpu_total_t structure, which is defined in the libperfstat.h file.

Selected fields from the perfstat_cpu_total_t structure include:

  • purr_coalescing — PURR cycles consumes coalescing data if the calling partition is authorized to see pool wide statistics, else set to zero.
  • spurr_coalescing — SPURR cycles consumes coalescing data if the calling partition is authorized to see pool wide statistics, else set to zero.
  • processorHz — Processor speed in Hertz (from ODM)
  • description — Processor type (from ODM)
  • CPUs — Current number of active processors
  • ncpus_cfg — Number of configured processors; that is, the maximum number of processors that this copy of AIX can handle simultaneously
  • ncpus_high — Maximum number of active processors; that is, the maximum number of active processors since the last reboot
  • user — Number of clock ticks spent in user mode
  • sys — Number of clock ticks spent in system (kernel) mode
  • idle — Number of clock ticks spent idle with no I/O pending
  • wait — Number of clock ticks spent idle with I/O pending
  • Note: Page coalescing is a transparent operation wherein the hypervisor detects duplicate pages, directs

all user reads to a single copy, and reclaims the other duplicate physical memory pages. Several other processor-related counters (such as number of system calls, number of reads, write, forks, execs, and load average) are also returned. For a complete list, see the perfstat_cpu_total_t section of the libperfstat.h header file.

The following program emulates lparstat's behavior and also shows an example of how the

perfstat_cpu_total interface is used

(290줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The program displays an output that is similar to the following example output:

text
cswch     scalls      sread     swrite       fork       exec      rchar      wchar  deviceint     bwrite      bread     phread
=====     ======      =====     ======       ====       ====      =====      =====  =========     ======      =====     ======
 83        525        133          2          0          1       1009462      264      27           0           0          0

perfstat_memory_total 인터페이스

perfstat_memory_total 인터페이스는 libperfstat.h 파일에 정의된 perfstat_memory_total_t 구조체를 돌려줍니다.

perfstat_memory_total_t 구조체의 주요 필드는 다음과 같습니다.

필드 설명
bytes_coalesced (6.1) 호출한 파티션의 논리 실메모리 가운데 병합된 바이트 수
bytes_coalesced_mempool (6.1) 호출한 파티션이 풀 전체 통계를 볼 권한이 있으면 그 파티션이 속한 메모리 풀에서 병합된 논리 실메모리 바이트 수, 없으면 0
virt_total 가상 메모리 양(4KB 페이지 단위)
real_total 실메모리 양(4KB 페이지 단위)
real_free 사용 가능한 실메모리 양(4KB 페이지 단위)
real_pinned 고정(pinned) 메모리 양(4KB 페이지 단위)
pgins 페이지 인된 페이지 수
pgouts 페이지 아웃된 페이지 수
pgsp_total 전체 페이징 공간 양(4KB 페이지 단위)
pgsp_free 사용 가능한 페이징 공간 양(4KB 페이지 단위)
pgsp_rsvd 예약된 페이징 공간 양(4KB 페이지 단위)

참고: 페이지 병합은 하이퍼바이저가 중복 페이지를 찾아 모든 사용자 읽기를 사본 하나로 보내고 나머지 중복 물리 메모리 페이지를 회수할 수 있는 작업으로, 사용자는 알아채지 못합니다.

이 밖에도 메모리 관련 지표(페이징 공간에서 페이지 인·아웃된 양, 시스템 메모리 양 등)를 돌려줍니다. 전체 목록은 Files Reference의 libperfstat.h 헤더 파일에서 perfstat_memory_total_t 부분을 봅니다.

다음 프로그램은 vmstat의 동작을 흉내 내며 perfstat_memory_total 인터페이스를 쓰는 방법을 보여 줍니다.

text
#include <stdio.h>
#include <libperfstat.h>
int main(int argc, char* argv[]) {
    perfstat_memory_total_t minfo;
    int rc;
    rc = perfstat_memory_total(NULL, &minfo, sizeof(perfstat_memory_total_t), 1);
    if (rc != 1) {
        perror("perfstat_memory_total");
        exit(-1);
    }
    printf("Memory statistics\n");
    printf("-----------------\n");
    printf("real memory size                 : %llu MB\n",
           minfo.real_total*4096/1024/1024);
    printf("reserved paging space            : %llu MB\n",minfo.pgsp_rsvd);
    printf("virtual memory size              : %llu MB\n",
           minfo.virt_total*4096/1024/1024);
    printf("number of free pages             : %llu\n",minfo.real_free);
    printf("number of pinned pages           : %llu\n",minfo.real_pinned);
    printf("number of pages in file cache    : %llu\n",minfo.numperm);
    printf("total paging space pages         : %llu\n",minfo.pgsp_total);
    printf("free paging space pages          : %llu\n", minfo.pgsp_free);
    printf("used paging space                : %3.2f%%\n",
        (float)(minfo.pgsp_total-minfo.pgsp_free)*100.0/
        (float)minfo.pgsp_total);
    perfstat_memory_total(NULL, &minfo, sizeof(perfstat_memory_total_t), 1);
    printf("Memory statistics\n");
    printf("-----------------\n");
    printf("real memory size                 : %llu MB\n",
           minfo.real_total*4096/1024/1024);
    printf("reserved paging space            : %llu MB\n",minfo.pgsp_rsvd);
    printf("virtual memory size              : %llu MB\n",
           minfo.virt_total*4096/1024/1024);
    printf("number of free pages             : %llu\n",minfo.real_free);
    printf("number of pinned pages           : %llu\n",minfo.real_pinned);
    printf("number of pages in file cache    : %llu\n",minfo.numperm);
    printf("total paging space pages         : %llu\n",minfo.pgsp_total);
    printf("free paging space pages          : %llu\n", minfo.pgsp_free);
    printf("used paging space                : %3.2f%%\n",
        (float)(minfo.pgsp_total-minfo.pgsp_free)*100.0/
        (float)minfo.pgsp_total);
    printf("number of paging space page ins  : %llu\n",minfo.pgspins);
    printf("number of paging space page outs : %llu\n",minfo.pgspouts);
    printf("number of page ins               : %llu\n",minfo.pgins);
    printf("number of page outs              : %llu\n",minfo.pgouts);
}

이 프로그램은 다음과 같은 출력을 냅니다.

text
Memory statistics
-----------------
real memory size                 : 256 MB
reserved paging space            : 512 MB
virtual memory size              : 768 MB
number of free pages             : 32304
number of pinned pages           : 6546
number of pages in file cache    : 12881
total paging space pages         : 131072
free paging space pages          : 129932
used paging space                : 0.87%
number of paging space page ins  : 0
number of paging space page outs : 0
number of page ins               : 20574
number of page outs              : 92508
영어 원문

perfstat_memory_total Interface

The perfstat_memory_total interface returns a perfstat_memory_total_t structure, which is defined in the libperfstat.h file.

Selected fields from the perfstat_memory_total_t structure include:

  • bytes_coalesced — Number of bytes of the calling partition’s logical real memory coalesced
  • bytes_coalesced_mempool — Number of bytes of logical real memory coalesced in the calling partition’s memory pool if the calling partition is authorized to see pool wide statistics else, set to zero.
  • virt_total — Amount of virtual memory (in units of 4 KB pages)
  • real_total — Amount of real memory (in units of 4 KB pages)
  • real_free — Amount of free real memory (in units of 4 KB pages)
  • real_pinned — Amount of pinned memory (in units of 4 KB pages)
  • pgins — Number of pages paged in
  • pgouts — Number of pages paged out
  • pgsp_total — Total amount of paging space (in units of 4 KB pages)
  • pgsp_free — Amount of free paging space (in units of 4 KB pages)
  • pgsp_rsvd — Amount of reserved paging space (in units of 4 KB pages)
  • Note: Page coalescing is a transparent operation wherein the hypervisor detects duplicate pages, directs

all user reads to a single copy, and can reclaim other duplicate physical memory pages. Several other memory-related metrics (such as amount of paging space paged in and out, and amount of system memory) are also returned. For a complete list, see the perfstat_memory_total_t section of the libperfstat.h header file in Files Reference.

The preceding program emulates vmstat's behavior and also shows an example of how the

perfstat_memory_total interface is used

(46줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The preceding program produces output such as the following:

(15줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The preceding program emulates vmstat's behavior and also shows how perfstat_memory_total is used.

perfstat_disk_total 인터페이스

perfstat_disk_total 인터페이스는 libperfstat.h 파일에 정의된 perfstat_disk_total_t 구조체를 돌려줍니다.

perfstat_disk_total_t 구조체의 주요 필드는 다음과 같습니다.

필드 설명
number 디스크 수
size 전체 디스크 크기(MB)
free 전체 빈 디스크 공간(MB)
xfers 디스크와 주고받은 전체 전송(KB)

이 밖에도 디스크 관련 지표(디스크에서 읽고 쓴 블록 수 등)를 돌려줍니다. 전체 목록은 Files Reference의 libperfstat.h 헤더 파일에서 perfstat_disk_total_t 부분을 봅니다.

다음 코드는 perfstat_disk_total을 쓰는 예입니다.

text
#include <stdio.h>
#include <libperfstat.h>
int main(int argc, char* argv[]) {
    perfstat_disk_total_t dinfo;
    int rc;
    rc = perfstat_disk_total(NULL, &dinfo, sizeof(perfstat_disk_total_t), 1);
    if (rc != 1)
    {
 perror("perfstat_disk_total");
        exit(-1);
    }
    perfstat_disk_total(NULL, &dinfo, sizeof(perfstat_disk_total_t), 1);
    printf("Total disk statistics\n");
    printf("---------------------\n");
    printf("number of  disks         : %d\n",   dinfo.number);
    printf("total disk space         : %llu\n", dinfo.size);
    printf("total free space         : %llu\n", dinfo.free);
    printf("number of transfers      : %llu\n", dinfo.xfers);
    printf("number of blocks written : %llu\n", dinfo.wblks);
    printf("number of blocks read    : %llu\n", dinfo.rblks);
}

이 프로그램은 다음과 같은 출력을 냅니다.

text
Total disk statistics
---------------------
number of  disks         : 3
total disk space         : 4296
total free space         : 2912
number of transfers      : 77759
number of blocks written : 738016
number of blocks read    : 363120

위 프로그램은 iostat의 동작을 흉내 내며 perfstat_disk_total을 쓰는 방법을 보여 줍니다.

영어 원문

perfstat_disk_total Interface

The perfstat_disk_total interface returns a perfstat_disk_total_t structure, which is defined in the libperfstat.h file.

Selected fields from the perfstat_disk_total_t structure include:

  • number — Number of disks
  • size — Total disk size (in MB)
  • free — Total free disk space (in MB)
  • xfers — Total transfers to and from disk (in KB)

Several other disk-related metrics, such as number of blocks read from and written to disk, are also returned. For a complete list, see the perfstat_disk_total_t section in the libperfstat.h header file in Files Reference.

The following code shows an example of how perfstat_disk_total is used:

(21줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

This program produces output such as the following:

text
Total disk statistics
---------------------
number of  disks         : 3
total disk space         : 4296
total free space         : 2912
number of transfers      : 77759
number of blocks written : 738016
number of blocks read    : 363120

The preceding program emulates iostat's behavior and also shows how perfstat_disk_total is used.

perfstat_netinterface_total 인터페이스

perfstat_netinterface_total 인터페이스는 libperfstat.h 파일에 정의된 perfstat_netinterface_total_t 구조체를 돌려줍니다.

perfstat_netinterface_total_t 구조체의 주요 필드는 다음과 같습니다.

필드 설명
number 네트워크 인터페이스 수
ipackets 모든 네트워크 인터페이스에서 받은 입력 패킷의 전체 수
opackets 모든 네트워크 인터페이스로 보낸 출력 패킷의 전체 수
ierrors 모든 네트워크 인터페이스의 입력 오류 전체 수
oerrors 모든 네트워크 인터페이스의 출력 오류 전체 수

이 밖에도 네트워크 인터페이스 관련 지표(보내고 받은 바이트 수 등)를 돌려줍니다. 전체 목록은 Files Reference의 libperfstat.h 헤더 파일에서 perfstat_netinterface_total_t 부분을 봅니다.

영어 원문

perfstat_netinterface_total Interface

The perfstat_netinterface_total interface returns a perfstat_netinterface_total_t structure, which is defined in the libperfstat.h file.

Selected fields from the perfstat_netinterface_total_t structure include:

  • number — Number of network interfaces
  • ipackets — Total number of input packets received on all network interfaces
  • opackets — Total number of output packets sent on all network interfaces
  • ierror — Total number of input errors on all network interfaces
  • oerror — Total number of output errors on all network interfaces

Several other network interface-related metrics (such as number of bytes sent and received). For a complete list, see the perfstat_netinterface_total_t section in the libperfstat.h header file in Files Reference.

perfstat_partition_total 인터페이스

perfstat_partition_total 인터페이스는 libperfstat.h 파일에 정의된 perfstat_partition_total_t 구조체를 돌려줍니다.

perfstat_partition_total_t 구조체의 주요 필드는 다음과 같습니다.

필드 설명
purr_coalescing (6.1) 호출한 파티션이 풀 전체 통계를 볼 권한이 있으면 병합 데이터에 쓴 PURR 사이클, 없으면 0
spurr_coalescing (6.1) 호출한 파티션이 풀 전체 통계를 볼 권한이 있으면 병합 데이터에 쓴 SPURR 사이클, 없으면 0
type 파티션 종류
online_cpus 지금 파티션에 할당된 가상 프로세서 수
online_memory 지금 파티션에 할당된 메모리 양

참고: 페이지 병합은 하이퍼바이저가 중복 페이지를 찾아 모든 사용자 읽기를 사본 하나로 보내고 중복 물리 메모리 페이지를 회수하는 작업으로, 사용자는 알아채지 못합니다.

전체 목록은 libperfstat.h 헤더 파일의 perfstat_partition_total_t 부분을 봅니다.

다음 코드는 perfstat_partition_total 함수를 쓰는 예입니다.

다음 예는 lparstat -i 명령을 흉내 냅니다.

text
#include <stdio.h>
#include <stdlib.h>
#include <libperfstat.h>
int main(int argc, char* argv[])
{
    perfstat_partition_total_t pinfo;
    int rc;
    rc = perfstat_partition_total(NULL, &pinfo, sizeof(perfstat_partition_total_t), 1);
    if (rc != 1) {
    perror("Error in perfstat_partition_total");
    exit(-1);
    }
    printf("Partition Name                 : %s\n", pinfo.name);
    printf("Partition Number               : %u\n", pinfo.lpar_id);
    printf("Type                           : %s\n", pinfo.type.b.shared_enabled ? "Shared" : "Dedicated");
    printf("Mode                           : %s\n", pinfo.type.b.donate_enabled ? "Donating" :
                                                    pinfo.type.b.capped ? "Capped" : "Uncapped");
    printf("Entitled Capacity              : %u\n", pinfo.entitled_proc_capacity);
    printf("Partition Group-ID             : %u\n", pinfo.group_id);
    printf("Shared Pool ID                 : %u\n", pinfo.pool_id);
    printf("Online Virtual CPUs            : %u\n", pinfo.online_cpus);
    printf("Maximum Virtual CPUs           : %u\n", pinfo.max_cpus);
    printf("Minimum Virtual CPUs           : %u\n", pinfo.min_cpus);
    printf("Online Memory                  : %llu MB\n", pinfo.online_memory);
    printf("Maximum Memory                 : %llu MB\n", pinfo.max_memory);
    printf("Minimum Memory                 : %llu MB\n", pinfo.min_memory);
    printf("Variable Capacity Weight       : %u\n", pinfo.var_proc_capacity_weight);
    printf("Minimum Capacity               : %u\n", pinfo.min_proc_capacity);
    printf("Maximum Capacity               : %u\n", pinfo.max_proc_capacity);
    printf("Capacity Increment             : %u\n", pinfo.proc_capacity_increment);
    printf("Maximum Physical CPUs in system: %u\n", pinfo.max_phys_cpus_sys);
    printf("Active Physical CPUs in system : %u\n", pinfo.online_phys_cpus_sys);
    printf("Active CPUs in Pool            : %u\n", pinfo.phys_cpus_pool);
    printf("Unallocated Capacity           : %u\n", pinfo.unalloc_proc_capacity);
    printf("Physical CPU Percentage        : %4.2f%%\n",
           (double)pinfo.entitled_proc_capacity / (double)pinfo.online_cpus);
    printf("Unallocated Weight             : %u\n", pinfo.unalloc_var_proc_capacity_weight);
}

이 프로그램은 다음과 비슷한 출력을 냅니다.

text
Partition Name                 : perfdev10
Partition Number               : 23
Type                           : Shared
Mode                           : Capped
Entitled Capacity              : 100
Partition Group-ID             : 32791
Shared Pool ID                 : 0
Online Virtual CPUs            : 2
Maximum Virtual CPUs           : 4
Minimum Virtual CPUs           : 1
Online Memory                  : 4096 MB
Maximum Memory                 : 8192 MB
Minimum Memory                 : 2048 MB
Variable Capacity Weight       : 0
Minimum Capacity               : 100
Maximum Capacity               : 400
Capacity Increment             : 1
Maximum Physical CPUs in system: 64
Active Physical CPUs in system : 64
Active CPUs in Pool            : 59
Unallocated Capacity           : 0
Physical CPU Percentage        : 50.00%
Unallocated Weight             : 0

다음 예는 lparstat 명령의 기본 모드를 흉내 냅니다.

text
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libperfstat.h>
#include <sys/systemcfg.h>
#define XINTFRAC ((double)(_system_configuration.Xint)/(double)(_system_configuration.Xfrac))
/* convert physical processor tics to seconds */
#define HTIC2SEC(x) ((double)x * XINTFRAC)/(double)1000000000.0
#define INTERVAL_DEFAULT   2
#define COUNT_DEFAULT    10
/*simplelparstat.c file can be used in two modes:-
1) Auto Mode:It makes use of perfstat_cpu_util API to calculate utilization values,enable ’UTIL_AUTO’ macro for execution in auto mode.
2) Manual Mode: Calculations are done in the current code.
*/
/*#define UTIL_AUTO     1*/
#ifdef  UTIL_AUTO
 #define UTIL_MS 1
 #define UTIL_PCT 0
 #define UTIL_CORE 2
 #define UTIL_PURR 0
 #define UTIL_SPURR 1
 void display_lpar_util_auto(int mode,int cpumode,int count,int interval);
#endif
static int disp_util_header = 1;
static u_longlong_t last_time_base;
static u_longlong_t last_pcpu_user, last_pcpu_sys, last_pcpu_idle, last_pcpu_wait;
static u_longlong_t last_lcpu_user, last_lcpu_sys, last_lcpu_idle, last_lcpu_wait;
static u_longlong_t last_busy_donated, last_idle_donated;
static u_longlong_t last_busy_stolen, last_idle_stolen;
static u_longlong_t last_phint = 0, last_vcsw = 0, last_pit = 0;
/* support for remote node statistics collection in a cluster environment */
perfstat_id_node_t nodeid;
static char nodename[MAXHOSTNAMELEN] = "";
static int collect_remote_node_stats = 0;
void display_lpar_util(void);
int main(int argc, char* argv[])
{
    int interval = INTERVAL_DEFAULT;
    int count = COUNT_DEFAULT;
    int i, rc;
    char *optlist = "i:c:n:";
    int mode=0,cpumode=0;
    /* Process the arguments */
    while ((i = getopt(argc, argv, optlist)) != EOF)
    {
        switch(i)
        {
            case ’i’:               /* Interval */
                     interval = atoi(optarg);
                     if( interval <= 0 )
                         interval = INTERVAL_DEFAULT;
                     break;
            case ’c’:               /* Number of interations */
                     count = atoi(optarg);
                     if( count <= 0 )
                         count = COUNT_DEFAULT;
                     break;
            case ’n’:               /* Node name in a cluster environment */
                     strncpy(nodename, optarg, MAXHOSTNAMELEN);
                     nodename[MAXHOSTNAMELEN-1] = ’\0’;
                     collect_remote_node_stats = 1;
                     break;
            default:
                    /* Invalid arguments. Print the usage and terminate */
                    fprintf (stderr, "usage: %s [-i <interval in seconds> ] [-c <number of iterations> ] [-n <node name in the cluster> ]\n", argv[0]);
                    return(-1);
        }
    }
    if(collect_remote_node_stats)
    {   /* perfstat_config needs to be called to enable cluster statistics collection */
        rc = perfstat_config(PERFSTAT_ENABLE|PERFSTAT_CLUSTER_STATS, NULL);
        if (rc == -1)
        {
            perror("cluster statistics collection is not available");
            exit(-1);
        }
    }
    #ifdef UTIL_AUTO
      printf("Enter CPU mode.\n");
      printf(" 0 PURR \n 1 SPURR \n");
      scanf("%d",&cpumode);
      printf("Enter print mode.\n");
      printf(" 0 PERCENTAGE\n 1 MILLISECONDS\n 2 CORES \n");
      scanf("%d",&mode);
      if((mode>2)&& (cpumode>1))
      {
        printf("Error: Invalid Input\n");
        exit(0);
      }
      display_lpar_util_auto(mode,cpumode,count,interval);
    #else
    /* Iterate "count" times */
    while (count > 0)
    {
        display_lpar_util();
        sleep(interval);
        count--;
    }
    #endif
    if(collect_remote_node_stats)
    {   /* Now disable cluster statistics by calling perfstat_config */
        perfstat_config(PERFSTAT_DISABLE|PERFSTAT_CLUSTER_STATS, NULL);
    }
    return(0);
}
/* Save the current values for the next iteration */
void save_last_values(perfstat_cpu_total_t *cpustats, perfstat_partition_total_t *lparstats)
{
    last_vcsw      = lparstats->vol_virt_cswitch + lparstats->invol_virt_cswitch;
    last_time_base = lparstats->timebase_last;
    last_phint     = lparstats->phantintrs;
    last_pit       = lparstats->pool_idle_time;
    last_pcpu_user = lparstats->puser;
    last_pcpu_sys  = lparstats->psys;
    last_pcpu_idle = lparstats->pidle;
    last_pcpu_wait = lparstats->pwait;
    last_lcpu_user = cpustats->user;
    last_lcpu_sys  = cpustats->sys;
    last_lcpu_idle = cpustats->idle;
    last_lcpu_wait = cpustats->wait;
    last_busy_donated = lparstats->busy_donated_purr;
    last_idle_donated = lparstats->idle_donated_purr;
    last_busy_stolen = lparstats->busy_stolen_purr;
    last_idle_stolen = lparstats->idle_stolen_purr;
}
/* retrieve metrics using perfstat API */
void collect_metrics (perfstat_cpu_total_t *cpustats, perfstat_partition_total_t *lparstats)
{
    if (collect_remote_node_stats)
    {
        strncpy(nodeid.u.nodename, nodename, MAXHOSTNAMELEN);
        nodeid.spec = NODENAME;
        if (perfstat_partition_total_node(&nodeid, lparstats, sizeof(perfstat_partition_total_t), 1) <= 0) {
            perror("perfstat_partition_total_node");
            exit(-1);
        }
        if (perfstat_cpu_total_node(&nodeid, cpustats, sizeof(perfstat_cpu_total_t), 1) <= 0) {
            perror("perfstat_cpu_total_node");
            exit(-1);
        }
    }
    else
    {
        if (perfstat_partition_total(NULL, lparstats, sizeof(perfstat_partition_total_t), 1) <= 0) {
            perror("perfstat_partition_total");
            exit(-1);
        }
        if (perfstat_cpu_total(NULL, cpustats, sizeof(perfstat_cpu_total_t), 1) <= 0) {
            perror("perfstat_cpu_total");
            exit(-1);
        }
    }
}
/* print header informations */
void print_header(perfstat_partition_total_t *lparstats)
{
    if (lparstats->type.b.shared_enabled) { /* partition is a SPLPAR */
       if (lparstats->type.b.pool_util_authority) { /* partition has PUA access */
          printf("\n%5s %5s %6s %6s %5s %5s %5s %5s %4s %5s",
          "%user", "%sys", "%wait", "%idle", "physc", "%entc", "lbusy", "app", "vcsw", "phint");
          printf("\n%5s %5s %6s %6s %5s %5s %5s %5s %4s %5s",
          "-----", "----", "-----", "-----", "-----", "-----", "-----", "---", "----", "-----");
       } else {
          printf("\n%5s %5s %6s %6s %5s %5s %5s %4s %5s",
          "%user", "%sys", "%wait", "%idle", "physc", "%entc", "lbusy", "vcsw", "phint");
          printf("\n%5s %5s %6s %6s %5s %5s %5s %4s %5s",
          "-----", "----", "-----", "-----", "-----", "-----", "-----", "----", "-----");
       }
    } else { /* partition is a DLPAR */
       printf("\n%5s %5s %6s %6s", "%user", "%sys", "%wait", "%idle");
       printf("\n%5s %5s %6s %6s", "-----", "----", "-----", "-----");
       if (lparstats->type.b.donate_enabled) { /* if donation is enabled for this DLPAR */
         printf(" %6s %6s", "%phsyc", "%vcsw");
         printf(" %6s %6s", "------", "-----");
       }
    }
    fprintf(stdout,"\n");
}
/* Gather and display lpar utilization metrics */
void display_lpar_util(void)
{
    u_longlong_t delta_pcpu_user, delta_pcpu_sys, delta_pcpu_idle, delta_pcpu_wait;
    u_longlong_t delta_lcpu_user, delta_lcpu_sys, delta_lcpu_idle, delta_lcpu_wait;
    u_longlong_t delta_busy_stolen, delta_busy_donated, delta_idle_stolen, delta_idle_donated;
    u_longlong_t vcsw, lcputime, pcputime;
    u_longlong_t entitled_purr, unused_purr;
    u_longlong_t delta_purr, delta_time_base;
    double phys_proc_consumed, entitlement, percent_ent, delta_sec;
    perfstat_partition_total_t lparstats;
    perfstat_cpu_total_t cpustats;
    /* retrieve the metrics */
    collect_metrics (&cpustats, &lparstats);
    /* Print the header for utilization metrics (only once) */
    if (disp_util_header) {
       print_header (&lparstats);
       disp_util_header = 0;
       /* first iteration, we only read the data, print the header and save the data */
       save_last_values(&cpustats, &lparstats);
       return;
    }
    /* calculate physcial processor tics during the last interval in user, system, idle and wait mode  */
    delta_pcpu_user  = lparstats.puser - last_pcpu_user;
    delta_pcpu_sys   = lparstats.psys  - last_pcpu_sys;
    delta_pcpu_idle  = lparstats.pidle - last_pcpu_idle;
    delta_pcpu_wait  = lparstats.pwait - last_pcpu_wait;
    /* calculate total physcial processor tics during the last interval */
    delta_purr = pcputime = delta_pcpu_user + delta_pcpu_sys + delta_pcpu_idle + delta_pcpu_wait;
    /* calculate clock tics during the last interval in user, system, idle and wait mode */
    delta_lcpu_user  = cpustats.user - last_lcpu_user;
    delta_lcpu_sys   = cpustats.sys  - last_lcpu_sys;
    delta_lcpu_idle  = cpustats.idle - last_lcpu_idle;
    delta_lcpu_wait  = cpustats.wait - last_lcpu_wait;
    /* calculate total clock tics during the last interval */
    lcputime = delta_lcpu_user + delta_lcpu_sys + delta_lcpu_idle + delta_lcpu_wait;
/* calculate entitlement for this partition - entitled physical processors for this partition */
entitlement = (double)lparstats.entitled_proc_capacity / 100.0 ;
/* calculate delta time in terms of physical processor tics */
delta_time_base = lparstats.timebase_last - last_time_base;
if (lparstats.type.b.shared_enabled) { /* partition is a SPLPAR */
    /* calculate entitled physical processor tics for this partitions */
    entitled_purr = delta_time_base * entitlement;
    if (entitled_purr < delta_purr) { /* for uncapped SPLPAR */
        /* in case of uncapped SPLPAR, consider entitled physical processor tics or
         * consumed physical processor tics, which ever is greater */
        entitled_purr = delta_purr;
    }
    /* calculate unused physical processor tics out of the entitled physical processor tics */
    unused_purr = entitled_purr - delta_purr;
    /* distributed unused physical processor tics amoung wait and idle proportionally to wait and idle in clock tics */
    delta_pcpu_wait += unused_purr * ((double)delta_lcpu_wait / (double)(delta_lcpu_wait + delta_lcpu_idle));
    delta_pcpu_idle += unused_purr * ((double)delta_lcpu_idle / (double)(delta_lcpu_wait + delta_lcpu_idle));
    /* far SPLPAR, consider the entitled physical processor tics as the actual delta physical processor tics */
    pcputime = entitled_purr;
}
else if (lparstats.type.b.donate_enabled) { /* if donation is enabled for this DLPAR */
    /* calculate busy stolen and idle stolen physical processor tics during the last interval */
    /* these physical processor tics are stolen from this partition by the hypervsior
     * which will be used by wanting partitions */
    delta_busy_stolen = lparstats.busy_stolen_purr - last_busy_stolen;
    delta_idle_stolen = lparstats.idle_stolen_purr - last_idle_stolen;
    /* calculate busy donated and idle donated physical processor tics during the last interval */
    /* these physical processor tics are voluntarily donated by this partition to the hypervsior
     * which will be used by wanting partitions */
    delta_busy_donated = lparstats.busy_donated_purr - last_busy_donated;
    delta_idle_donated = lparstats.idle_donated_purr - last_idle_donated;
    /* add busy donated and busy stolen to the kernel bucket, as cpu
     * cycles were donated / stolen when this partition is busy */
    delta_pcpu_sys += delta_busy_donated;
    delta_pcpu_sys += delta_busy_stolen;
    /* distribute idle stolen to wait and idle proportionally to the logical wait and idle in clock tics, as
     * cpu cycles were stolen when this partition is idle or in wait */
    delta_pcpu_wait += delta_idle_stolen *
                          ((double)delta_lcpu_wait / (double)(delta_lcpu_wait + delta_lcpu_idle));
    delta_pcpu_idle += delta_idle_stolen *
                          ((double)delta_lcpu_idle / (double)(delta_lcpu_wait + delta_lcpu_idle));
    /* distribute idle donated to wait and idle proportionally to the logical wait and idle in clock tics, as
     * cpu cycles were donated when this partition is idle or in wait */
    delta_pcpu_wait += delta_idle_donated *
                          ((double)delta_lcpu_wait / (double)(delta_lcpu_wait + delta_lcpu_idle));
    delta_pcpu_idle += delta_idle_donated *
                          ((double)delta_lcpu_idle / (double)(delta_lcpu_wait + delta_lcpu_idle));
    /* add donated to the total physical processor tics for CPU usage calculation, as they were
     * distributed to respective buckets accordingly */
    pcputime +=  (delta_idle_donated + delta_busy_donated);
    /* add stolen to the total physical processor tics for CPU usage calculation, as they were
     * distributed to respective buckets accordingly */
    pcputime +=  (delta_idle_stolen + delta_busy_stolen);
}
/* Processor Utilization - Applies for both SPLPAR and DLPAR*/
printf("%5.1f ", (double)delta_pcpu_user * 100.0 / (double)pcputime);
printf("%5.1f ", (double)delta_pcpu_sys  * 100.0 / (double)pcputime);
printf("%6.1f ", (double)delta_pcpu_wait * 100.0 / (double)pcputime);
printf("%6.1f ", (double)delta_pcpu_idle * 100.0 / (double)pcputime);
if (lparstats.type.b.shared_enabled) { /* print SPLPAR specific stats */
    /* Physical Processor Consumed by this partition */
    phys_proc_consumed = (double)delta_purr / (double)delta_time_base;
    printf("%5.2f ", (double)phys_proc_consumed);
    /* Percentage of Entitlement Consumed - percentage of entitled physical processor tics consumed */
    percent_ent = (double)((phys_proc_consumed / entitlement) * 100);
    printf("%5.1f ", percent_ent);
    /* Logical Processor Utilization of this partition */
    printf("%5.1f ", (double)(delta_lcpu_user+delta_lcpu_sys) * 100.0 / (double)lcputime);
    if (lparstats.type.b.pool_util_authority) {
    /* Available physical Processor units available in the shared pool (app) */
       printf("%5.2f ", (double)(lparstats.pool_idle_time - last_pit) /
             XINTFRAC*(double)delta_time_base);
    }
    /* Virtual CPU Context Switches per second */
    vcsw = lparstats.vol_virt_cswitch + lparstats.invol_virt_cswitch;
  delta_sec = HTIC2SEC(delta_time_base);
    printf("%4.0f ", (double)(vcsw - last_vcsw) / delta_sec);
    /* Phantom Interrupts per second */
    printf("%5.0f",(double)(lparstats.phantintrs - last_phint) / delta_sec);
}
else if (lparstats.type.b.donate_enabled) { /* print donation-enabled DLPAR specific stats */
    /* Physical Processor Consumed by this partition
     * (excluding donated and stolen physical processor tics). */
    phys_proc_consumed = (double)delta_purr / (double)delta_time_base;
    printf("%5.2f ", (double)phys_proc_consumed);
        /* Virtual CPU Context Switches per second */
        vcsw = lparstats.vol_virt_cswitch + lparstats.invol_virt_cswitch;
      delta_sec = HTIC2SEC(delta_time_base);
        printf("%5.0f ", (double)(vcsw - last_vcsw) / delta_sec);
    }
    printf("\n");
    save_last_values(&cpustats, &lparstats);
}
#ifdef UTIL_AUTO
void display_lpar_util_auto(int mode,int cpumode,int count,int interval)
{
    float user_core_purr,kern_core_purr,wait_core_purr,idle_core_purr;
    float user_core_spurr,kern_core_spurr,wait_core_spurr,idle_core_spurr,sum_core_spurr;
    u_longlong_t user_ms_purr,kern_ms_purr,wait_ms_purr,idle_ms_purr,sum_ms;
    u_longlong_t user_ms_spurr,kern_ms_spurr,wait_ms_spurr,idle_ms_spurr;
    perfstat_rawdata_t data;
    u_longlong_t delta_purr, delta_time_base;
    double phys_proc_consumed, entitlement, percent_ent, delta_sec;
    perfstat_partition_total_t lparstats;
    static perfstat_cpu_total_t oldt,newt;
    perfstat_cpu_util_t util;
    int rc;
    /* retrieve the metrics */
    /* Print the header for utilization metrics (only once) */
    if (disp_util_header) {
    if(mode==UTIL_PCT)
          printf("\n%5s %5s %6s %6s %5s  \n",
          "%user", "%sys", "%wait", "%idle", "physc");
    else if(mode==UTIL_MS)
          printf("\n%5s   %5s   %6s   %6s   %5s \n",
          "user(ms)", "sys(ms)", "wait(ms)", "idle(ms)", "physc");
    else if(mode==UTIL_CORE)
          printf("\n%5s  %5s  %6s  %6s  %5s  \n",
          "user", "sys", "wait", "idle", "physc");
       disp_util_header = 0;
       /* first iteration, we only read the data, print the header and save the data */
    }
  while(count)
  {
    collect_metrics (&oldt, &lparstats);
    sleep(interval);
    collect_metrics (&newt, &lparstats);
   data.type = UTIL_CPU_TOTAL;
   data.curstat = &newt; data.prevstat= &oldt;
   data.sizeof_data = sizeof(perfstat_cpu_total_t);
   data.cur_elems = 1;
   data.prev_elems = 1;
   rc = perfstat_cpu_util(&data, &util,sizeof(perfstat_cpu_util_t), 1);
   if(rc <= 0)
   {
     perror("Error in perfstat_cpu_util");
     exit(-1);
   }
   delta_time_base =  util.delta_time;
  switch(mode)
   {
   case  UTIL_PCT:
         printf(" %5.1f  %5.1f  %5.1f  %5.1f  %5.4f \n",util.user_pct,util.kern_pct,util.wait_pct,util.idle_pct,util.physical_consumed);
         break;
   case  UTIL_MS:
         user_ms_purr=((util.user_pct*delta_time_base)/100.0);
         kern_ms_purr=((util.kern_pct*delta_time_base)/100.0);
         wait_ms_purr=((util.wait_pct*delta_time_base)/100.0);
         idle_ms_purr=((util.idle_pct*delta_time_base)/100.0);
        if(cpumode==UTIL_PURR)
        {
            printf(" %llu    %llu    %llu    %llu   %5.4f\n",user_ms_purr,kern_ms_purr,wait_ms_purr,idle_ms_purr,util.physical_consumed);
        }
       else if(cpumode==UTIL_SPURR)
       {
            user_ms_spurr=(user_ms_purr*util.freq_pct)/100.0;
            kern_ms_spurr=(kern_ms_purr*util.freq_pct)/100.0;
            wait_ms_spurr=(wait_ms_purr*util.freq_pct)/100.0;
            sum_ms=user_ms_spurr+kern_ms_spurr+wait_ms_spurr;
            idle_ms_spurr=delta_time_base-sum_ms;
            printf(" %llu    %llu    %llu    %llu    %5.4f \n",user_ms_spurr,kern_ms_spurr,wait_ms_spurr,idle_ms_spurr,util.physical_consumed);
       }
            break;
   case  UTIL_CORE:
           user_core_purr=((util.user_pct*util.physical_consumed)/100.0);
           kern_core_purr=((util.kern_pct*util.physical_consumed)/100.0);
           wait_core_purr=((util.wait_pct*util.physical_consumed)/100.0);
           idle_core_purr=((util.idle_pct*util.physical_consumed)/100.0);
           user_core_spurr=((user_core_purr*util.freq_pct)/100.0);
           kern_core_spurr=((kern_core_purr*util.freq_pct)/100.0);
           wait_core_spurr=((wait_core_purr*util.freq_pct)/100.0);
           if(cpumode==UTIL_PURR)
           {
            printf("%5.4f   %5.4f   %5.4f   %5.4f   %5.4f\n",user_core_purr,kern_core_purr,wait_core_purr,idle_core_purr,util.physical_consumed);
           }
           else if(cpumode==UTIL_SPURR)
           {
           sum_core_spurr=user_core_spurr+kern_core_spurr+wait_core_spurr;
           idle_core_spurr=util.physical_consumed-sum_core_spurr;
            printf("%5.4f   %5.4f   %5.4f   %5.4f   %5.4f \n",user_core_spurr,kern_core_spurr,wait_core_spurr,idle_core_spurr,util.physical_consumed);
           }
           break;
           default:
           printf("In correct usage\n");
           return;
}
count--;
}
}
#endif

이 프로그램은 다음과 비슷한 출력을 냅니다.

text
%user  %sys  %wait  %idle physc %entc lbusy vcsw phint
-----  ----  -----  ----- ----- ----- ----- ---- -----
  0.1   0.4    0.0   99.5  0.01   1.2   0.2  278     0
  0.0   0.3    0.0   99.7  0.01   0.8   0.2  271     0
  0.0   0.2    0.0   99.8  0.01   0.5   0.1  180     0
  0.0   0.2    0.0   99.8  0.01   0.6   0.1  184     0
  0.0   0.2    0.0   99.7  0.01   0.6   0.1  181     0
  0.0   0.2    0.0   99.8  0.01   0.6   0.1  198     0
  0.0   0.2    0.0   99.8  0.01   0.7   0.2  189     0
  2.1   3.3    0.0   94.6  0.09   8.7   2.1  216     0
  0.0   0.2    0.0   99.8  0.01   0.7   0.1  265     0
영어 원문

perfstat_partition_total Interface

The perfstat_partition_total interface returns a perfstat_partition_total_t structure, which is defined in the libperfstat.h file.

Selected fields from the perfstat_partition_total_t structure include:

  • purr_coalescing — PURR cycles consumes coalescing data if the calling partition is authorized to see pool wide statistics, else set to zero
  • spurr_coalescing — SPURR cycles consumes coalescing data if the calling partition is authorized to see pool wide statistics, else set to zero
  • type — Partition type
  • online_cpus — Number of virtual processors currently allocated to the partition
  • online_memory — Amount of memory currently allocated to the partition
  • Note: Page coalescing is a transparent operation wherein the hypervisor detects duplicate pages, directs

all user reads to a single copy, and reclaims duplicate physical memory pages For a complete list, see the perfstat_partition_total_t section in the libperfstat.h header file.

The following code shows examples of how to use the perfstat_partition_total function.

The following example demonstrates how to emulate the lpartstat -i command:

(38줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The program displays an output that is similar to the following example output:

(23줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The following example demonstrates emulating the lparstat command in default mode:

(404줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The program displays an output that is similar to the following example output:

text
%user  %sys  %wait  %idle physc %entc lbusy vcsw phint
-----  ----  -----  ----- ----- ----- ----- ---- -----
  0.1   0.4    0.0   99.5  0.01   1.2   0.2  278     0
  0.0   0.3    0.0   99.7  0.01   0.8   0.2  271     0
  0.0   0.2    0.0   99.8  0.01   0.5   0.1  180     0
  0.0   0.2    0.0   99.8  0.01   0.6   0.1  184     0
  0.0   0.2    0.0   99.7  0.01   0.6   0.1  181     0
  0.0   0.2    0.0   99.8  0.01   0.6   0.1  198     0
  0.0   0.2    0.0   99.8  0.01   0.7   0.2  189     0
  2.1   3.3    0.0   94.6  0.09   8.7   2.1  216     0
  0.0   0.2    0.0   99.8  0.01   0.7   0.1  265     0

perfstat_tape_total 인터페이스

perfstat_tape_total 인터페이스는 libperfstat.h 파일에 정의된 perfstat_tape_total_t 구조체를 돌려줍니다.

perfstat_tape_total_t 구조체의 주요 필드는 다음과 같습니다.

필드 설명
number 전체 테이프 수
size 모든 테이프의 전체 크기(MB)
free 모든 테이프의 전체 빈 부분(MB)
rxfers 테이프와 주고받은 읽기 전송의 전체 수
xfers 테이프와 주고받은 전송의 전체 수

이 밖에도 테이프 관련 지표(보내고 받은 바이트 수 등)를 돌려줍니다. 전체 목록은 libperfstat.h 헤더 파일의 perfstat_tape_total 부분을 봅니다.

다음 코드는 perfstat_tape_total 함수를 쓰는 예입니다.

text
#include <stdio.h>
#include <stdlib.h>
#include <libperfstat.h>
int main(){
    perfstat_tape_total_t *tinfo;
    int rc,i;
    rc = perfstat_tape_total(NULL, NULL, sizeof(perfstat_tape_total_t), 0);
    if(rc<=0){
        perror("perfstat_tape_total");
        exit(-1);
    }
    /* allocate enough memory for all the structures */
    tinfo = calloc(rc, sizeof(perfstat_tape_t));
    if(tinfo==NULL){
        printf("No sufficient memory\n");
        exit(-1);
    }
    rc = perfstat_tape_total(NULL, tinfo, sizeof(perfstat_tape_total_t), rc);
    if (rc < 0)
    {
        perror("perfstat_tape_total");
        exit(-1);
    }
    if(rc==0){
        printf("No tape found on the system\n");
        exit(-1);
    }
    for(i=0;i<rc;i++){
        printf("Total number of tapes=%d\n",tinfo[i].number);
        printf("Total size of all tapes (in MB)=%lld\n",tinfo[i].size);
        printf("Free portion of all tapes(in MB)=%lld\n",tinfo[i].free);
        printf("Number of read transfers to/from tape=%lld\n",tinfo[i].rxfers);
        printf("Total number of transfers to/from tape=%lld\n",tinfo[i].xfers);
        printf("Blocks written to all tapes=%lld\n",tinfo[i].wblks);
        printf("Blocks read from all tapes=%lld\n",tinfo[i].rblks);
        printf("Amount of time tapes are active=%lld\n",tinfo[i].time);
    }
    return(0);
}

위 프로그램은 diskstat의 동작을 흉내 내며 perfstat_tape_total을 쓰는 방법을 보여 줍니다.

영어 원문

perfstat_tape_total Interface

The perfstat_tape_total interface returns a perfstat_tape_total_t structure, which is defined in the libperfstat.h file.

Selected fields from the perfstat_tape_total_t structure include:

  • number — Total number of tapes
  • size — Total size of all tapes(in MB)
  • free — Total free portion of all tapes (in MB)
  • rxfers — Total number of read transfers from/to tape
  • xfers — Total number of transfers from/to tape

Several other tape-related metrics (such as number of bytes sent and received). For a complete list, see the perfstat_tape_total section in the libperfstat.h header file.

The following code shows examples of how to use the perfstat_tape_total function.

(39줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The preceding program emulates diskstat behavior and also shows how perfstat_tape_total is used.

(6.1) perfstat_partition_config 인터페이스

perfstat_partition_config 인터페이스는 libperfstat.h 파일에 정의된 perfstat_partition_config_t 구조체를 돌려줍니다.

perfstat_partition_config_t 구조체의 주요 필드는 다음과 같습니다.

필드 설명
partitionname 파티션 이름
processorFamily 프로세서 종류
processorModel 프로세서 모델
machineID 머신 ID
processorMHz 프로세서 클록 속도(MHz)
numProcessors 프레임에 구성된 물리 프로세서 수
OSName 운영 체제 이름
OSVersion 운영 체제 버전
OSBuild 운영 체제 빌드
lcpus 논리 CPU 수
smtthreads SMT 스레드 수
drives 전체 드라이브 수
nw_adapters 전체 네트워크 어댑터 수
vcpus 가상 CPU의 최소·최대·온라인 수
cpucap CPU 용량의 최소·최대·온라인 값
entitled_proc_capacity 이 파티션이 받을 권리가 있는 프로세서 단위 수
cpucap_weightage 가변 프로세서 용량 가중치
mem_weightage 가변 메모리 용량 가중치
cpupool_weightage 풀 가중치
activecpusinpool 파티션이 속한 공유 프로세서 풀의 물리 CPU 수
sharedpcpu 공유 프로세서용으로 할당된 물리 프로세서 수
maxpoolcap 파티션 풀의 최대 프로세서 용량
entpoolcap 파티션 풀의 권리 프로세서 용량
mem 메모리의 최소·최대·온라인 양
totiomement 파티션의 I/O 메모리 권리량(바이트)
mempoolid 논리 파티션(LPAR)이 속한 AMS 풀의 풀 ID
hyperpgsize 하이퍼바이저 페이지 크기(KB)
exp_mem 확장 메모리의 최소·최대·온라인 양
targetmemexpfactor 목표 메모리 확장 계수(100을 곱한 값)
targetmemexpsize 확장 메모리 크기(MB)
Subprocessormode 파티션의 하위 프로세서(subprocessor) 모드

전체 목록은 libperfstat.h 헤더 파일의 perfstat_partition_config_t 부분을 봅니다.

perfstat_partition_config API를 쓰는 코드는 다음과 같습니다.

text
#include <libperfstat.h>
int main(int argc, char *argv[])
{
   perfstat_partition_config_t pinfo;
   int rc;
   rc = perfstat_partition_config(NULL, &pinfo, sizeof(perfstat_partition_config_t), 1);
   if(rc != 1)
   {
    perror("Error in perfstat_partition_config");
    exit(-1);
   }
   printf("==========Configuration Information of Partition==========\n");
   printf("Partition Name =       %s\n",pinfo.partitionname);
   printf("Node Name =            %s\n",pinfo.nodename);
   printf("Partition Number =     %u\n",pinfo.partitionnum);
   printf("Group ID =             %u\n",pinfo.groupid);
   printf("\n\n========General Partition Properties(1=YES, 0=NO)=========\n");
   printf("SMT Capable =          %u\n",pinfo.conf.b.smt_capable);
              /* 1, if OS supports SMT mode */
   printf("SMT Enabled =          %u\n",pinfo.conf.b.smt_enabled);
              /* 1, if SMT mode is on */
   printf("LPAR Capable =         %u\n",pinfo.conf.b.lpar_capable);
              /* 1, if OS supports logical partitioning */
   printf("LPAR Enabled =         %u\n",pinfo.conf.b.lpar_enabled);
              /* 1, if logical partitioning is on */
   printf("Shared Capable =       %u\n",pinfo.conf.b.shared_capable);
              /* 1, if OS supports shared processor LPAR */
   printf("Shared Enabled =       %u\n",pinfo.conf.b.shared_enabled);
              /* 1, if partition runs in shared mode */
   printf("DLPAR Capable =        %u\n",pinfo.conf.b.dlpar_capable);
              /* 1, if OS supports dynamic LPAR */
   printf("Capped =               %u\n",pinfo.conf.b.capped);
              /* 1, if partition is capped */
   printf("64-Bit Kernel =        %u\n",pinfo.conf.b.kernel_is_64);
              /* 1, if kernel is 64 bit */
   printf("Pool Util Authority =  %u\n",pinfo.conf.b.pool_util_authority);
              /* 1, if pool utilization available */
   printf("Donate Capable =       %u\n",pinfo.conf.b.donate_capable);
              /* 1, if capable of donating cycles */
   printf("Donate Enabled =       %u\n",pinfo.conf.b.donate_enabled);
              /* 1, if capable of donating cycles */
   printf("AMS Capable =          %u\n",pinfo.conf.b.ams_capable);
              /* 1, if AMS(Active Memory Sharing) capable */
   printf("AMS Enabled =          %u\n",pinfo.conf.b.ams_enabled);
              /* 1, if AMS(Active Memory Sharing) enabled */
   printf("Power Saving Mode =    %u\n",pinfo.conf.b.power_save);
              /* 1, if Power saving mode is enabled */
   printf("AME Enabled =          %u\n",pinfo.conf.b.ame_enabled);
              /* 1, if Active Memory Expansion is enabled */
   printf("Shared Extended =      %u\n",pinfo.conf.b.shared_extended);
              /* 1, if Shared Extended */
   printf("\n\n==================Hardware Configuration==================\n");
   printf("Processor Type =               %s\n",pinfo.processorFamily);
   printf("Processor Model =              %s\n",pinfo.processorModel);
   printf("Machine ID =                   %s\n",pinfo.machineID);
   printf("Processor Clock Speed =        %lf MHz\n",pinfo.processorMHz);
   printf("Online Configured Processors = %lld\n",pinfo.numProcessors.online);
   printf("Max Configured Processors =    %lld\n",pinfo.numProcessors.max);
   printf("\n\n==================Software Configuration==================\n");
   printf("OS Name =                      %s\n",pinfo.OSName);
   printf("OS Version =                   %s\n",pinfo.OSVersion);
   printf("OS Build =                     %s\n",pinfo.OSBuild);
   printf("\n\n====================LPAR Configuration====================\n");
   printf("Number of Logical CPUs =       %u\n",pinfo.lcpus);
   printf("Number of SMT Threads =        %u\n",pinfo.smtthreads);
   printf("Number of Drives =             %u\n",pinfo.drives);
   printf("Number of NW Adapters =        %u\n",pinfo.nw_adapters);
   printf("\n\n===========Physical CPU Related Configuration=============\n");
   printf("Minimum CPU Capacity =         %.2f\n",(float)pinfo.cpucap.min/100.0);
   printf("Maximum CPU Capacity =         %.2f\n",(float)pinfo.cpucap.max/100.0);
   printf("CPU Capacity Weightage =       %u\n",pinfo.cpucap_weightage);
   printf("Entitled Proc Capacity =       %.2f\n",pinfo.entitled_proc_capacity/100.0);
   printf("\n\n============Virtual CPU Related Configuration=============\n");
   printf("Minimum Virtual CPUs =         %lld\n",pinfo.vcpus.min);
   printf("Maximum Virtual CPUs =         %lld\n",pinfo.vcpus.max);
   printf("Online Virtual CPUs =          %lld\n",pinfo.vcpus.online);
   printf("\n\n==========Processor Pool Related Configuration============\n");
   printf("Processor Pool Id =            %u\n",pinfo.processor_poolid);
   printf("Active CPUs in pool =          %u\n",pinfo.activecpusinpool);
   printf("Pool Weightage =               %u\n",pinfo.cpupool_weightage);
   printf("Shared processors Count =      %u\n",pinfo.sharedpcpu);
   printf("Max pool Capacity =            %u\n",pinfo.maxpoolcap);
   printf("Entitled pool Capacity =       %u\n",pinfo.entpoolcap);
   printf("\n\n==============Memory Related Configuration================\n");
   printf("Minimum Memory =               %lld\n",pinfo.mem.min);
   printf("Maximum memory =               %lld\n",pinfo.mem.max);
   printf("Online memory =                %lld\n",pinfo.mem.online);
   printf("Memory capacity Weightage =    %u\n",pinfo.mem_weightage);
   printf("\n\n===============AMS Related Configuration==================\n");
   printf("I/O memory Entitlement =       %lld\n",pinfo.totiomement);
   printf("AMS Pool ID =                  %d\n",pinfo.mempoolid);
   printf("Hypervisor Page Size =         %f\n",pinfo.hyperpgsize);
   printf("\n\n===============AME Related Configuration==================\n");
   printf("Minimum Expanded memory =      %lld\n",pinfo.exp_mem.min);
   printf("Maximum Expanded Memory =      %lld\n",pinfo.exp_mem.max);
   printf("Online Expanded memory =       %lld\n",pinfo.exp_mem.online);
   printf("Target memory Expansion factor = %lld\n",pinfo.targetmemexpfactor);
   printf("Target Memory Expansion Size = %lld\n",pinfo.targetmemexpsize);
   printf("\n==========================================================");
}

프로그램의 출력은 다음과 같습니다.

text
==========Configuration Information of Partition==========
Partition Name = clock15
Node Name = clock15
Partition Number = 9
Group ID = 0
========General Partition Properties(1=YES, 0=NO)=========
SMT Capable = 1
SMT Enabled = 1
LPAR Capable = 1
LPAR Enabled = 1
Shared Capable = 1
Shared Enabled = 1
DLPAR Capable = 1
Capped = 0
64-Bit Kernel = 1
Pool Util Authority = 0
Donate Capable = 0
Donate Enabled = 0
AMS Capable = 0
AMS Enabled = 0
Power Saving Mode = 1
AME Enabled = 0
Shared Extended = 0
==================Hardware Configuration==================
Processor Type = POWER_5
Processor Model = IBM,9133-55A
Machine ID = 061500H
Processor Clock Speed = 1648.350000 MHz
Online Configured Processors = 8
Max Configured Processors = 8
==================Software Configuration==================
OS Name = AIX
OS Version = 7.1
OS Build = Feb 17 2011 15:57:15 1107A_71D
====================LPAR Configuration====================
Number of Logical CPUs = 2
Number of SMT Threads = 2
Number of Drives = 2
Number of NW Adapters = 2
===========Physical CPU Related Configuration=============
Minimum CPU Capacity = 0.10
Maximum CPU Capacity = 8.00
CPU Capacity Weightage = 128
Entitled Proc Capacity = 0.75
============Virtual CPU Related Configuration=============
Minimum Virtual CPUs = 1
Maximum Virtual CPUs = 8
Online Virtual CPUs = 1
==========Processor Pool Related Configuration============
Processor Pool Id = 0
Active CPUs in pool = 3
Pool Weightage = 128
Shared processors Count = 0
Max pool Capacity = 0
Entitled pool Capacity = 0
==============Memory Related Configuration================
Minimum Memory = 256
Maximum memory = 4096
Online memory = 2048
Memory capacity Weightage = 0
===============AMS Related Configuration==================
I/O memory Entitlement = 0
AMS Pool ID = 0
Hypervisor Page Size = 0.000000
===============AME Related Configuration==================
Minimum Expanded memory = 0
Maximum Expanded Memory = 0
Online Expanded memory = 0
Target memory Expansion factor = 0
Target Memory Expansion Size = 0
==========================================================
영어 원문

perfstat_partition_config interface

The perfstat_partition_config interface returns a perfstat_partition_config_t structure, which is defined in the libperfstat.h file.

The selected fields from the perfstat_partition_config_t structure include:

  • partitionname — Partition name
  • processorFamily — Processor type
  • processorModel — Processor model
  • machineID — Machine ID
  • processorMHz — Processor clock speed in megahertz
  • numProcessors — Number of configured physical processors in frame
  • OSName — Name of operating system
  • OSVersion — Version of operating system
  • OSBuild — Build of operating system
  • lcpus — Number of logical CPUs
  • smtthreads — Number of SMT threads
  • drives — Total number of drives
  • nw_adapters — Total number of network adapters
  • vcpus — Minimum, maximum, and online virtual CPUs
  • cpucap — Minimum, maximum, and online CPU capacity
  • entitled_proc_capacity — Number of processor units that this partition is entitled to receive
  • cpucap_weightage — Variable processor capacity weightage
  • mem_weightage — Variable memory capacity weightage
  • cpupool_weightage — Pool weightage
  • activecpusinpool — Count of physical CPUs in the shared processor pool to which the partition belongs
  • sharedpcpu — Number of physical processors allocated for the use of the shared processor
  • maxpoolcap — Maximum processor capacity of partition's pool
  • entpoolcap — Entitled processor capacity of partition's pool
  • mem — Minimum, maximum, and online memory
  • totiomement — I/O memory entitlement of the partition in bytes
  • mempoolid — AMS pool ID of the pool to which the logical partition (LPAR) belongs
  • hyperpgsize — Hypervisor page size in kilobytes
  • exp_mem — Minimum, maximum, and online expanded memory
  • targetmemexpfactor — Target memory expansion factor scaled by 100
  • targetmemexpsize — Expanded memory size in megabytes
  • Subprocessormode — Subprocessor mode for the partition

For a complete list, see the perfstat_partition_config_t section in the libperfstat.h header file.

The usage of the code for the perfstat_partition_config API is as follows:

(100줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The output of the program is as follows:

(71줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

자주 쓰는 형태

bash
ls /usr/samples/libperfstat                       # 예제 소스
cd /usr/samples/libperfstat && make -f Makefile.samples
cc -o cputotal cputotal.c -lperfstat              # 직접 컴파일