xref: /openbmc/linux/kernel/taskstats.c (revision 489111e5)
1 /*
2  * taskstats.c - Export per-task statistics to userland
3  *
4  * Copyright (C) Shailabh Nagar, IBM Corp. 2006
5  *           (C) Balbir Singh,   IBM Corp. 2006
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  */
18 
19 #include <linux/kernel.h>
20 #include <linux/taskstats_kern.h>
21 #include <linux/tsacct_kern.h>
22 #include <linux/delayacct.h>
23 #include <linux/cpumask.h>
24 #include <linux/percpu.h>
25 #include <linux/slab.h>
26 #include <linux/cgroupstats.h>
27 #include <linux/cgroup.h>
28 #include <linux/fs.h>
29 #include <linux/file.h>
30 #include <linux/pid_namespace.h>
31 #include <net/genetlink.h>
32 #include <linux/atomic.h>
33 
34 /*
35  * Maximum length of a cpumask that can be specified in
36  * the TASKSTATS_CMD_ATTR_REGISTER/DEREGISTER_CPUMASK attribute
37  */
38 #define TASKSTATS_CPUMASK_MAXLEN	(100+6*NR_CPUS)
39 
40 static DEFINE_PER_CPU(__u32, taskstats_seqnum);
41 static int family_registered;
42 struct kmem_cache *taskstats_cache;
43 
44 static struct genl_family family;
45 
46 static const struct nla_policy taskstats_cmd_get_policy[TASKSTATS_CMD_ATTR_MAX+1] = {
47 	[TASKSTATS_CMD_ATTR_PID]  = { .type = NLA_U32 },
48 	[TASKSTATS_CMD_ATTR_TGID] = { .type = NLA_U32 },
49 	[TASKSTATS_CMD_ATTR_REGISTER_CPUMASK] = { .type = NLA_STRING },
50 	[TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK] = { .type = NLA_STRING },};
51 
52 static const struct nla_policy cgroupstats_cmd_get_policy[CGROUPSTATS_CMD_ATTR_MAX+1] = {
53 	[CGROUPSTATS_CMD_ATTR_FD] = { .type = NLA_U32 },
54 };
55 
56 struct listener {
57 	struct list_head list;
58 	pid_t pid;
59 	char valid;
60 };
61 
62 struct listener_list {
63 	struct rw_semaphore sem;
64 	struct list_head list;
65 };
66 static DEFINE_PER_CPU(struct listener_list, listener_array);
67 
68 enum actions {
69 	REGISTER,
70 	DEREGISTER,
71 	CPU_DONT_CARE
72 };
73 
74 static int prepare_reply(struct genl_info *info, u8 cmd, struct sk_buff **skbp,
75 				size_t size)
76 {
77 	struct sk_buff *skb;
78 	void *reply;
79 
80 	/*
81 	 * If new attributes are added, please revisit this allocation
82 	 */
83 	skb = genlmsg_new(size, GFP_KERNEL);
84 	if (!skb)
85 		return -ENOMEM;
86 
87 	if (!info) {
88 		int seq = this_cpu_inc_return(taskstats_seqnum) - 1;
89 
90 		reply = genlmsg_put(skb, 0, seq, &family, 0, cmd);
91 	} else
92 		reply = genlmsg_put_reply(skb, info, &family, 0, cmd);
93 	if (reply == NULL) {
94 		nlmsg_free(skb);
95 		return -EINVAL;
96 	}
97 
98 	*skbp = skb;
99 	return 0;
100 }
101 
102 /*
103  * Send taskstats data in @skb to listener with nl_pid @pid
104  */
105 static int send_reply(struct sk_buff *skb, struct genl_info *info)
106 {
107 	struct genlmsghdr *genlhdr = nlmsg_data(nlmsg_hdr(skb));
108 	void *reply = genlmsg_data(genlhdr);
109 
110 	genlmsg_end(skb, reply);
111 
112 	return genlmsg_reply(skb, info);
113 }
114 
115 /*
116  * Send taskstats data in @skb to listeners registered for @cpu's exit data
117  */
118 static void send_cpu_listeners(struct sk_buff *skb,
119 					struct listener_list *listeners)
120 {
121 	struct genlmsghdr *genlhdr = nlmsg_data(nlmsg_hdr(skb));
122 	struct listener *s, *tmp;
123 	struct sk_buff *skb_next, *skb_cur = skb;
124 	void *reply = genlmsg_data(genlhdr);
125 	int rc, delcount = 0;
126 
127 	genlmsg_end(skb, reply);
128 
129 	rc = 0;
130 	down_read(&listeners->sem);
131 	list_for_each_entry(s, &listeners->list, list) {
132 		skb_next = NULL;
133 		if (!list_is_last(&s->list, &listeners->list)) {
134 			skb_next = skb_clone(skb_cur, GFP_KERNEL);
135 			if (!skb_next)
136 				break;
137 		}
138 		rc = genlmsg_unicast(&init_net, skb_cur, s->pid);
139 		if (rc == -ECONNREFUSED) {
140 			s->valid = 0;
141 			delcount++;
142 		}
143 		skb_cur = skb_next;
144 	}
145 	up_read(&listeners->sem);
146 
147 	if (skb_cur)
148 		nlmsg_free(skb_cur);
149 
150 	if (!delcount)
151 		return;
152 
153 	/* Delete invalidated entries */
154 	down_write(&listeners->sem);
155 	list_for_each_entry_safe(s, tmp, &listeners->list, list) {
156 		if (!s->valid) {
157 			list_del(&s->list);
158 			kfree(s);
159 		}
160 	}
161 	up_write(&listeners->sem);
162 }
163 
164 static void fill_stats(struct user_namespace *user_ns,
165 		       struct pid_namespace *pid_ns,
166 		       struct task_struct *tsk, struct taskstats *stats)
167 {
168 	memset(stats, 0, sizeof(*stats));
169 	/*
170 	 * Each accounting subsystem adds calls to its functions to
171 	 * fill in relevant parts of struct taskstsats as follows
172 	 *
173 	 *	per-task-foo(stats, tsk);
174 	 */
175 
176 	delayacct_add_tsk(stats, tsk);
177 
178 	/* fill in basic acct fields */
179 	stats->version = TASKSTATS_VERSION;
180 	stats->nvcsw = tsk->nvcsw;
181 	stats->nivcsw = tsk->nivcsw;
182 	bacct_add_tsk(user_ns, pid_ns, stats, tsk);
183 
184 	/* fill in extended acct fields */
185 	xacct_add_tsk(stats, tsk);
186 }
187 
188 static int fill_stats_for_pid(pid_t pid, struct taskstats *stats)
189 {
190 	struct task_struct *tsk;
191 
192 	rcu_read_lock();
193 	tsk = find_task_by_vpid(pid);
194 	if (tsk)
195 		get_task_struct(tsk);
196 	rcu_read_unlock();
197 	if (!tsk)
198 		return -ESRCH;
199 	fill_stats(current_user_ns(), task_active_pid_ns(current), tsk, stats);
200 	put_task_struct(tsk);
201 	return 0;
202 }
203 
204 static int fill_stats_for_tgid(pid_t tgid, struct taskstats *stats)
205 {
206 	struct task_struct *tsk, *first;
207 	unsigned long flags;
208 	int rc = -ESRCH;
209 
210 	/*
211 	 * Add additional stats from live tasks except zombie thread group
212 	 * leaders who are already counted with the dead tasks
213 	 */
214 	rcu_read_lock();
215 	first = find_task_by_vpid(tgid);
216 
217 	if (!first || !lock_task_sighand(first, &flags))
218 		goto out;
219 
220 	if (first->signal->stats)
221 		memcpy(stats, first->signal->stats, sizeof(*stats));
222 	else
223 		memset(stats, 0, sizeof(*stats));
224 
225 	tsk = first;
226 	do {
227 		if (tsk->exit_state)
228 			continue;
229 		/*
230 		 * Accounting subsystem can call its functions here to
231 		 * fill in relevant parts of struct taskstsats as follows
232 		 *
233 		 *	per-task-foo(stats, tsk);
234 		 */
235 		delayacct_add_tsk(stats, tsk);
236 
237 		stats->nvcsw += tsk->nvcsw;
238 		stats->nivcsw += tsk->nivcsw;
239 	} while_each_thread(first, tsk);
240 
241 	unlock_task_sighand(first, &flags);
242 	rc = 0;
243 out:
244 	rcu_read_unlock();
245 
246 	stats->version = TASKSTATS_VERSION;
247 	/*
248 	 * Accounting subsystems can also add calls here to modify
249 	 * fields of taskstats.
250 	 */
251 	return rc;
252 }
253 
254 static void fill_tgid_exit(struct task_struct *tsk)
255 {
256 	unsigned long flags;
257 
258 	spin_lock_irqsave(&tsk->sighand->siglock, flags);
259 	if (!tsk->signal->stats)
260 		goto ret;
261 
262 	/*
263 	 * Each accounting subsystem calls its functions here to
264 	 * accumalate its per-task stats for tsk, into the per-tgid structure
265 	 *
266 	 *	per-task-foo(tsk->signal->stats, tsk);
267 	 */
268 	delayacct_add_tsk(tsk->signal->stats, tsk);
269 ret:
270 	spin_unlock_irqrestore(&tsk->sighand->siglock, flags);
271 	return;
272 }
273 
274 static int add_del_listener(pid_t pid, const struct cpumask *mask, int isadd)
275 {
276 	struct listener_list *listeners;
277 	struct listener *s, *tmp, *s2;
278 	unsigned int cpu;
279 	int ret = 0;
280 
281 	if (!cpumask_subset(mask, cpu_possible_mask))
282 		return -EINVAL;
283 
284 	if (current_user_ns() != &init_user_ns)
285 		return -EINVAL;
286 
287 	if (task_active_pid_ns(current) != &init_pid_ns)
288 		return -EINVAL;
289 
290 	if (isadd == REGISTER) {
291 		for_each_cpu(cpu, mask) {
292 			s = kmalloc_node(sizeof(struct listener),
293 					GFP_KERNEL, cpu_to_node(cpu));
294 			if (!s) {
295 				ret = -ENOMEM;
296 				goto cleanup;
297 			}
298 			s->pid = pid;
299 			s->valid = 1;
300 
301 			listeners = &per_cpu(listener_array, cpu);
302 			down_write(&listeners->sem);
303 			list_for_each_entry(s2, &listeners->list, list) {
304 				if (s2->pid == pid && s2->valid)
305 					goto exists;
306 			}
307 			list_add(&s->list, &listeners->list);
308 			s = NULL;
309 exists:
310 			up_write(&listeners->sem);
311 			kfree(s); /* nop if NULL */
312 		}
313 		return 0;
314 	}
315 
316 	/* Deregister or cleanup */
317 cleanup:
318 	for_each_cpu(cpu, mask) {
319 		listeners = &per_cpu(listener_array, cpu);
320 		down_write(&listeners->sem);
321 		list_for_each_entry_safe(s, tmp, &listeners->list, list) {
322 			if (s->pid == pid) {
323 				list_del(&s->list);
324 				kfree(s);
325 				break;
326 			}
327 		}
328 		up_write(&listeners->sem);
329 	}
330 	return ret;
331 }
332 
333 static int parse(struct nlattr *na, struct cpumask *mask)
334 {
335 	char *data;
336 	int len;
337 	int ret;
338 
339 	if (na == NULL)
340 		return 1;
341 	len = nla_len(na);
342 	if (len > TASKSTATS_CPUMASK_MAXLEN)
343 		return -E2BIG;
344 	if (len < 1)
345 		return -EINVAL;
346 	data = kmalloc(len, GFP_KERNEL);
347 	if (!data)
348 		return -ENOMEM;
349 	nla_strlcpy(data, na, len);
350 	ret = cpulist_parse(data, mask);
351 	kfree(data);
352 	return ret;
353 }
354 
355 static struct taskstats *mk_reply(struct sk_buff *skb, int type, u32 pid)
356 {
357 	struct nlattr *na, *ret;
358 	int aggr;
359 
360 	aggr = (type == TASKSTATS_TYPE_PID)
361 			? TASKSTATS_TYPE_AGGR_PID
362 			: TASKSTATS_TYPE_AGGR_TGID;
363 
364 	na = nla_nest_start(skb, aggr);
365 	if (!na)
366 		goto err;
367 
368 	if (nla_put(skb, type, sizeof(pid), &pid) < 0) {
369 		nla_nest_cancel(skb, na);
370 		goto err;
371 	}
372 	ret = nla_reserve_64bit(skb, TASKSTATS_TYPE_STATS,
373 				sizeof(struct taskstats), TASKSTATS_TYPE_NULL);
374 	if (!ret) {
375 		nla_nest_cancel(skb, na);
376 		goto err;
377 	}
378 	nla_nest_end(skb, na);
379 
380 	return nla_data(ret);
381 err:
382 	return NULL;
383 }
384 
385 static int cgroupstats_user_cmd(struct sk_buff *skb, struct genl_info *info)
386 {
387 	int rc = 0;
388 	struct sk_buff *rep_skb;
389 	struct cgroupstats *stats;
390 	struct nlattr *na;
391 	size_t size;
392 	u32 fd;
393 	struct fd f;
394 
395 	na = info->attrs[CGROUPSTATS_CMD_ATTR_FD];
396 	if (!na)
397 		return -EINVAL;
398 
399 	fd = nla_get_u32(info->attrs[CGROUPSTATS_CMD_ATTR_FD]);
400 	f = fdget(fd);
401 	if (!f.file)
402 		return 0;
403 
404 	size = nla_total_size(sizeof(struct cgroupstats));
405 
406 	rc = prepare_reply(info, CGROUPSTATS_CMD_NEW, &rep_skb,
407 				size);
408 	if (rc < 0)
409 		goto err;
410 
411 	na = nla_reserve(rep_skb, CGROUPSTATS_TYPE_CGROUP_STATS,
412 				sizeof(struct cgroupstats));
413 	if (na == NULL) {
414 		nlmsg_free(rep_skb);
415 		rc = -EMSGSIZE;
416 		goto err;
417 	}
418 
419 	stats = nla_data(na);
420 	memset(stats, 0, sizeof(*stats));
421 
422 	rc = cgroupstats_build(stats, f.file->f_path.dentry);
423 	if (rc < 0) {
424 		nlmsg_free(rep_skb);
425 		goto err;
426 	}
427 
428 	rc = send_reply(rep_skb, info);
429 
430 err:
431 	fdput(f);
432 	return rc;
433 }
434 
435 static int cmd_attr_register_cpumask(struct genl_info *info)
436 {
437 	cpumask_var_t mask;
438 	int rc;
439 
440 	if (!alloc_cpumask_var(&mask, GFP_KERNEL))
441 		return -ENOMEM;
442 	rc = parse(info->attrs[TASKSTATS_CMD_ATTR_REGISTER_CPUMASK], mask);
443 	if (rc < 0)
444 		goto out;
445 	rc = add_del_listener(info->snd_portid, mask, REGISTER);
446 out:
447 	free_cpumask_var(mask);
448 	return rc;
449 }
450 
451 static int cmd_attr_deregister_cpumask(struct genl_info *info)
452 {
453 	cpumask_var_t mask;
454 	int rc;
455 
456 	if (!alloc_cpumask_var(&mask, GFP_KERNEL))
457 		return -ENOMEM;
458 	rc = parse(info->attrs[TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK], mask);
459 	if (rc < 0)
460 		goto out;
461 	rc = add_del_listener(info->snd_portid, mask, DEREGISTER);
462 out:
463 	free_cpumask_var(mask);
464 	return rc;
465 }
466 
467 static size_t taskstats_packet_size(void)
468 {
469 	size_t size;
470 
471 	size = nla_total_size(sizeof(u32)) +
472 		nla_total_size_64bit(sizeof(struct taskstats)) +
473 		nla_total_size(0);
474 
475 	return size;
476 }
477 
478 static int cmd_attr_pid(struct genl_info *info)
479 {
480 	struct taskstats *stats;
481 	struct sk_buff *rep_skb;
482 	size_t size;
483 	u32 pid;
484 	int rc;
485 
486 	size = taskstats_packet_size();
487 
488 	rc = prepare_reply(info, TASKSTATS_CMD_NEW, &rep_skb, size);
489 	if (rc < 0)
490 		return rc;
491 
492 	rc = -EINVAL;
493 	pid = nla_get_u32(info->attrs[TASKSTATS_CMD_ATTR_PID]);
494 	stats = mk_reply(rep_skb, TASKSTATS_TYPE_PID, pid);
495 	if (!stats)
496 		goto err;
497 
498 	rc = fill_stats_for_pid(pid, stats);
499 	if (rc < 0)
500 		goto err;
501 	return send_reply(rep_skb, info);
502 err:
503 	nlmsg_free(rep_skb);
504 	return rc;
505 }
506 
507 static int cmd_attr_tgid(struct genl_info *info)
508 {
509 	struct taskstats *stats;
510 	struct sk_buff *rep_skb;
511 	size_t size;
512 	u32 tgid;
513 	int rc;
514 
515 	size = taskstats_packet_size();
516 
517 	rc = prepare_reply(info, TASKSTATS_CMD_NEW, &rep_skb, size);
518 	if (rc < 0)
519 		return rc;
520 
521 	rc = -EINVAL;
522 	tgid = nla_get_u32(info->attrs[TASKSTATS_CMD_ATTR_TGID]);
523 	stats = mk_reply(rep_skb, TASKSTATS_TYPE_TGID, tgid);
524 	if (!stats)
525 		goto err;
526 
527 	rc = fill_stats_for_tgid(tgid, stats);
528 	if (rc < 0)
529 		goto err;
530 	return send_reply(rep_skb, info);
531 err:
532 	nlmsg_free(rep_skb);
533 	return rc;
534 }
535 
536 static int taskstats_user_cmd(struct sk_buff *skb, struct genl_info *info)
537 {
538 	if (info->attrs[TASKSTATS_CMD_ATTR_REGISTER_CPUMASK])
539 		return cmd_attr_register_cpumask(info);
540 	else if (info->attrs[TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK])
541 		return cmd_attr_deregister_cpumask(info);
542 	else if (info->attrs[TASKSTATS_CMD_ATTR_PID])
543 		return cmd_attr_pid(info);
544 	else if (info->attrs[TASKSTATS_CMD_ATTR_TGID])
545 		return cmd_attr_tgid(info);
546 	else
547 		return -EINVAL;
548 }
549 
550 static struct taskstats *taskstats_tgid_alloc(struct task_struct *tsk)
551 {
552 	struct signal_struct *sig = tsk->signal;
553 	struct taskstats *stats;
554 
555 	if (sig->stats || thread_group_empty(tsk))
556 		goto ret;
557 
558 	/* No problem if kmem_cache_zalloc() fails */
559 	stats = kmem_cache_zalloc(taskstats_cache, GFP_KERNEL);
560 
561 	spin_lock_irq(&tsk->sighand->siglock);
562 	if (!sig->stats) {
563 		sig->stats = stats;
564 		stats = NULL;
565 	}
566 	spin_unlock_irq(&tsk->sighand->siglock);
567 
568 	if (stats)
569 		kmem_cache_free(taskstats_cache, stats);
570 ret:
571 	return sig->stats;
572 }
573 
574 /* Send pid data out on exit */
575 void taskstats_exit(struct task_struct *tsk, int group_dead)
576 {
577 	int rc;
578 	struct listener_list *listeners;
579 	struct taskstats *stats;
580 	struct sk_buff *rep_skb;
581 	size_t size;
582 	int is_thread_group;
583 
584 	if (!family_registered)
585 		return;
586 
587 	/*
588 	 * Size includes space for nested attributes
589 	 */
590 	size = taskstats_packet_size();
591 
592 	is_thread_group = !!taskstats_tgid_alloc(tsk);
593 	if (is_thread_group) {
594 		/* PID + STATS + TGID + STATS */
595 		size = 2 * size;
596 		/* fill the tsk->signal->stats structure */
597 		fill_tgid_exit(tsk);
598 	}
599 
600 	listeners = raw_cpu_ptr(&listener_array);
601 	if (list_empty(&listeners->list))
602 		return;
603 
604 	rc = prepare_reply(NULL, TASKSTATS_CMD_NEW, &rep_skb, size);
605 	if (rc < 0)
606 		return;
607 
608 	stats = mk_reply(rep_skb, TASKSTATS_TYPE_PID,
609 			 task_pid_nr_ns(tsk, &init_pid_ns));
610 	if (!stats)
611 		goto err;
612 
613 	fill_stats(&init_user_ns, &init_pid_ns, tsk, stats);
614 
615 	/*
616 	 * Doesn't matter if tsk is the leader or the last group member leaving
617 	 */
618 	if (!is_thread_group || !group_dead)
619 		goto send;
620 
621 	stats = mk_reply(rep_skb, TASKSTATS_TYPE_TGID,
622 			 task_tgid_nr_ns(tsk, &init_pid_ns));
623 	if (!stats)
624 		goto err;
625 
626 	memcpy(stats, tsk->signal->stats, sizeof(*stats));
627 
628 send:
629 	send_cpu_listeners(rep_skb, listeners);
630 	return;
631 err:
632 	nlmsg_free(rep_skb);
633 }
634 
635 static const struct genl_ops taskstats_ops[] = {
636 	{
637 		.cmd		= TASKSTATS_CMD_GET,
638 		.doit		= taskstats_user_cmd,
639 		.policy		= taskstats_cmd_get_policy,
640 		.flags		= GENL_ADMIN_PERM,
641 	},
642 	{
643 		.cmd		= CGROUPSTATS_CMD_GET,
644 		.doit		= cgroupstats_user_cmd,
645 		.policy		= cgroupstats_cmd_get_policy,
646 	},
647 };
648 
649 static struct genl_family family = {
650 	.name		= TASKSTATS_GENL_NAME,
651 	.version	= TASKSTATS_GENL_VERSION,
652 	.maxattr	= TASKSTATS_CMD_ATTR_MAX,
653 	.module		= THIS_MODULE,
654 	.ops		= taskstats_ops,
655 	.n_ops		= ARRAY_SIZE(taskstats_ops),
656 };
657 
658 /* Needed early in initialization */
659 void __init taskstats_init_early(void)
660 {
661 	unsigned int i;
662 
663 	taskstats_cache = KMEM_CACHE(taskstats, SLAB_PANIC);
664 	for_each_possible_cpu(i) {
665 		INIT_LIST_HEAD(&(per_cpu(listener_array, i).list));
666 		init_rwsem(&(per_cpu(listener_array, i).sem));
667 	}
668 }
669 
670 static int __init taskstats_init(void)
671 {
672 	int rc;
673 
674 	rc = genl_register_family(&family);
675 	if (rc)
676 		return rc;
677 
678 	family_registered = 1;
679 	pr_info("registered taskstats version %d\n", TASKSTATS_GENL_VERSION);
680 	return 0;
681 }
682 
683 /*
684  * late initcall ensures initialization of statistics collection
685  * mechanisms precedes initialization of the taskstats interface
686  */
687 late_initcall(taskstats_init);
688