Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1// SPDX-License-Identifier: GPL-2.0
2/* procacct.c
3 *
4 * Demonstrator of fetching resource data on task exit, as a way
5 * to accumulate accurate program resource usage statistics, without
6 * prior identification of the programs. For that, the fields for
7 * device and inode of the program executable binary file are also
8 * extracted in addition to the command string.
9 *
10 * The TGID together with the PID and the AGROUP flag allow
11 * identification of threads in a process and single-threaded processes.
12 * The ac_tgetime field gives proper whole-process walltime.
13 *
14 * Written (changed) by Thomas Orgis, University of Hamburg in 2022
15 *
16 * This is a cheap derivation (inheriting the style) of getdelays.c:
17 *
18 * Utility to get per-pid and per-tgid delay accounting statistics
19 * Also illustrates usage of the taskstats interface
20 *
21 * Copyright (C) Shailabh Nagar, IBM Corp. 2005
22 * Copyright (C) Balbir Singh, IBM Corp. 2006
23 * Copyright (c) Jay Lan, SGI. 2006
24 */
25
26#include <stdio.h>
27#include <stdlib.h>
28#include <errno.h>
29#include <unistd.h>
30#include <poll.h>
31#include <string.h>
32#include <fcntl.h>
33#include <sys/types.h>
34#include <sys/stat.h>
35#include <sys/socket.h>
36#include <sys/wait.h>
37#include <signal.h>
38
39#include <linux/genetlink.h>
40#include <linux/acct.h>
41#include <linux/taskstats.h>
42#include <linux/kdev_t.h>
43
44/*
45 * Generic macros for dealing with netlink sockets. Might be duplicated
46 * elsewhere. It is recommended that commercial grade applications use
47 * libnl or libnetlink and use the interfaces provided by the library
48 */
49#define GENLMSG_DATA(glh) ((void *)(NLMSG_DATA(glh) + GENL_HDRLEN))
50#define GENLMSG_PAYLOAD(glh) (NLMSG_PAYLOAD(glh, 0) - GENL_HDRLEN)
51#define NLA_DATA(na) ((void *)((char *)(na) + NLA_HDRLEN))
52#define NLA_PAYLOAD(len) (len - NLA_HDRLEN)
53
54#define err(code, fmt, arg...) \
55 do { \
56 fprintf(stderr, fmt, ##arg); \
57 exit(code); \
58 } while (0)
59
60int rcvbufsz;
61char name[100];
62int dbg;
63int print_delays;
64int print_io_accounting;
65int print_task_context_switch_counts;
66
67#define PRINTF(fmt, arg...) { \
68 if (dbg) { \
69 printf(fmt, ##arg); \
70 } \
71 }
72
73/* Maximum size of response requested or message sent */
74#define MAX_MSG_SIZE 2048
75/* Maximum number of cpus expected to be specified in a cpumask */
76#define MAX_CPUS 32
77
78struct msgtemplate {
79 struct nlmsghdr n;
80 struct genlmsghdr g;
81 char buf[MAX_MSG_SIZE];
82};
83
84char cpumask[100+6*MAX_CPUS];
85
86static void usage(void)
87{
88 fprintf(stderr, "procacct [-v] [-w logfile] [-r bufsize] [-m cpumask]\n");
89 fprintf(stderr, " -v: debug on\n");
90}
91
92/*
93 * Create a raw netlink socket and bind
94 */
95static int create_nl_socket(int protocol)
96{
97 int fd;
98 struct sockaddr_nl local;
99
100 fd = socket(AF_NETLINK, SOCK_RAW, protocol);
101 if (fd < 0)
102 return -1;
103
104 if (rcvbufsz)
105 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF,
106 &rcvbufsz, sizeof(rcvbufsz)) < 0) {
107 fprintf(stderr, "Unable to set socket rcv buf size to %d\n",
108 rcvbufsz);
109 goto error;
110 }
111
112 memset(&local, 0, sizeof(local));
113 local.nl_family = AF_NETLINK;
114
115 if (bind(fd, (struct sockaddr *) &local, sizeof(local)) < 0)
116 goto error;
117
118 return fd;
119error:
120 close(fd);
121 return -1;
122}
123
124static int recv_taskstats_msg(int sd, struct msgtemplate *msg)
125{
126 struct sockaddr_nl nladdr;
127 struct iovec iov = {
128 .iov_base = msg,
129 .iov_len = sizeof(*msg),
130 };
131 struct msghdr hdr = {
132 .msg_name = &nladdr,
133 .msg_namelen = sizeof(nladdr),
134 .msg_iov = &iov,
135 .msg_iovlen = 1,
136 };
137 int ret;
138
139 ret = recvmsg(sd, &hdr, 0);
140 if (ret < 0)
141 return -1;
142 if (hdr.msg_flags & MSG_TRUNC) {
143 errno = EMSGSIZE;
144 return -1;
145 }
146
147 return ret;
148}
149
150
151static int send_cmd(int sd, __u16 nlmsg_type, __u32 nlmsg_pid,
152 __u8 genl_cmd, __u16 nla_type,
153 void *nla_data, int nla_len)
154{
155 struct nlattr *na;
156 struct sockaddr_nl nladdr;
157 int r, buflen;
158 char *buf;
159
160 struct msgtemplate msg;
161
162 msg.n.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN);
163 msg.n.nlmsg_type = nlmsg_type;
164 msg.n.nlmsg_flags = NLM_F_REQUEST;
165 msg.n.nlmsg_seq = 0;
166 msg.n.nlmsg_pid = nlmsg_pid;
167 msg.g.cmd = genl_cmd;
168 msg.g.version = 0x1;
169 na = (struct nlattr *) GENLMSG_DATA(&msg);
170 na->nla_type = nla_type;
171 na->nla_len = nla_len + 1 + NLA_HDRLEN;
172 memcpy(NLA_DATA(na), nla_data, nla_len);
173 msg.n.nlmsg_len += NLMSG_ALIGN(na->nla_len);
174
175 buf = (char *) &msg;
176 buflen = msg.n.nlmsg_len;
177 memset(&nladdr, 0, sizeof(nladdr));
178 nladdr.nl_family = AF_NETLINK;
179 while ((r = sendto(sd, buf, buflen, 0, (struct sockaddr *) &nladdr,
180 sizeof(nladdr))) < buflen) {
181 if (r > 0) {
182 buf += r;
183 buflen -= r;
184 } else if (errno != EAGAIN)
185 return -1;
186 }
187 return 0;
188}
189
190
191/*
192 * Probe the controller in genetlink to find the family id
193 * for the TASKSTATS family
194 */
195static int get_family_id(int sd)
196{
197 struct {
198 struct nlmsghdr n;
199 struct genlmsghdr g;
200 char buf[256];
201 } ans;
202
203 int id = 0, rc;
204 struct nlattr *na;
205 int rep_len;
206
207 strcpy(name, TASKSTATS_GENL_NAME);
208 rc = send_cmd(sd, GENL_ID_CTRL, getpid(), CTRL_CMD_GETFAMILY,
209 CTRL_ATTR_FAMILY_NAME, (void *)name,
210 strlen(TASKSTATS_GENL_NAME)+1);
211 if (rc < 0)
212 return 0; /* sendto() failure? */
213
214 rep_len = recv(sd, &ans, sizeof(ans), 0);
215 if (ans.n.nlmsg_type == NLMSG_ERROR ||
216 (rep_len < 0) || !NLMSG_OK((&ans.n), rep_len))
217 return 0;
218
219 na = (struct nlattr *) GENLMSG_DATA(&ans);
220 na = (struct nlattr *) ((char *) na + NLA_ALIGN(na->nla_len));
221 if (na->nla_type == CTRL_ATTR_FAMILY_ID)
222 id = *(__u16 *) NLA_DATA(na);
223
224 return id;
225}
226
227#define average_ms(t, c) (t / 1000000ULL / (c ? c : 1))
228
229static void print_procacct(struct taskstats *t)
230{
231 /* First letter: T is a mere thread, G the last in a group, U unknown. */
232 printf(
233 "%c pid=%lu tgid=%lu uid=%lu wall=%llu gwall=%llu cpu=%llu vmpeak=%llu rsspeak=%llu dev=%lu:%lu inode=%llu comm=%s\n"
234 , t->version >= 12 ? (t->ac_flag & AGROUP ? 'P' : 'T') : '?'
235 , (unsigned long)t->ac_pid
236 , (unsigned long)(t->version >= 12 ? t->ac_tgid : 0)
237 , (unsigned long)t->ac_uid
238 , (unsigned long long)t->ac_etime
239 , (unsigned long long)(t->version >= 12 ? t->ac_tgetime : 0)
240 , (unsigned long long)(t->ac_utime+t->ac_stime)
241 , (unsigned long long)t->hiwater_vm
242 , (unsigned long long)t->hiwater_rss
243 , (unsigned long)(t->version >= 12 ? MAJOR(t->ac_exe_dev) : 0)
244 , (unsigned long)(t->version >= 12 ? MINOR(t->ac_exe_dev) : 0)
245 , (unsigned long long)(t->version >= 12 ? t->ac_exe_inode : 0)
246 , t->ac_comm
247 );
248}
249
250void handle_aggr(int mother, struct nlattr *na, int fd)
251{
252 int aggr_len = NLA_PAYLOAD(na->nla_len);
253 int len2 = 0;
254 pid_t rtid = 0;
255
256 na = (struct nlattr *) NLA_DATA(na);
257 while (len2 < aggr_len) {
258 switch (na->nla_type) {
259 case TASKSTATS_TYPE_PID:
260 rtid = *(int *) NLA_DATA(na);
261 PRINTF("PID\t%d\n", rtid);
262 break;
263 case TASKSTATS_TYPE_TGID:
264 rtid = *(int *) NLA_DATA(na);
265 PRINTF("TGID\t%d\n", rtid);
266 break;
267 case TASKSTATS_TYPE_STATS:
268 PRINTF("version %u\n",
269 ((struct taskstats *)NLA_DATA(na))->version);
270 if (mother == TASKSTATS_TYPE_AGGR_PID)
271 print_procacct((struct taskstats *) NLA_DATA(na));
272 if (fd) {
273 if (write(fd, NLA_DATA(na), na->nla_len) < 0)
274 err(1, "write error\n");
275 }
276 break;
277 case TASKSTATS_TYPE_NULL:
278 break;
279 default:
280 fprintf(stderr, "Unknown nested nla_type %d\n",
281 na->nla_type);
282 break;
283 }
284 len2 += NLA_ALIGN(na->nla_len);
285 na = (struct nlattr *)((char *)na +
286 NLA_ALIGN(na->nla_len));
287 }
288}
289
290int main(int argc, char *argv[])
291{
292 int c, rc, rep_len;
293 __u16 id;
294 __u32 mypid;
295
296 struct nlattr *na;
297 int nl_sd = -1;
298 int len = 0;
299
300 int fd = 0;
301 int write_file = 0;
302 int maskset = 0;
303 char *logfile = NULL;
304 int cfd = 0;
305
306 struct msgtemplate msg;
307
308 while (1) {
309 c = getopt(argc, argv, "m:vr:w:");
310 if (c < 0)
311 break;
312
313 switch (c) {
314 case 'w':
315 logfile = strdup(optarg);
316 printf("write to file %s\n", logfile);
317 write_file = 1;
318 break;
319 case 'r':
320 rcvbufsz = atoi(optarg);
321 printf("receive buf size %d\n", rcvbufsz);
322 if (rcvbufsz < 0)
323 err(1, "Invalid rcv buf size\n");
324 break;
325 case 'm':
326 strncpy(cpumask, optarg, sizeof(cpumask));
327 cpumask[sizeof(cpumask) - 1] = '\0';
328 maskset = 1;
329 break;
330 case 'v':
331 printf("debug on\n");
332 dbg = 1;
333 break;
334 default:
335 usage();
336 exit(-1);
337 }
338 }
339 if (!maskset) {
340 maskset = 1;
341 strncpy(cpumask, "1", sizeof(cpumask));
342 cpumask[sizeof(cpumask) - 1] = '\0';
343 }
344 printf("cpumask %s maskset %d\n", cpumask, maskset);
345
346 if (write_file) {
347 fd = open(logfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
348 if (fd == -1) {
349 perror("Cannot open output file\n");
350 exit(1);
351 }
352 }
353
354 nl_sd = create_nl_socket(NETLINK_GENERIC);
355 if (nl_sd < 0)
356 err(1, "error creating Netlink socket\n");
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 goto err;
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 goto err;
374 }
375 }
376
377 do {
378 rep_len = recv_taskstats_msg(nl_sd, &msg);
379 PRINTF("received %d bytes\n", rep_len);
380
381 if (rep_len < 0) {
382 if (errno == EMSGSIZE)
383 fprintf(stderr,
384 "dropped truncated taskstats netlink message, please increase MAX_MSG_SIZE\n");
385 else
386 fprintf(stderr, "nonfatal reply error: errno %d\n",
387 errno);
388 continue;
389 }
390 if (msg.n.nlmsg_type == NLMSG_ERROR ||
391 !NLMSG_OK((&msg.n), rep_len)) {
392 struct nlmsgerr *err = NLMSG_DATA(&msg);
393
394 fprintf(stderr, "fatal reply error, errno %d\n",
395 err->error);
396 goto done;
397 }
398
399 PRINTF("nlmsghdr size=%zu, nlmsg_len=%d, rep_len=%d\n",
400 sizeof(struct nlmsghdr), msg.n.nlmsg_len, rep_len);
401
402
403 rep_len = GENLMSG_PAYLOAD(&msg.n);
404
405 na = (struct nlattr *) GENLMSG_DATA(&msg);
406 len = 0;
407 while (len < rep_len) {
408 len += NLA_ALIGN(na->nla_len);
409 int mother = na->nla_type;
410
411 PRINTF("mother=%i\n", mother);
412 switch (na->nla_type) {
413 case TASKSTATS_TYPE_AGGR_PID:
414 case TASKSTATS_TYPE_AGGR_TGID:
415 /* For nested attributes, na follows */
416 handle_aggr(mother, na, fd);
417 break;
418 default:
419 fprintf(stderr, "Unexpected nla_type %d\n",
420 na->nla_type);
421 case TASKSTATS_TYPE_NULL:
422 break;
423 }
424 na = (struct nlattr *) (GENLMSG_DATA(&msg) + len);
425 }
426 } while (1);
427done:
428 if (maskset) {
429 rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,
430 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK,
431 &cpumask, strlen(cpumask) + 1);
432 printf("Sent deregister mask, retval %d\n", rc);
433 if (rc < 0)
434 err(rc, "error sending deregister cpumask\n");
435 }
436err:
437 close(nl_sd);
438 if (fd)
439 close(fd);
440 if (cfd)
441 close(cfd);
442 return 0;
443}