Path: blob/master/Documentation/accounting/getdelays.c
10821 views
/* getdelays.c1*2* Utility to get per-pid and per-tgid delay accounting statistics3* Also illustrates usage of the taskstats interface4*5* Copyright (C) Shailabh Nagar, IBM Corp. 20056* Copyright (C) Balbir Singh, IBM Corp. 20067* Copyright (c) Jay Lan, SGI. 20068*9* Compile with10* gcc -I/usr/src/linux/include getdelays.c -o getdelays11*/1213#include <stdio.h>14#include <stdlib.h>15#include <errno.h>16#include <unistd.h>17#include <poll.h>18#include <string.h>19#include <fcntl.h>20#include <sys/types.h>21#include <sys/stat.h>22#include <sys/socket.h>23#include <sys/wait.h>24#include <signal.h>2526#include <linux/genetlink.h>27#include <linux/taskstats.h>28#include <linux/cgroupstats.h>2930/*31* Generic macros for dealing with netlink sockets. Might be duplicated32* elsewhere. It is recommended that commercial grade applications use33* libnl or libnetlink and use the interfaces provided by the library34*/35#define GENLMSG_DATA(glh) ((void *)(NLMSG_DATA(glh) + GENL_HDRLEN))36#define GENLMSG_PAYLOAD(glh) (NLMSG_PAYLOAD(glh, 0) - GENL_HDRLEN)37#define NLA_DATA(na) ((void *)((char*)(na) + NLA_HDRLEN))38#define NLA_PAYLOAD(len) (len - NLA_HDRLEN)3940#define err(code, fmt, arg...) \41do { \42fprintf(stderr, fmt, ##arg); \43exit(code); \44} while (0)4546int done;47int rcvbufsz;48char name[100];49int dbg;50int print_delays;51int print_io_accounting;52int print_task_context_switch_counts;53__u64 stime, utime;5455#define PRINTF(fmt, arg...) { \56if (dbg) { \57printf(fmt, ##arg); \58} \59}6061/* Maximum size of response requested or message sent */62#define MAX_MSG_SIZE 102463/* Maximum number of cpus expected to be specified in a cpumask */64#define MAX_CPUS 326566struct msgtemplate {67struct nlmsghdr n;68struct genlmsghdr g;69char buf[MAX_MSG_SIZE];70};7172char cpumask[100+6*MAX_CPUS];7374static void usage(void)75{76fprintf(stderr, "getdelays [-dilv] [-w logfile] [-r bufsize] "77"[-m cpumask] [-t tgid] [-p pid]\n");78fprintf(stderr, " -d: print delayacct stats\n");79fprintf(stderr, " -i: print IO accounting (works only with -p)\n");80fprintf(stderr, " -l: listen forever\n");81fprintf(stderr, " -v: debug on\n");82fprintf(stderr, " -C: container path\n");83}8485/*86* Create a raw netlink socket and bind87*/88static int create_nl_socket(int protocol)89{90int fd;91struct sockaddr_nl local;9293fd = socket(AF_NETLINK, SOCK_RAW, protocol);94if (fd < 0)95return -1;9697if (rcvbufsz)98if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF,99&rcvbufsz, sizeof(rcvbufsz)) < 0) {100fprintf(stderr, "Unable to set socket rcv buf size "101"to %d\n",102rcvbufsz);103return -1;104}105106memset(&local, 0, sizeof(local));107local.nl_family = AF_NETLINK;108109if (bind(fd, (struct sockaddr *) &local, sizeof(local)) < 0)110goto error;111112return fd;113error:114close(fd);115return -1;116}117118119static int send_cmd(int sd, __u16 nlmsg_type, __u32 nlmsg_pid,120__u8 genl_cmd, __u16 nla_type,121void *nla_data, int nla_len)122{123struct nlattr *na;124struct sockaddr_nl nladdr;125int r, buflen;126char *buf;127128struct msgtemplate msg;129130msg.n.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN);131msg.n.nlmsg_type = nlmsg_type;132msg.n.nlmsg_flags = NLM_F_REQUEST;133msg.n.nlmsg_seq = 0;134msg.n.nlmsg_pid = nlmsg_pid;135msg.g.cmd = genl_cmd;136msg.g.version = 0x1;137na = (struct nlattr *) GENLMSG_DATA(&msg);138na->nla_type = nla_type;139na->nla_len = nla_len + 1 + NLA_HDRLEN;140memcpy(NLA_DATA(na), nla_data, nla_len);141msg.n.nlmsg_len += NLMSG_ALIGN(na->nla_len);142143buf = (char *) &msg;144buflen = msg.n.nlmsg_len ;145memset(&nladdr, 0, sizeof(nladdr));146nladdr.nl_family = AF_NETLINK;147while ((r = sendto(sd, buf, buflen, 0, (struct sockaddr *) &nladdr,148sizeof(nladdr))) < buflen) {149if (r > 0) {150buf += r;151buflen -= r;152} else if (errno != EAGAIN)153return -1;154}155return 0;156}157158159/*160* Probe the controller in genetlink to find the family id161* for the TASKSTATS family162*/163static int get_family_id(int sd)164{165struct {166struct nlmsghdr n;167struct genlmsghdr g;168char buf[256];169} ans;170171int id = 0, rc;172struct nlattr *na;173int rep_len;174175strcpy(name, TASKSTATS_GENL_NAME);176rc = send_cmd(sd, GENL_ID_CTRL, getpid(), CTRL_CMD_GETFAMILY,177CTRL_ATTR_FAMILY_NAME, (void *)name,178strlen(TASKSTATS_GENL_NAME)+1);179if (rc < 0)180return 0; /* sendto() failure? */181182rep_len = recv(sd, &ans, sizeof(ans), 0);183if (ans.n.nlmsg_type == NLMSG_ERROR ||184(rep_len < 0) || !NLMSG_OK((&ans.n), rep_len))185return 0;186187na = (struct nlattr *) GENLMSG_DATA(&ans);188na = (struct nlattr *) ((char *) na + NLA_ALIGN(na->nla_len));189if (na->nla_type == CTRL_ATTR_FAMILY_ID) {190id = *(__u16 *) NLA_DATA(na);191}192return id;193}194195#define average_ms(t, c) (t / 1000000ULL / (c ? c : 1))196197static void print_delayacct(struct taskstats *t)198{199printf("\n\nCPU %15s%15s%15s%15s%15s\n"200" %15llu%15llu%15llu%15llu%15.3fms\n"201"IO %15s%15s%15s\n"202" %15llu%15llu%15llums\n"203"SWAP %15s%15s%15s\n"204" %15llu%15llu%15llums\n"205"RECLAIM %12s%15s%15s\n"206" %15llu%15llu%15llums\n",207"count", "real total", "virtual total",208"delay total", "delay average",209(unsigned long long)t->cpu_count,210(unsigned long long)t->cpu_run_real_total,211(unsigned long long)t->cpu_run_virtual_total,212(unsigned long long)t->cpu_delay_total,213average_ms((double)t->cpu_delay_total, t->cpu_count),214"count", "delay total", "delay average",215(unsigned long long)t->blkio_count,216(unsigned long long)t->blkio_delay_total,217average_ms(t->blkio_delay_total, t->blkio_count),218"count", "delay total", "delay average",219(unsigned long long)t->swapin_count,220(unsigned long long)t->swapin_delay_total,221average_ms(t->swapin_delay_total, t->swapin_count),222"count", "delay total", "delay average",223(unsigned long long)t->freepages_count,224(unsigned long long)t->freepages_delay_total,225average_ms(t->freepages_delay_total, t->freepages_count));226}227228static void task_context_switch_counts(struct taskstats *t)229{230printf("\n\nTask %15s%15s\n"231" %15llu%15llu\n",232"voluntary", "nonvoluntary",233(unsigned long long)t->nvcsw, (unsigned long long)t->nivcsw);234}235236static void print_cgroupstats(struct cgroupstats *c)237{238printf("sleeping %llu, blocked %llu, running %llu, stopped %llu, "239"uninterruptible %llu\n", (unsigned long long)c->nr_sleeping,240(unsigned long long)c->nr_io_wait,241(unsigned long long)c->nr_running,242(unsigned long long)c->nr_stopped,243(unsigned long long)c->nr_uninterruptible);244}245246247static void print_ioacct(struct taskstats *t)248{249printf("%s: read=%llu, write=%llu, cancelled_write=%llu\n",250t->ac_comm,251(unsigned long long)t->read_bytes,252(unsigned long long)t->write_bytes,253(unsigned long long)t->cancelled_write_bytes);254}255256int main(int argc, char *argv[])257{258int c, rc, rep_len, aggr_len, len2;259int cmd_type = TASKSTATS_CMD_ATTR_UNSPEC;260__u16 id;261__u32 mypid;262263struct nlattr *na;264int nl_sd = -1;265int len = 0;266pid_t tid = 0;267pid_t rtid = 0;268269int fd = 0;270int count = 0;271int write_file = 0;272int maskset = 0;273char *logfile = NULL;274int loop = 0;275int containerset = 0;276char containerpath[1024];277int cfd = 0;278int forking = 0;279sigset_t sigset;280281struct msgtemplate msg;282283while (!forking) {284c = getopt(argc, argv, "qdiw:r:m:t:p:vlC:c:");285if (c < 0)286break;287288switch (c) {289case 'd':290printf("print delayacct stats ON\n");291print_delays = 1;292break;293case 'i':294printf("printing IO accounting\n");295print_io_accounting = 1;296break;297case 'q':298printf("printing task/process context switch rates\n");299print_task_context_switch_counts = 1;300break;301case 'C':302containerset = 1;303strncpy(containerpath, optarg, strlen(optarg) + 1);304break;305case 'w':306logfile = strdup(optarg);307printf("write to file %s\n", logfile);308write_file = 1;309break;310case 'r':311rcvbufsz = atoi(optarg);312printf("receive buf size %d\n", rcvbufsz);313if (rcvbufsz < 0)314err(1, "Invalid rcv buf size\n");315break;316case 'm':317strncpy(cpumask, optarg, sizeof(cpumask));318maskset = 1;319printf("cpumask %s maskset %d\n", cpumask, maskset);320break;321case 't':322tid = atoi(optarg);323if (!tid)324err(1, "Invalid tgid\n");325cmd_type = TASKSTATS_CMD_ATTR_TGID;326break;327case 'p':328tid = atoi(optarg);329if (!tid)330err(1, "Invalid pid\n");331cmd_type = TASKSTATS_CMD_ATTR_PID;332break;333case 'c':334335/* Block SIGCHLD for sigwait() later */336if (sigemptyset(&sigset) == -1)337err(1, "Failed to empty sigset");338if (sigaddset(&sigset, SIGCHLD))339err(1, "Failed to set sigchld in sigset");340sigprocmask(SIG_BLOCK, &sigset, NULL);341342/* fork/exec a child */343tid = fork();344if (tid < 0)345err(1, "Fork failed\n");346if (tid == 0)347if (execvp(argv[optind - 1],348&argv[optind - 1]) < 0)349exit(-1);350351/* Set the command type and avoid further processing */352cmd_type = TASKSTATS_CMD_ATTR_PID;353forking = 1;354break;355case 'v':356printf("debug on\n");357dbg = 1;358break;359case 'l':360printf("listen forever\n");361loop = 1;362break;363default:364usage();365exit(-1);366}367}368369if (write_file) {370fd = open(logfile, O_WRONLY | O_CREAT | O_TRUNC,371S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);372if (fd == -1) {373perror("Cannot open output file\n");374exit(1);375}376}377378if ((nl_sd = create_nl_socket(NETLINK_GENERIC)) < 0)379err(1, "error creating Netlink socket\n");380381382mypid = getpid();383id = get_family_id(nl_sd);384if (!id) {385fprintf(stderr, "Error getting family id, errno %d\n", errno);386goto err;387}388PRINTF("family id %d\n", id);389390if (maskset) {391rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,392TASKSTATS_CMD_ATTR_REGISTER_CPUMASK,393&cpumask, strlen(cpumask) + 1);394PRINTF("Sent register cpumask, retval %d\n", rc);395if (rc < 0) {396fprintf(stderr, "error sending register cpumask\n");397goto err;398}399}400401if (tid && containerset) {402fprintf(stderr, "Select either -t or -C, not both\n");403goto err;404}405406/*407* If we forked a child, wait for it to exit. Cannot use waitpid()408* as all the delicious data would be reaped as part of the wait409*/410if (tid && forking) {411int sig_received;412sigwait(&sigset, &sig_received);413}414415if (tid) {416rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,417cmd_type, &tid, sizeof(__u32));418PRINTF("Sent pid/tgid, retval %d\n", rc);419if (rc < 0) {420fprintf(stderr, "error sending tid/tgid cmd\n");421goto done;422}423}424425if (containerset) {426cfd = open(containerpath, O_RDONLY);427if (cfd < 0) {428perror("error opening container file");429goto err;430}431rc = send_cmd(nl_sd, id, mypid, CGROUPSTATS_CMD_GET,432CGROUPSTATS_CMD_ATTR_FD, &cfd, sizeof(__u32));433if (rc < 0) {434perror("error sending cgroupstats command");435goto err;436}437}438if (!maskset && !tid && !containerset) {439usage();440goto err;441}442443do {444rep_len = recv(nl_sd, &msg, sizeof(msg), 0);445PRINTF("received %d bytes\n", rep_len);446447if (rep_len < 0) {448fprintf(stderr, "nonfatal reply error: errno %d\n",449errno);450continue;451}452if (msg.n.nlmsg_type == NLMSG_ERROR ||453!NLMSG_OK((&msg.n), rep_len)) {454struct nlmsgerr *err = NLMSG_DATA(&msg);455fprintf(stderr, "fatal reply error, errno %d\n",456err->error);457goto done;458}459460PRINTF("nlmsghdr size=%zu, nlmsg_len=%d, rep_len=%d\n",461sizeof(struct nlmsghdr), msg.n.nlmsg_len, rep_len);462463464rep_len = GENLMSG_PAYLOAD(&msg.n);465466na = (struct nlattr *) GENLMSG_DATA(&msg);467len = 0;468while (len < rep_len) {469len += NLA_ALIGN(na->nla_len);470switch (na->nla_type) {471case TASKSTATS_TYPE_AGGR_TGID:472/* Fall through */473case TASKSTATS_TYPE_AGGR_PID:474aggr_len = NLA_PAYLOAD(na->nla_len);475len2 = 0;476/* For nested attributes, na follows */477na = (struct nlattr *) NLA_DATA(na);478done = 0;479while (len2 < aggr_len) {480switch (na->nla_type) {481case TASKSTATS_TYPE_PID:482rtid = *(int *) NLA_DATA(na);483if (print_delays)484printf("PID\t%d\n", rtid);485break;486case TASKSTATS_TYPE_TGID:487rtid = *(int *) NLA_DATA(na);488if (print_delays)489printf("TGID\t%d\n", rtid);490break;491case TASKSTATS_TYPE_STATS:492count++;493if (print_delays)494print_delayacct((struct taskstats *) NLA_DATA(na));495if (print_io_accounting)496print_ioacct((struct taskstats *) NLA_DATA(na));497if (print_task_context_switch_counts)498task_context_switch_counts((struct taskstats *) NLA_DATA(na));499if (fd) {500if (write(fd, NLA_DATA(na), na->nla_len) < 0) {501err(1,"write error\n");502}503}504if (!loop)505goto done;506break;507default:508fprintf(stderr, "Unknown nested"509" nla_type %d\n",510na->nla_type);511break;512}513len2 += NLA_ALIGN(na->nla_len);514na = (struct nlattr *) ((char *) na + len2);515}516break;517518case CGROUPSTATS_TYPE_CGROUP_STATS:519print_cgroupstats(NLA_DATA(na));520break;521default:522fprintf(stderr, "Unknown nla_type %d\n",523na->nla_type);524case TASKSTATS_TYPE_NULL:525break;526}527na = (struct nlattr *) (GENLMSG_DATA(&msg) + len);528}529} while (loop);530done:531if (maskset) {532rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,533TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK,534&cpumask, strlen(cpumask) + 1);535printf("Sent deregister mask, retval %d\n", rc);536if (rc < 0)537err(rc, "error sending deregister cpumask\n");538}539err:540close(nl_sd);541if (fd)542close(fd);543if (cfd)544close(cfd);545return 0;546}547548549