OSDN Git Service

Merge tag 'v4.4.214' into 10
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / kernel / taskstats.c
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         .id             = GENL_ID_GENERATE,
46         .name           = TASKSTATS_GENL_NAME,
47         .version        = TASKSTATS_GENL_VERSION,
48         .maxattr        = TASKSTATS_CMD_ATTR_MAX,
49 };
50
51 static const struct nla_policy taskstats_cmd_get_policy[TASKSTATS_CMD_ATTR_MAX+1] = {
52         [TASKSTATS_CMD_ATTR_PID]  = { .type = NLA_U32 },
53         [TASKSTATS_CMD_ATTR_TGID] = { .type = NLA_U32 },
54         [TASKSTATS_CMD_ATTR_REGISTER_CPUMASK] = { .type = NLA_STRING },
55         [TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK] = { .type = NLA_STRING },};
56
57 /*
58  * We have to use TASKSTATS_CMD_ATTR_MAX here, it is the maxattr in the family.
59  * Make sure they are always aligned.
60  */
61 static const struct nla_policy cgroupstats_cmd_get_policy[TASKSTATS_CMD_ATTR_MAX+1] = {
62         [CGROUPSTATS_CMD_ATTR_FD] = { .type = NLA_U32 },
63 };
64
65 struct listener {
66         struct list_head list;
67         pid_t pid;
68         char valid;
69 };
70
71 struct listener_list {
72         struct rw_semaphore sem;
73         struct list_head list;
74 };
75 static DEFINE_PER_CPU(struct listener_list, listener_array);
76
77 enum actions {
78         REGISTER,
79         DEREGISTER,
80         CPU_DONT_CARE
81 };
82
83 static int prepare_reply(struct genl_info *info, u8 cmd, struct sk_buff **skbp,
84                                 size_t size)
85 {
86         struct sk_buff *skb;
87         void *reply;
88
89         /*
90          * If new attributes are added, please revisit this allocation
91          */
92         skb = genlmsg_new(size, GFP_KERNEL);
93         if (!skb)
94                 return -ENOMEM;
95
96         if (!info) {
97                 int seq = this_cpu_inc_return(taskstats_seqnum) - 1;
98
99                 reply = genlmsg_put(skb, 0, seq, &family, 0, cmd);
100         } else
101                 reply = genlmsg_put_reply(skb, info, &family, 0, cmd);
102         if (reply == NULL) {
103                 nlmsg_free(skb);
104                 return -EINVAL;
105         }
106
107         *skbp = skb;
108         return 0;
109 }
110
111 /*
112  * Send taskstats data in @skb to listener with nl_pid @pid
113  */
114 static int send_reply(struct sk_buff *skb, struct genl_info *info)
115 {
116         struct genlmsghdr *genlhdr = nlmsg_data(nlmsg_hdr(skb));
117         void *reply = genlmsg_data(genlhdr);
118
119         genlmsg_end(skb, reply);
120
121         return genlmsg_reply(skb, info);
122 }
123
124 /*
125  * Send taskstats data in @skb to listeners registered for @cpu's exit data
126  */
127 static void send_cpu_listeners(struct sk_buff *skb,
128                                         struct listener_list *listeners)
129 {
130         struct genlmsghdr *genlhdr = nlmsg_data(nlmsg_hdr(skb));
131         struct listener *s, *tmp;
132         struct sk_buff *skb_next, *skb_cur = skb;
133         void *reply = genlmsg_data(genlhdr);
134         int rc, delcount = 0;
135
136         genlmsg_end(skb, reply);
137
138         rc = 0;
139         down_read(&listeners->sem);
140         list_for_each_entry(s, &listeners->list, list) {
141                 skb_next = NULL;
142                 if (!list_is_last(&s->list, &listeners->list)) {
143                         skb_next = skb_clone(skb_cur, GFP_KERNEL);
144                         if (!skb_next)
145                                 break;
146                 }
147                 rc = genlmsg_unicast(&init_net, skb_cur, s->pid);
148                 if (rc == -ECONNREFUSED) {
149                         s->valid = 0;
150                         delcount++;
151                 }
152                 skb_cur = skb_next;
153         }
154         up_read(&listeners->sem);
155
156         if (skb_cur)
157                 nlmsg_free(skb_cur);
158
159         if (!delcount)
160                 return;
161
162         /* Delete invalidated entries */
163         down_write(&listeners->sem);
164         list_for_each_entry_safe(s, tmp, &listeners->list, list) {
165                 if (!s->valid) {
166                         list_del(&s->list);
167                         kfree(s);
168                 }
169         }
170         up_write(&listeners->sem);
171 }
172
173 static void fill_stats(struct user_namespace *user_ns,
174                        struct pid_namespace *pid_ns,
175                        struct task_struct *tsk, struct taskstats *stats)
176 {
177         memset(stats, 0, sizeof(*stats));
178         /*
179          * Each accounting subsystem adds calls to its functions to
180          * fill in relevant parts of struct taskstsats as follows
181          *
182          *      per-task-foo(stats, tsk);
183          */
184
185         delayacct_add_tsk(stats, tsk);
186
187         /* fill in basic acct fields */
188         stats->version = TASKSTATS_VERSION;
189         stats->nvcsw = tsk->nvcsw;
190         stats->nivcsw = tsk->nivcsw;
191         bacct_add_tsk(user_ns, pid_ns, stats, tsk);
192
193         /* fill in extended acct fields */
194         xacct_add_tsk(stats, tsk);
195 }
196
197 static int fill_stats_for_pid(pid_t pid, struct taskstats *stats)
198 {
199         struct task_struct *tsk;
200
201         rcu_read_lock();
202         tsk = find_task_by_vpid(pid);
203         if (tsk)
204                 get_task_struct(tsk);
205         rcu_read_unlock();
206         if (!tsk)
207                 return -ESRCH;
208         fill_stats(current_user_ns(), task_active_pid_ns(current), tsk, stats);
209         put_task_struct(tsk);
210         return 0;
211 }
212
213 static int fill_stats_for_tgid(pid_t tgid, struct taskstats *stats)
214 {
215         struct task_struct *tsk, *first;
216         unsigned long flags;
217         int rc = -ESRCH;
218
219         /*
220          * Add additional stats from live tasks except zombie thread group
221          * leaders who are already counted with the dead tasks
222          */
223         rcu_read_lock();
224         first = find_task_by_vpid(tgid);
225
226         if (!first || !lock_task_sighand(first, &flags))
227                 goto out;
228
229         if (first->signal->stats)
230                 memcpy(stats, first->signal->stats, sizeof(*stats));
231         else
232                 memset(stats, 0, sizeof(*stats));
233
234         tsk = first;
235         do {
236                 if (tsk->exit_state)
237                         continue;
238                 /*
239                  * Accounting subsystem can call its functions here to
240                  * fill in relevant parts of struct taskstsats as follows
241                  *
242                  *      per-task-foo(stats, tsk);
243                  */
244                 delayacct_add_tsk(stats, tsk);
245
246                 stats->nvcsw += tsk->nvcsw;
247                 stats->nivcsw += tsk->nivcsw;
248         } while_each_thread(first, tsk);
249
250         unlock_task_sighand(first, &flags);
251         rc = 0;
252 out:
253         rcu_read_unlock();
254
255         stats->version = TASKSTATS_VERSION;
256         /*
257          * Accounting subsystems can also add calls here to modify
258          * fields of taskstats.
259          */
260         return rc;
261 }
262
263 static void fill_tgid_exit(struct task_struct *tsk)
264 {
265         unsigned long flags;
266
267         spin_lock_irqsave(&tsk->sighand->siglock, flags);
268         if (!tsk->signal->stats)
269                 goto ret;
270
271         /*
272          * Each accounting subsystem calls its functions here to
273          * accumalate its per-task stats for tsk, into the per-tgid structure
274          *
275          *      per-task-foo(tsk->signal->stats, tsk);
276          */
277         delayacct_add_tsk(tsk->signal->stats, tsk);
278 ret:
279         spin_unlock_irqrestore(&tsk->sighand->siglock, flags);
280         return;
281 }
282
283 static int add_del_listener(pid_t pid, const struct cpumask *mask, int isadd)
284 {
285         struct listener_list *listeners;
286         struct listener *s, *tmp, *s2;
287         unsigned int cpu;
288         int ret = 0;
289
290         if (!cpumask_subset(mask, cpu_possible_mask))
291                 return -EINVAL;
292
293         if (current_user_ns() != &init_user_ns)
294                 return -EINVAL;
295
296         if (task_active_pid_ns(current) != &init_pid_ns)
297                 return -EINVAL;
298
299         if (isadd == REGISTER) {
300                 for_each_cpu(cpu, mask) {
301                         s = kmalloc_node(sizeof(struct listener),
302                                         GFP_KERNEL, cpu_to_node(cpu));
303                         if (!s) {
304                                 ret = -ENOMEM;
305                                 goto cleanup;
306                         }
307                         s->pid = pid;
308                         s->valid = 1;
309
310                         listeners = &per_cpu(listener_array, cpu);
311                         down_write(&listeners->sem);
312                         list_for_each_entry(s2, &listeners->list, list) {
313                                 if (s2->pid == pid && s2->valid)
314                                         goto exists;
315                         }
316                         list_add(&s->list, &listeners->list);
317                         s = NULL;
318 exists:
319                         up_write(&listeners->sem);
320                         kfree(s); /* nop if NULL */
321                 }
322                 return 0;
323         }
324
325         /* Deregister or cleanup */
326 cleanup:
327         for_each_cpu(cpu, mask) {
328                 listeners = &per_cpu(listener_array, cpu);
329                 down_write(&listeners->sem);
330                 list_for_each_entry_safe(s, tmp, &listeners->list, list) {
331                         if (s->pid == pid) {
332                                 list_del(&s->list);
333                                 kfree(s);
334                                 break;
335                         }
336                 }
337                 up_write(&listeners->sem);
338         }
339         return ret;
340 }
341
342 static int parse(struct nlattr *na, struct cpumask *mask)
343 {
344         char *data;
345         int len;
346         int ret;
347
348         if (na == NULL)
349                 return 1;
350         len = nla_len(na);
351         if (len > TASKSTATS_CPUMASK_MAXLEN)
352                 return -E2BIG;
353         if (len < 1)
354                 return -EINVAL;
355         data = kmalloc(len, GFP_KERNEL);
356         if (!data)
357                 return -ENOMEM;
358         nla_strlcpy(data, na, len);
359         ret = cpulist_parse(data, mask);
360         kfree(data);
361         return ret;
362 }
363
364 #if defined(CONFIG_64BIT) && !defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
365 #define TASKSTATS_NEEDS_PADDING 1
366 #endif
367
368 static struct taskstats *mk_reply(struct sk_buff *skb, int type, u32 pid)
369 {
370         struct nlattr *na, *ret;
371         int aggr;
372
373         aggr = (type == TASKSTATS_TYPE_PID)
374                         ? TASKSTATS_TYPE_AGGR_PID
375                         : TASKSTATS_TYPE_AGGR_TGID;
376
377         /*
378          * The taskstats structure is internally aligned on 8 byte
379          * boundaries but the layout of the aggregrate reply, with
380          * two NLA headers and the pid (each 4 bytes), actually
381          * force the entire structure to be unaligned. This causes
382          * the kernel to issue unaligned access warnings on some
383          * architectures like ia64. Unfortunately, some software out there
384          * doesn't properly unroll the NLA packet and assumes that the start
385          * of the taskstats structure will always be 20 bytes from the start
386          * of the netlink payload. Aligning the start of the taskstats
387          * structure breaks this software, which we don't want. So, for now
388          * the alignment only happens on architectures that require it
389          * and those users will have to update to fixed versions of those
390          * packages. Space is reserved in the packet only when needed.
391          * This ifdef should be removed in several years e.g. 2012 once
392          * we can be confident that fixed versions are installed on most
393          * systems. We add the padding before the aggregate since the
394          * aggregate is already a defined type.
395          */
396 #ifdef TASKSTATS_NEEDS_PADDING
397         if (nla_put(skb, TASKSTATS_TYPE_NULL, 0, NULL) < 0)
398                 goto err;
399 #endif
400         na = nla_nest_start(skb, aggr);
401         if (!na)
402                 goto err;
403
404         if (nla_put(skb, type, sizeof(pid), &pid) < 0) {
405                 nla_nest_cancel(skb, na);
406                 goto err;
407         }
408         ret = nla_reserve(skb, TASKSTATS_TYPE_STATS, sizeof(struct taskstats));
409         if (!ret) {
410                 nla_nest_cancel(skb, na);
411                 goto err;
412         }
413         nla_nest_end(skb, na);
414
415         return nla_data(ret);
416 err:
417         return NULL;
418 }
419
420 static int cgroupstats_user_cmd(struct sk_buff *skb, struct genl_info *info)
421 {
422         int rc = 0;
423         struct sk_buff *rep_skb;
424         struct cgroupstats *stats;
425         struct nlattr *na;
426         size_t size;
427         u32 fd;
428         struct fd f;
429
430         na = info->attrs[CGROUPSTATS_CMD_ATTR_FD];
431         if (!na)
432                 return -EINVAL;
433
434         fd = nla_get_u32(info->attrs[CGROUPSTATS_CMD_ATTR_FD]);
435         f = fdget(fd);
436         if (!f.file)
437                 return 0;
438
439         size = nla_total_size(sizeof(struct cgroupstats));
440
441         rc = prepare_reply(info, CGROUPSTATS_CMD_NEW, &rep_skb,
442                                 size);
443         if (rc < 0)
444                 goto err;
445
446         na = nla_reserve(rep_skb, CGROUPSTATS_TYPE_CGROUP_STATS,
447                                 sizeof(struct cgroupstats));
448         if (na == NULL) {
449                 nlmsg_free(rep_skb);
450                 rc = -EMSGSIZE;
451                 goto err;
452         }
453
454         stats = nla_data(na);
455         memset(stats, 0, sizeof(*stats));
456
457         rc = cgroupstats_build(stats, f.file->f_path.dentry);
458         if (rc < 0) {
459                 nlmsg_free(rep_skb);
460                 goto err;
461         }
462
463         rc = send_reply(rep_skb, info);
464
465 err:
466         fdput(f);
467         return rc;
468 }
469
470 static int cmd_attr_register_cpumask(struct genl_info *info)
471 {
472         cpumask_var_t mask;
473         int rc;
474
475         if (!alloc_cpumask_var(&mask, GFP_KERNEL))
476                 return -ENOMEM;
477         rc = parse(info->attrs[TASKSTATS_CMD_ATTR_REGISTER_CPUMASK], mask);
478         if (rc < 0)
479                 goto out;
480         rc = add_del_listener(info->snd_portid, mask, REGISTER);
481 out:
482         free_cpumask_var(mask);
483         return rc;
484 }
485
486 static int cmd_attr_deregister_cpumask(struct genl_info *info)
487 {
488         cpumask_var_t mask;
489         int rc;
490
491         if (!alloc_cpumask_var(&mask, GFP_KERNEL))
492                 return -ENOMEM;
493         rc = parse(info->attrs[TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK], mask);
494         if (rc < 0)
495                 goto out;
496         rc = add_del_listener(info->snd_portid, mask, DEREGISTER);
497 out:
498         free_cpumask_var(mask);
499         return rc;
500 }
501
502 static size_t taskstats_packet_size(void)
503 {
504         size_t size;
505
506         size = nla_total_size(sizeof(u32)) +
507                 nla_total_size(sizeof(struct taskstats)) + nla_total_size(0);
508 #ifdef TASKSTATS_NEEDS_PADDING
509         size += nla_total_size(0); /* Padding for alignment */
510 #endif
511         return size;
512 }
513
514 static int cmd_attr_pid(struct genl_info *info)
515 {
516         struct taskstats *stats;
517         struct sk_buff *rep_skb;
518         size_t size;
519         u32 pid;
520         int rc;
521
522         size = taskstats_packet_size();
523
524         rc = prepare_reply(info, TASKSTATS_CMD_NEW, &rep_skb, size);
525         if (rc < 0)
526                 return rc;
527
528         rc = -EINVAL;
529         pid = nla_get_u32(info->attrs[TASKSTATS_CMD_ATTR_PID]);
530         stats = mk_reply(rep_skb, TASKSTATS_TYPE_PID, pid);
531         if (!stats)
532                 goto err;
533
534         rc = fill_stats_for_pid(pid, stats);
535         if (rc < 0)
536                 goto err;
537         return send_reply(rep_skb, info);
538 err:
539         nlmsg_free(rep_skb);
540         return rc;
541 }
542
543 static int cmd_attr_tgid(struct genl_info *info)
544 {
545         struct taskstats *stats;
546         struct sk_buff *rep_skb;
547         size_t size;
548         u32 tgid;
549         int rc;
550
551         size = taskstats_packet_size();
552
553         rc = prepare_reply(info, TASKSTATS_CMD_NEW, &rep_skb, size);
554         if (rc < 0)
555                 return rc;
556
557         rc = -EINVAL;
558         tgid = nla_get_u32(info->attrs[TASKSTATS_CMD_ATTR_TGID]);
559         stats = mk_reply(rep_skb, TASKSTATS_TYPE_TGID, tgid);
560         if (!stats)
561                 goto err;
562
563         rc = fill_stats_for_tgid(tgid, stats);
564         if (rc < 0)
565                 goto err;
566         return send_reply(rep_skb, info);
567 err:
568         nlmsg_free(rep_skb);
569         return rc;
570 }
571
572 static int taskstats_user_cmd(struct sk_buff *skb, struct genl_info *info)
573 {
574         if (info->attrs[TASKSTATS_CMD_ATTR_REGISTER_CPUMASK])
575                 return cmd_attr_register_cpumask(info);
576         else if (info->attrs[TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK])
577                 return cmd_attr_deregister_cpumask(info);
578         else if (info->attrs[TASKSTATS_CMD_ATTR_PID])
579                 return cmd_attr_pid(info);
580         else if (info->attrs[TASKSTATS_CMD_ATTR_TGID])
581                 return cmd_attr_tgid(info);
582         else
583                 return -EINVAL;
584 }
585
586 static struct taskstats *taskstats_tgid_alloc(struct task_struct *tsk)
587 {
588         struct signal_struct *sig = tsk->signal;
589         struct taskstats *stats_new, *stats;
590
591         /* Pairs with smp_store_release() below. */
592         stats = smp_load_acquire(&sig->stats);
593         if (stats || thread_group_empty(tsk))
594                 return stats;
595
596         /* No problem if kmem_cache_zalloc() fails */
597         stats_new = kmem_cache_zalloc(taskstats_cache, GFP_KERNEL);
598
599         spin_lock_irq(&tsk->sighand->siglock);
600         stats = sig->stats;
601         if (!stats) {
602                 /*
603                  * Pairs with smp_store_release() above and order the
604                  * kmem_cache_zalloc().
605                  */
606                 smp_store_release(&sig->stats, stats_new);
607                 stats = stats_new;
608                 stats_new = NULL;
609         }
610         spin_unlock_irq(&tsk->sighand->siglock);
611
612         if (stats_new)
613                 kmem_cache_free(taskstats_cache, stats_new);
614
615         return stats;
616 }
617
618 /* Send pid data out on exit */
619 void taskstats_exit(struct task_struct *tsk, int group_dead)
620 {
621         int rc;
622         struct listener_list *listeners;
623         struct taskstats *stats;
624         struct sk_buff *rep_skb;
625         size_t size;
626         int is_thread_group;
627
628         if (!family_registered)
629                 return;
630
631         /*
632          * Size includes space for nested attributes
633          */
634         size = taskstats_packet_size();
635
636         is_thread_group = !!taskstats_tgid_alloc(tsk);
637         if (is_thread_group) {
638                 /* PID + STATS + TGID + STATS */
639                 size = 2 * size;
640                 /* fill the tsk->signal->stats structure */
641                 fill_tgid_exit(tsk);
642         }
643
644         listeners = raw_cpu_ptr(&listener_array);
645         if (list_empty(&listeners->list))
646                 return;
647
648         rc = prepare_reply(NULL, TASKSTATS_CMD_NEW, &rep_skb, size);
649         if (rc < 0)
650                 return;
651
652         stats = mk_reply(rep_skb, TASKSTATS_TYPE_PID,
653                          task_pid_nr_ns(tsk, &init_pid_ns));
654         if (!stats)
655                 goto err;
656
657         fill_stats(&init_user_ns, &init_pid_ns, tsk, stats);
658
659         /*
660          * Doesn't matter if tsk is the leader or the last group member leaving
661          */
662         if (!is_thread_group || !group_dead)
663                 goto send;
664
665         stats = mk_reply(rep_skb, TASKSTATS_TYPE_TGID,
666                          task_tgid_nr_ns(tsk, &init_pid_ns));
667         if (!stats)
668                 goto err;
669
670         memcpy(stats, tsk->signal->stats, sizeof(*stats));
671
672 send:
673         send_cpu_listeners(rep_skb, listeners);
674         return;
675 err:
676         nlmsg_free(rep_skb);
677 }
678
679 static const struct genl_ops taskstats_ops[] = {
680         {
681                 .cmd            = TASKSTATS_CMD_GET,
682                 .doit           = taskstats_user_cmd,
683                 .policy         = taskstats_cmd_get_policy,
684                 .flags          = GENL_ADMIN_PERM,
685         },
686         {
687                 .cmd            = CGROUPSTATS_CMD_GET,
688                 .doit           = cgroupstats_user_cmd,
689                 .policy         = cgroupstats_cmd_get_policy,
690         },
691 };
692
693 /* Needed early in initialization */
694 void __init taskstats_init_early(void)
695 {
696         unsigned int i;
697
698         taskstats_cache = KMEM_CACHE(taskstats, SLAB_PANIC);
699         for_each_possible_cpu(i) {
700                 INIT_LIST_HEAD(&(per_cpu(listener_array, i).list));
701                 init_rwsem(&(per_cpu(listener_array, i).sem));
702         }
703 }
704
705 static int __init taskstats_init(void)
706 {
707         int rc;
708
709         rc = genl_register_family_with_ops(&family, taskstats_ops);
710         if (rc)
711                 return rc;
712
713         family_registered = 1;
714         pr_info("registered taskstats version %d\n", TASKSTATS_GENL_VERSION);
715         return 0;
716 }
717
718 /*
719  * late initcall ensures initialization of statistics collection
720  * mechanisms precedes initialization of the taskstats interface
721  */
722 late_initcall(taskstats_init);