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