1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * taskstats.c - Export per-task statistics to userland
5 * Copyright (C) Shailabh Nagar, IBM Corp. 2006
6 * (C) Balbir Singh, IBM Corp. 2006
9 #include <linux/kernel.h>
10 #include <linux/taskstats_kern.h>
11 #include <linux/tsacct_kern.h>
12 #include <linux/delayacct.h>
13 #include <linux/cpumask.h>
14 #include <linux/percpu.h>
15 #include <linux/slab.h>
16 #include <linux/cgroupstats.h>
17 #include <linux/cgroup.h>
19 #include <linux/file.h>
20 #include <linux/pid_namespace.h>
21 #include <net/genetlink.h>
22 #include <linux/atomic.h>
23 #include <linux/sched/cputime.h>
26 * Maximum length of a cpumask that can be specified in
27 * the TASKSTATS_CMD_ATTR_REGISTER/DEREGISTER_CPUMASK attribute
29 #define TASKSTATS_CPUMASK_MAXLEN (100+6*NR_CPUS)
31 static DEFINE_PER_CPU(__u32, taskstats_seqnum);
32 static int family_registered;
33 struct kmem_cache *taskstats_cache;
35 static struct genl_family family;
37 static const struct nla_policy taskstats_cmd_get_policy[] = {
38 [TASKSTATS_CMD_ATTR_PID] = { .type = NLA_U32 },
39 [TASKSTATS_CMD_ATTR_TGID] = { .type = NLA_U32 },
40 [TASKSTATS_CMD_ATTR_REGISTER_CPUMASK] = { .type = NLA_STRING },
41 [TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK] = { .type = NLA_STRING },};
43 static const struct nla_policy cgroupstats_cmd_get_policy[] = {
44 [CGROUPSTATS_CMD_ATTR_FD] = { .type = NLA_U32 },
48 struct list_head list;
53 struct listener_list {
54 struct rw_semaphore sem;
55 struct list_head list;
57 static DEFINE_PER_CPU(struct listener_list, listener_array);
65 static int prepare_reply(struct genl_info *info, u8 cmd, struct sk_buff **skbp,
72 * If new attributes are added, please revisit this allocation
74 skb = genlmsg_new(size, GFP_KERNEL);
79 int seq = this_cpu_inc_return(taskstats_seqnum) - 1;
81 reply = genlmsg_put(skb, 0, seq, &family, 0, cmd);
83 reply = genlmsg_put_reply(skb, info, &family, 0, cmd);
94 * Send taskstats data in @skb to listener with nl_pid @pid
96 static int send_reply(struct sk_buff *skb, struct genl_info *info)
98 struct genlmsghdr *genlhdr = nlmsg_data(nlmsg_hdr(skb));
99 void *reply = genlmsg_data(genlhdr);
101 genlmsg_end(skb, reply);
103 return genlmsg_reply(skb, info);
107 * Send taskstats data in @skb to listeners registered for @cpu's exit data
109 static void send_cpu_listeners(struct sk_buff *skb,
110 struct listener_list *listeners)
112 struct genlmsghdr *genlhdr = nlmsg_data(nlmsg_hdr(skb));
113 struct listener *s, *tmp;
114 struct sk_buff *skb_next, *skb_cur = skb;
115 void *reply = genlmsg_data(genlhdr);
116 int rc, delcount = 0;
118 genlmsg_end(skb, reply);
121 down_read(&listeners->sem);
122 list_for_each_entry(s, &listeners->list, list) {
124 if (!list_is_last(&s->list, &listeners->list)) {
125 skb_next = skb_clone(skb_cur, GFP_KERNEL);
129 rc = genlmsg_unicast(&init_net, skb_cur, s->pid);
130 if (rc == -ECONNREFUSED) {
136 up_read(&listeners->sem);
144 /* Delete invalidated entries */
145 down_write(&listeners->sem);
146 list_for_each_entry_safe(s, tmp, &listeners->list, list) {
152 up_write(&listeners->sem);
155 static void fill_stats(struct user_namespace *user_ns,
156 struct pid_namespace *pid_ns,
157 struct task_struct *tsk, struct taskstats *stats)
159 memset(stats, 0, sizeof(*stats));
161 * Each accounting subsystem adds calls to its functions to
162 * fill in relevant parts of struct taskstsats as follows
164 * per-task-foo(stats, tsk);
167 delayacct_add_tsk(stats, tsk);
169 /* fill in basic acct fields */
170 stats->version = TASKSTATS_VERSION;
171 stats->nvcsw = tsk->nvcsw;
172 stats->nivcsw = tsk->nivcsw;
173 bacct_add_tsk(user_ns, pid_ns, stats, tsk);
175 /* fill in extended acct fields */
176 xacct_add_tsk(stats, tsk);
179 static int fill_stats_for_pid(pid_t pid, struct taskstats *stats)
181 struct task_struct *tsk;
183 tsk = find_get_task_by_vpid(pid);
186 fill_stats(current_user_ns(), task_active_pid_ns(current), tsk, stats);
187 put_task_struct(tsk);
191 static int fill_stats_for_tgid(pid_t tgid, struct taskstats *stats)
193 struct task_struct *tsk, *first;
196 u64 delta, utime, stime;
200 * Add additional stats from live tasks except zombie thread group
201 * leaders who are already counted with the dead tasks
204 first = find_task_by_vpid(tgid);
206 if (!first || !lock_task_sighand(first, &flags))
209 if (first->signal->stats)
210 memcpy(stats, first->signal->stats, sizeof(*stats));
212 memset(stats, 0, sizeof(*stats));
215 start_time = ktime_get_ns();
220 * Accounting subsystem can call its functions here to
221 * fill in relevant parts of struct taskstsats as follows
223 * per-task-foo(stats, tsk);
225 delayacct_add_tsk(stats, tsk);
227 /* calculate task elapsed time in nsec */
228 delta = start_time - tsk->start_time;
229 /* Convert to micro seconds */
230 do_div(delta, NSEC_PER_USEC);
231 stats->ac_etime += delta;
233 task_cputime(tsk, &utime, &stime);
234 stats->ac_utime += div_u64(utime, NSEC_PER_USEC);
235 stats->ac_stime += div_u64(stime, NSEC_PER_USEC);
237 stats->nvcsw += tsk->nvcsw;
238 stats->nivcsw += tsk->nivcsw;
239 } while_each_thread(first, tsk);
241 unlock_task_sighand(first, &flags);
246 stats->version = TASKSTATS_VERSION;
248 * Accounting subsystems can also add calls here to modify
249 * fields of taskstats.
254 static void fill_tgid_exit(struct task_struct *tsk)
258 spin_lock_irqsave(&tsk->sighand->siglock, flags);
259 if (!tsk->signal->stats)
263 * Each accounting subsystem calls its functions here to
264 * accumalate its per-task stats for tsk, into the per-tgid structure
266 * per-task-foo(tsk->signal->stats, tsk);
268 delayacct_add_tsk(tsk->signal->stats, tsk);
270 spin_unlock_irqrestore(&tsk->sighand->siglock, flags);
274 static int add_del_listener(pid_t pid, const struct cpumask *mask, int isadd)
276 struct listener_list *listeners;
277 struct listener *s, *tmp, *s2;
281 if (!cpumask_subset(mask, cpu_possible_mask))
284 if (current_user_ns() != &init_user_ns)
287 if (task_active_pid_ns(current) != &init_pid_ns)
290 if (isadd == REGISTER) {
291 for_each_cpu(cpu, mask) {
292 s = kmalloc_node(sizeof(struct listener),
293 GFP_KERNEL, cpu_to_node(cpu));
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)
307 list_add(&s->list, &listeners->list);
310 up_write(&listeners->sem);
311 kfree(s); /* nop if NULL */
316 /* Deregister or 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) {
328 up_write(&listeners->sem);
333 static int parse(struct nlattr *na, struct cpumask *mask)
342 if (len > TASKSTATS_CPUMASK_MAXLEN)
346 data = kmalloc(len, GFP_KERNEL);
349 nla_strscpy(data, na, len);
350 ret = cpulist_parse(data, mask);
355 static struct taskstats *mk_reply(struct sk_buff *skb, int type, u32 pid)
357 struct nlattr *na, *ret;
360 aggr = (type == TASKSTATS_TYPE_PID)
361 ? TASKSTATS_TYPE_AGGR_PID
362 : TASKSTATS_TYPE_AGGR_TGID;
364 na = nla_nest_start_noflag(skb, aggr);
368 if (nla_put(skb, type, sizeof(pid), &pid) < 0) {
369 nla_nest_cancel(skb, na);
372 ret = nla_reserve_64bit(skb, TASKSTATS_TYPE_STATS,
373 sizeof(struct taskstats), TASKSTATS_TYPE_NULL);
375 nla_nest_cancel(skb, na);
378 nla_nest_end(skb, na);
380 return nla_data(ret);
385 static int cgroupstats_user_cmd(struct sk_buff *skb, struct genl_info *info)
388 struct sk_buff *rep_skb;
389 struct cgroupstats *stats;
395 na = info->attrs[CGROUPSTATS_CMD_ATTR_FD];
399 fd = nla_get_u32(info->attrs[CGROUPSTATS_CMD_ATTR_FD]);
404 size = nla_total_size(sizeof(struct cgroupstats));
406 rc = prepare_reply(info, CGROUPSTATS_CMD_NEW, &rep_skb,
411 na = nla_reserve(rep_skb, CGROUPSTATS_TYPE_CGROUP_STATS,
412 sizeof(struct cgroupstats));
419 stats = nla_data(na);
420 memset(stats, 0, sizeof(*stats));
422 rc = cgroupstats_build(stats, f.file->f_path.dentry);
428 rc = send_reply(rep_skb, info);
435 static int cmd_attr_register_cpumask(struct genl_info *info)
440 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
442 rc = parse(info->attrs[TASKSTATS_CMD_ATTR_REGISTER_CPUMASK], mask);
445 rc = add_del_listener(info->snd_portid, mask, REGISTER);
447 free_cpumask_var(mask);
451 static int cmd_attr_deregister_cpumask(struct genl_info *info)
456 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
458 rc = parse(info->attrs[TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK], mask);
461 rc = add_del_listener(info->snd_portid, mask, DEREGISTER);
463 free_cpumask_var(mask);
467 static size_t taskstats_packet_size(void)
471 size = nla_total_size(sizeof(u32)) +
472 nla_total_size_64bit(sizeof(struct taskstats)) +
478 static int cmd_attr_pid(struct genl_info *info)
480 struct taskstats *stats;
481 struct sk_buff *rep_skb;
486 size = taskstats_packet_size();
488 rc = prepare_reply(info, TASKSTATS_CMD_NEW, &rep_skb, size);
493 pid = nla_get_u32(info->attrs[TASKSTATS_CMD_ATTR_PID]);
494 stats = mk_reply(rep_skb, TASKSTATS_TYPE_PID, pid);
498 rc = fill_stats_for_pid(pid, stats);
501 return send_reply(rep_skb, info);
507 static int cmd_attr_tgid(struct genl_info *info)
509 struct taskstats *stats;
510 struct sk_buff *rep_skb;
515 size = taskstats_packet_size();
517 rc = prepare_reply(info, TASKSTATS_CMD_NEW, &rep_skb, size);
522 tgid = nla_get_u32(info->attrs[TASKSTATS_CMD_ATTR_TGID]);
523 stats = mk_reply(rep_skb, TASKSTATS_TYPE_TGID, tgid);
527 rc = fill_stats_for_tgid(tgid, stats);
530 return send_reply(rep_skb, info);
536 static int taskstats_user_cmd(struct sk_buff *skb, struct genl_info *info)
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);
550 static struct taskstats *taskstats_tgid_alloc(struct task_struct *tsk)
552 struct signal_struct *sig = tsk->signal;
553 struct taskstats *stats_new, *stats;
555 /* Pairs with smp_store_release() below. */
556 stats = smp_load_acquire(&sig->stats);
557 if (stats || thread_group_empty(tsk))
560 /* No problem if kmem_cache_zalloc() fails */
561 stats_new = kmem_cache_zalloc(taskstats_cache, GFP_KERNEL);
563 spin_lock_irq(&tsk->sighand->siglock);
567 * Pairs with smp_store_release() above and order the
568 * kmem_cache_zalloc().
570 smp_store_release(&sig->stats, stats_new);
574 spin_unlock_irq(&tsk->sighand->siglock);
577 kmem_cache_free(taskstats_cache, stats_new);
582 /* Send pid data out on exit */
583 void taskstats_exit(struct task_struct *tsk, int group_dead)
586 struct listener_list *listeners;
587 struct taskstats *stats;
588 struct sk_buff *rep_skb;
592 if (!family_registered)
596 * Size includes space for nested attributes
598 size = taskstats_packet_size();
600 is_thread_group = !!taskstats_tgid_alloc(tsk);
601 if (is_thread_group) {
602 /* PID + STATS + TGID + STATS */
604 /* fill the tsk->signal->stats structure */
608 listeners = raw_cpu_ptr(&listener_array);
609 if (list_empty(&listeners->list))
612 rc = prepare_reply(NULL, TASKSTATS_CMD_NEW, &rep_skb, size);
616 stats = mk_reply(rep_skb, TASKSTATS_TYPE_PID,
617 task_pid_nr_ns(tsk, &init_pid_ns));
621 fill_stats(&init_user_ns, &init_pid_ns, tsk, stats);
624 * Doesn't matter if tsk is the leader or the last group member leaving
626 if (!is_thread_group || !group_dead)
629 stats = mk_reply(rep_skb, TASKSTATS_TYPE_TGID,
630 task_tgid_nr_ns(tsk, &init_pid_ns));
634 memcpy(stats, tsk->signal->stats, sizeof(*stats));
637 send_cpu_listeners(rep_skb, listeners);
643 static const struct genl_ops taskstats_ops[] = {
645 .cmd = TASKSTATS_CMD_GET,
646 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
647 .doit = taskstats_user_cmd,
648 .policy = taskstats_cmd_get_policy,
649 .maxattr = ARRAY_SIZE(taskstats_cmd_get_policy) - 1,
650 .flags = GENL_ADMIN_PERM,
653 .cmd = CGROUPSTATS_CMD_GET,
654 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
655 .doit = cgroupstats_user_cmd,
656 .policy = cgroupstats_cmd_get_policy,
657 .maxattr = ARRAY_SIZE(cgroupstats_cmd_get_policy) - 1,
661 static struct genl_family family __ro_after_init = {
662 .name = TASKSTATS_GENL_NAME,
663 .version = TASKSTATS_GENL_VERSION,
664 .module = THIS_MODULE,
665 .ops = taskstats_ops,
666 .n_ops = ARRAY_SIZE(taskstats_ops),
669 /* Needed early in initialization */
670 void __init taskstats_init_early(void)
674 taskstats_cache = KMEM_CACHE(taskstats, SLAB_PANIC);
675 for_each_possible_cpu(i) {
676 INIT_LIST_HEAD(&(per_cpu(listener_array, i).list));
677 init_rwsem(&(per_cpu(listener_array, i).sem));
681 static int __init taskstats_init(void)
685 rc = genl_register_family(&family);
689 family_registered = 1;
690 pr_info("registered taskstats version %d\n", TASKSTATS_GENL_VERSION);
695 * late initcall ensures initialization of statistics collection
696 * mechanisms precedes initialization of the taskstats interface
698 late_initcall(taskstats_init);