getdelays.c revision 09aba8f67313fe84b1aaf14a16cd71d4575d8d78
1/* getdelays.c
2 *
3 * Utility to get per-pid and per-tgid delay accounting statistics
4 * Also illustrates usage of the taskstats interface
5 *
6 * Copyright (C) Shailabh Nagar, IBM Corp. 2005
7 * Copyright (C) Balbir Singh, IBM Corp. 2006
8 * Copyright (c) Jay Lan, SGI. 2006
9 *
10 * Compile with
11 *	gcc -I/usr/src/linux/include getdelays.c -o getdelays
12 */
13
14#include <stdio.h>
15#include <stdlib.h>
16#include <errno.h>
17#include <unistd.h>
18#include <poll.h>
19#include <string.h>
20#include <fcntl.h>
21#include <sys/types.h>
22#include <sys/stat.h>
23#include <sys/socket.h>
24#include <signal.h>
25
26#include <linux/genetlink.h>
27#include <linux/taskstats.h>
28#include <linux/cgroupstats.h>
29
30#include "config.h"
31/*
32 * Generic macros for dealing with netlink sockets. Might be duplicated
33 * elsewhere. It is recommended that commercial grade applications use
34 * libnl or libnetlink and use the interfaces provided by the library
35 */
36#define GENLMSG_DATA(glh)	((void *)(NLMSG_DATA(glh) + GENL_HDRLEN))
37#define GENLMSG_PAYLOAD(glh)	(NLMSG_PAYLOAD(glh, 0) - GENL_HDRLEN)
38#define NLA_DATA(na)		((void *)((char*)(na) + NLA_HDRLEN))
39#define NLA_PAYLOAD(len)	(len - NLA_HDRLEN)
40
41#define err(code, fmt, arg...)			\
42	do {					\
43		fprintf(stderr, fmt, ##arg);	\
44		exit(code);			\
45	} while (0)
46
47int done;
48int rcvbufsz;
49char name[100];
50int dbg;
51int print_delays;
52int print_io_accounting;
53int print_task_context_switch_counts;
54__u64 stime, utime;
55
56#define PRINTF(fmt, arg...) {			\
57	    if (dbg) {				\
58		printf(fmt, ##arg);		\
59	    }					\
60	}
61
62/* Maximum size of response requested or message sent */
63#define MAX_MSG_SIZE	1024
64/* Maximum number of cpus expected to be specified in a cpumask */
65#define MAX_CPUS	32
66
67struct msgtemplate {
68	struct nlmsghdr n;
69	struct genlmsghdr g;
70	char buf[MAX_MSG_SIZE];
71};
72
73char cpumask[100+6*MAX_CPUS];
74
75static void usage(void)
76{
77	fprintf(stderr, "getdelays [-dilv] [-w logfile] [-r bufsize] "
78			"[-m cpumask] [-t tgid] [-p pid]\n");
79	fprintf(stderr, "  -d: print delayacct stats\n");
80	fprintf(stderr, "  -i: print IO accounting (works only with -p)\n");
81	fprintf(stderr, "  -l: listen forever\n");
82	fprintf(stderr, "  -v: debug on\n");
83	fprintf(stderr, "  -C: container path\n");
84}
85
86/*
87 * Create a raw netlink socket and bind
88 */
89static int create_nl_socket(int protocol)
90{
91	int fd;
92	struct sockaddr_nl local;
93
94	fd = socket(AF_NETLINK, SOCK_RAW, protocol);
95	if (fd < 0)
96		return -1;
97
98	if (rcvbufsz)
99		if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF,
100				&rcvbufsz, sizeof(rcvbufsz)) < 0) {
101			fprintf(stderr, "Unable to set socket rcv buf size "
102					"to %d\n",
103				rcvbufsz);
104			return -1;
105		}
106
107	memset(&local, 0, sizeof(local));
108	local.nl_family = AF_NETLINK;
109
110	if (bind(fd, (struct sockaddr *) &local, sizeof(local)) < 0)
111		goto error;
112
113	return fd;
114error:
115	close(fd);
116	return -1;
117}
118
119
120int send_cmd(int sd, __u16 nlmsg_type, __u32 nlmsg_pid,
121	     __u8 genl_cmd, __u16 nla_type,
122	     void *nla_data, int nla_len)
123{
124	struct nlattr *na;
125	struct sockaddr_nl nladdr;
126	int r, buflen;
127	char *buf;
128
129	struct msgtemplate msg;
130
131	msg.n.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN);
132	msg.n.nlmsg_type = nlmsg_type;
133	msg.n.nlmsg_flags = NLM_F_REQUEST;
134	msg.n.nlmsg_seq = 0;
135	msg.n.nlmsg_pid = nlmsg_pid;
136	msg.g.cmd = genl_cmd;
137	msg.g.version = 0x1;
138	na = (struct nlattr *) GENLMSG_DATA(&msg);
139	na->nla_type = nla_type;
140	na->nla_len = nla_len + 1 + NLA_HDRLEN;
141	memcpy(NLA_DATA(na), nla_data, nla_len);
142	msg.n.nlmsg_len += NLMSG_ALIGN(na->nla_len);
143
144	buf = (char *) &msg;
145	buflen = msg.n.nlmsg_len ;
146	memset(&nladdr, 0, sizeof(nladdr));
147	nladdr.nl_family = AF_NETLINK;
148	while ((r = sendto(sd, buf, buflen, 0, (struct sockaddr *) &nladdr,
149			   sizeof(nladdr))) < buflen) {
150		if (r > 0) {
151			buf += r;
152			buflen -= r;
153		} else if (errno != EAGAIN)
154			return -1;
155	}
156	return 0;
157}
158
159
160/*
161 * Probe the controller in genetlink to find the family id
162 * for the TASKSTATS family
163 */
164int get_family_id(int sd)
165{
166	struct {
167		struct nlmsghdr n;
168		struct genlmsghdr g;
169		char buf[256];
170	} ans;
171
172	int id = 0, rc;
173	struct nlattr *na;
174	int rep_len;
175
176	strcpy(name, TASKSTATS_GENL_NAME);
177	rc = send_cmd(sd, GENL_ID_CTRL, getpid(), CTRL_CMD_GETFAMILY,
178			CTRL_ATTR_FAMILY_NAME, (void *)name,
179			strlen(TASKSTATS_GENL_NAME)+1);
180
181	rep_len = recv(sd, &ans, sizeof(ans), 0);
182	if (ans.n.nlmsg_type == NLMSG_ERROR ||
183	    (rep_len < 0) || !NLMSG_OK((&ans.n), rep_len))
184		return 0;
185
186	na = (struct nlattr *) GENLMSG_DATA(&ans);
187	na = (struct nlattr *) ((char *) na + NLA_ALIGN(na->nla_len));
188	if (na->nla_type == CTRL_ATTR_FAMILY_ID) {
189		id = *(__u16 *) NLA_DATA(na);
190	}
191	return id;
192}
193
194void print_delayacct(struct taskstats *t)
195{
196	printf("\n\nCPU   %15s%15s%15s%15s\n"
197	       "      %15llu%15llu%15llu%15llu\n"
198	       "IO    %15s%15s\n"
199	       "      %15llu%15llu\n"
200	       "SWAP  %15s%15s\n"
201	       "      %15llu%15llu\n"
202	       "RECLAIM  %12s%15s\n"
203#ifdef HAVE_STRUCT_TASKSTATS_FREEPAGES_COUNT
204	       "      %15llu%15llu\n"
205#endif
206	       , "count", "real total", "virtual total", "delay total",
207	       (unsigned long long)t->cpu_count,
208	       (unsigned long long)t->cpu_run_real_total,
209	       (unsigned long long)t->cpu_run_virtual_total,
210	       (unsigned long long)t->cpu_delay_total,
211	       "count", "delay total",
212	       (unsigned long long)t->blkio_count,
213	       (unsigned long long)t->blkio_delay_total,
214	       "count", "delay total",
215	       (unsigned long long)t->swapin_count,
216	       (unsigned long long)t->swapin_delay_total,
217	       "count", "delay total"
218#ifdef HAVE_STRUCT_TASKSTATS_FREEPAGES_COUNT
219	       , (unsigned long long)t->freepages_count,
220	       (unsigned long long)t->freepages_delay_total
221#endif
222	       );
223}
224
225void task_context_switch_counts(struct taskstats *t)
226{
227#ifdef HAVE_STRUCT_TASKSTATS_NVCSW
228	printf("\n\nTask   %15s%15s\n"
229	       "       %15llu%15llu\n",
230	       "voluntary", "nonvoluntary",
231	       (unsigned long long)t->nvcsw, (unsigned long long)t->nivcsw);
232#endif
233}
234
235void print_cgroupstats(struct cgroupstats *c)
236{
237	printf("sleeping %llu, blocked %llu, running %llu, stopped %llu, "
238		"uninterruptible %llu\n", (unsigned long long)c->nr_sleeping,
239		(unsigned long long)c->nr_io_wait,
240		(unsigned long long)c->nr_running,
241		(unsigned long long)c->nr_stopped,
242		(unsigned long long)c->nr_uninterruptible);
243}
244
245
246void print_ioacct(struct taskstats *t)
247{
248#ifdef HAVE_STRUCT_TASKSTATS_READ_BYTES
249	printf("%s: read=%llu, write=%llu, cancelled_write=%llu\n",
250		t->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#endif
255}
256
257int main(int argc, char *argv[])
258{
259	int c, rc, rep_len, aggr_len, len2, cmd_type;
260	__u16 id;
261	__u32 mypid;
262
263	struct nlattr *na;
264	int nl_sd = -1;
265	int len = 0;
266	pid_t tid = 0;
267	pid_t rtid = 0;
268
269	int fd = 0;
270	int count = 0;
271	int write_file = 0;
272	int maskset = 0;
273	char *logfile = NULL;
274	int loop = 0;
275	int containerset = 0;
276	char containerpath[1024];
277	int cfd = 0;
278
279	struct msgtemplate msg;
280
281	while (1) {
282		c = getopt(argc, argv, "qdiw:r:m:t:p:vlC:");
283		if (c < 0)
284			break;
285
286		switch (c) {
287		case 'd':
288			printf("print delayacct stats ON\n");
289			print_delays = 1;
290			break;
291		case 'i':
292			printf("printing IO accounting\n");
293			print_io_accounting = 1;
294			break;
295		case 'q':
296			printf("printing task/process context switch rates\n");
297			print_task_context_switch_counts = 1;
298			break;
299		case 'C':
300			containerset = 1;
301			strncpy(containerpath, optarg, strlen(optarg) + 1);
302			break;
303		case 'w':
304			logfile = strdup(optarg);
305			printf("write to file %s\n", logfile);
306			write_file = 1;
307			break;
308		case 'r':
309			rcvbufsz = atoi(optarg);
310			printf("receive buf size %d\n", rcvbufsz);
311			if (rcvbufsz < 0)
312				err(1, "Invalid rcv buf size\n");
313			break;
314		case 'm':
315			strncpy(cpumask, optarg, sizeof(cpumask));
316			maskset = 1;
317			printf("cpumask %s maskset %d\n", cpumask, maskset);
318			break;
319		case 't':
320			tid = atoi(optarg);
321			if (!tid)
322				err(1, "Invalid tgid\n");
323			cmd_type = TASKSTATS_CMD_ATTR_TGID;
324			break;
325		case 'p':
326			tid = atoi(optarg);
327			if (!tid)
328				err(1, "Invalid pid\n");
329			cmd_type = TASKSTATS_CMD_ATTR_PID;
330			break;
331		case 'v':
332			printf("debug on\n");
333			dbg = 1;
334			break;
335		case 'l':
336			printf("listen forever\n");
337			loop = 1;
338			break;
339		default:
340			usage();
341			exit(1);
342		}
343	}
344
345	if (write_file) {
346		fd = open(logfile, O_WRONLY | O_CREAT | O_TRUNC,
347			  S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
348		if (fd == -1) {
349			perror("Cannot open output file\n");
350			exit(1);
351		}
352	}
353
354	if ((nl_sd = create_nl_socket(NETLINK_GENERIC)) < 0)
355		err(1, "error creating Netlink socket\n");
356
357
358	mypid = getpid();
359	id = get_family_id(nl_sd);
360	if (!id) {
361		fprintf(stderr, "Error getting family id, errno %d\n", errno);
362		exit(1);
363	}
364	PRINTF("family id %d\n", id);
365
366	if (maskset) {
367		rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,
368			      TASKSTATS_CMD_ATTR_REGISTER_CPUMASK,
369			      &cpumask, strlen(cpumask) + 1);
370		PRINTF("Sent register cpumask, retval %d\n", rc);
371		if (rc < 0) {
372			fprintf(stderr, "error sending register cpumask\n");
373			exit(1);
374		}
375	}
376
377	if (tid && containerset) {
378		fprintf(stderr, "Select either -t or -C, not both\n");
379		exit(1);
380	}
381
382	if (tid) {
383		rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,
384			      cmd_type, &tid, sizeof(__u32));
385		PRINTF("Sent pid/tgid, retval %d\n", rc);
386		if (rc < 0) {
387			fprintf(stderr, "error sending tid/tgid cmd\n");
388			exit(1);
389		}
390	}
391
392	if (containerset) {
393		cfd = open(containerpath, O_RDONLY);
394		if (cfd < 0) {
395			perror("error opening container file");
396			exit(1);
397		}
398		rc = send_cmd(nl_sd, id, mypid, CGROUPSTATS_CMD_GET,
399			      CGROUPSTATS_CMD_ATTR_FD, &cfd, sizeof(__u32));
400		if (rc < 0) {
401			perror("error sending cgroupstats command");
402			exit(1);
403		}
404	}
405	if (!maskset && !tid && !containerset) {
406		usage();
407		exit(1);
408	}
409
410	do {
411		int i;
412
413		rep_len = recv(nl_sd, &msg, sizeof(msg), 0);
414		PRINTF("received %d bytes\n", rep_len);
415
416		if (rep_len < 0) {
417			fprintf(stderr, "nonfatal reply error: errno %d\n",
418				errno);
419			exit(1);
420		}
421		if (msg.n.nlmsg_type == NLMSG_ERROR ||
422		    !NLMSG_OK((&msg.n), rep_len)) {
423			struct nlmsgerr *err = NLMSG_DATA(&msg);
424			fprintf(stderr, "fatal reply error,  errno %d\n",
425				err->error);
426			exit(1);
427		}
428
429		PRINTF("nlmsghdr size=%zu, nlmsg_len=%d, rep_len=%d\n",
430		       sizeof(struct nlmsghdr), msg.n.nlmsg_len, rep_len);
431
432
433		rep_len = GENLMSG_PAYLOAD(&msg.n);
434
435		na = (struct nlattr *) GENLMSG_DATA(&msg);
436		len = 0;
437		i = 0;
438		while (len < rep_len) {
439			len += NLA_ALIGN(na->nla_len);
440			switch (na->nla_type) {
441			case TASKSTATS_TYPE_AGGR_TGID:
442				/* Fall through */
443			case TASKSTATS_TYPE_AGGR_PID:
444				aggr_len = NLA_PAYLOAD(na->nla_len);
445				len2 = 0;
446				/* For nested attributes, na follows */
447				na = (struct nlattr *) NLA_DATA(na);
448				done = 0;
449				while (len2 < aggr_len) {
450					switch (na->nla_type) {
451					case TASKSTATS_TYPE_PID:
452						rtid = *(int *) NLA_DATA(na);
453						if (print_delays)
454							printf("PID\t%d\n", rtid);
455						break;
456					case TASKSTATS_TYPE_TGID:
457						rtid = *(int *) NLA_DATA(na);
458						if (print_delays)
459							printf("TGID\t%d\n", rtid);
460						break;
461					case TASKSTATS_TYPE_STATS:
462						count++;
463						if (print_delays)
464							print_delayacct((struct taskstats *) NLA_DATA(na));
465						if (print_io_accounting)
466							print_ioacct((struct taskstats *) NLA_DATA(na));
467						if (print_task_context_switch_counts)
468							task_context_switch_counts((struct taskstats *) NLA_DATA(na));
469						if (fd) {
470							if (write(fd, NLA_DATA(na), na->nla_len) < 0) {
471								err(1,"write error\n");
472							}
473						}
474						if (!loop)
475							goto done;
476						break;
477					default:
478						fprintf(stderr, "Unknown nested"
479							" nla_type %d\n",
480							na->nla_type);
481						break;
482					}
483					len2 += NLA_ALIGN(na->nla_len);
484					na = (struct nlattr *) ((char *) na + len2);
485				}
486				break;
487
488			case CGROUPSTATS_TYPE_CGROUP_STATS:
489				print_cgroupstats(NLA_DATA(na));
490				break;
491			default:
492				fprintf(stderr, "Unknown nla_type %d\n",
493					na->nla_type);
494				exit(1);
495			}
496			na = (struct nlattr *) (GENLMSG_DATA(&msg) + len);
497		}
498	} while (loop);
499done:
500	if (maskset) {
501		rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,
502			      TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK,
503			      &cpumask, strlen(cpumask) + 1);
504		printf("Sent deregister mask, retval %d\n", rc);
505		if (rc < 0)
506			err(rc, "error sending deregister cpumask\n");
507	}
508
509	close(nl_sd);
510	if (fd)
511		close(fd);
512	if (cfd)
513		close(cfd);
514	return 0;
515}
516