GNU Linux-libre 4.19.281-gnu1
[releases.git] / kernel / cgroup / cgroup-v1.c
1 #include "cgroup-internal.h"
2
3 #include <linux/ctype.h>
4 #include <linux/kmod.h>
5 #include <linux/sort.h>
6 #include <linux/delay.h>
7 #include <linux/mm.h>
8 #include <linux/sched/signal.h>
9 #include <linux/sched/task.h>
10 #include <linux/magic.h>
11 #include <linux/slab.h>
12 #include <linux/vmalloc.h>
13 #include <linux/delayacct.h>
14 #include <linux/pid_namespace.h>
15 #include <linux/cgroupstats.h>
16 #include <linux/cpu.h>
17
18 #include <trace/events/cgroup.h>
19
20 /*
21  * pidlists linger the following amount before being destroyed.  The goal
22  * is avoiding frequent destruction in the middle of consecutive read calls
23  * Expiring in the middle is a performance problem not a correctness one.
24  * 1 sec should be enough.
25  */
26 #define CGROUP_PIDLIST_DESTROY_DELAY    HZ
27
28 /* Controllers blocked by the commandline in v1 */
29 static u16 cgroup_no_v1_mask;
30
31 /*
32  * pidlist destructions need to be flushed on cgroup destruction.  Use a
33  * separate workqueue as flush domain.
34  */
35 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
36
37 /*
38  * Protects cgroup_subsys->release_agent_path.  Modifying it also requires
39  * cgroup_mutex.  Reading requires either cgroup_mutex or this spinlock.
40  */
41 static DEFINE_SPINLOCK(release_agent_path_lock);
42
43 bool cgroup1_ssid_disabled(int ssid)
44 {
45         return cgroup_no_v1_mask & (1 << ssid);
46 }
47
48 /**
49  * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
50  * @from: attach to all cgroups of a given task
51  * @tsk: the task to be attached
52  */
53 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
54 {
55         struct cgroup_root *root;
56         int retval = 0;
57
58         mutex_lock(&cgroup_mutex);
59         get_online_cpus();
60         percpu_down_write(&cgroup_threadgroup_rwsem);
61         for_each_root(root) {
62                 struct cgroup *from_cgrp;
63
64                 if (root == &cgrp_dfl_root)
65                         continue;
66
67                 spin_lock_irq(&css_set_lock);
68                 from_cgrp = task_cgroup_from_root(from, root);
69                 spin_unlock_irq(&css_set_lock);
70
71                 retval = cgroup_attach_task(from_cgrp, tsk, false);
72                 if (retval)
73                         break;
74         }
75         percpu_up_write(&cgroup_threadgroup_rwsem);
76         put_online_cpus();
77         mutex_unlock(&cgroup_mutex);
78
79         return retval;
80 }
81 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
82
83 /**
84  * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
85  * @to: cgroup to which the tasks will be moved
86  * @from: cgroup in which the tasks currently reside
87  *
88  * Locking rules between cgroup_post_fork() and the migration path
89  * guarantee that, if a task is forking while being migrated, the new child
90  * is guaranteed to be either visible in the source cgroup after the
91  * parent's migration is complete or put into the target cgroup.  No task
92  * can slip out of migration through forking.
93  */
94 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
95 {
96         DEFINE_CGROUP_MGCTX(mgctx);
97         struct cgrp_cset_link *link;
98         struct css_task_iter it;
99         struct task_struct *task;
100         int ret;
101
102         if (cgroup_on_dfl(to))
103                 return -EINVAL;
104
105         ret = cgroup_migrate_vet_dst(to);
106         if (ret)
107                 return ret;
108
109         mutex_lock(&cgroup_mutex);
110
111         percpu_down_write(&cgroup_threadgroup_rwsem);
112
113         /* all tasks in @from are being moved, all csets are source */
114         spin_lock_irq(&css_set_lock);
115         list_for_each_entry(link, &from->cset_links, cset_link)
116                 cgroup_migrate_add_src(link->cset, to, &mgctx);
117         spin_unlock_irq(&css_set_lock);
118
119         ret = cgroup_migrate_prepare_dst(&mgctx);
120         if (ret)
121                 goto out_err;
122
123         /*
124          * Migrate tasks one-by-one until @from is empty.  This fails iff
125          * ->can_attach() fails.
126          */
127         do {
128                 css_task_iter_start(&from->self, 0, &it);
129
130                 do {
131                         task = css_task_iter_next(&it);
132                 } while (task && (task->flags & PF_EXITING));
133
134                 if (task)
135                         get_task_struct(task);
136                 css_task_iter_end(&it);
137
138                 if (task) {
139                         ret = cgroup_migrate(task, false, &mgctx);
140                         if (!ret)
141                                 TRACE_CGROUP_PATH(transfer_tasks, to, task, false);
142                         put_task_struct(task);
143                 }
144         } while (task && !ret);
145 out_err:
146         cgroup_migrate_finish(&mgctx);
147         percpu_up_write(&cgroup_threadgroup_rwsem);
148         mutex_unlock(&cgroup_mutex);
149         return ret;
150 }
151
152 /*
153  * Stuff for reading the 'tasks'/'procs' files.
154  *
155  * Reading this file can return large amounts of data if a cgroup has
156  * *lots* of attached tasks. So it may need several calls to read(),
157  * but we cannot guarantee that the information we produce is correct
158  * unless we produce it entirely atomically.
159  *
160  */
161
162 /* which pidlist file are we talking about? */
163 enum cgroup_filetype {
164         CGROUP_FILE_PROCS,
165         CGROUP_FILE_TASKS,
166 };
167
168 /*
169  * A pidlist is a list of pids that virtually represents the contents of one
170  * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
171  * a pair (one each for procs, tasks) for each pid namespace that's relevant
172  * to the cgroup.
173  */
174 struct cgroup_pidlist {
175         /*
176          * used to find which pidlist is wanted. doesn't change as long as
177          * this particular list stays in the list.
178         */
179         struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
180         /* array of xids */
181         pid_t *list;
182         /* how many elements the above list has */
183         int length;
184         /* each of these stored in a list by its cgroup */
185         struct list_head links;
186         /* pointer to the cgroup we belong to, for list removal purposes */
187         struct cgroup *owner;
188         /* for delayed destruction */
189         struct delayed_work destroy_dwork;
190 };
191
192 /*
193  * The following two functions "fix" the issue where there are more pids
194  * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
195  * TODO: replace with a kernel-wide solution to this problem
196  */
197 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
198 static void *pidlist_allocate(int count)
199 {
200         if (PIDLIST_TOO_LARGE(count))
201                 return vmalloc(array_size(count, sizeof(pid_t)));
202         else
203                 return kmalloc_array(count, sizeof(pid_t), GFP_KERNEL);
204 }
205
206 static void pidlist_free(void *p)
207 {
208         kvfree(p);
209 }
210
211 /*
212  * Used to destroy all pidlists lingering waiting for destroy timer.  None
213  * should be left afterwards.
214  */
215 void cgroup1_pidlist_destroy_all(struct cgroup *cgrp)
216 {
217         struct cgroup_pidlist *l, *tmp_l;
218
219         mutex_lock(&cgrp->pidlist_mutex);
220         list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
221                 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
222         mutex_unlock(&cgrp->pidlist_mutex);
223
224         flush_workqueue(cgroup_pidlist_destroy_wq);
225         BUG_ON(!list_empty(&cgrp->pidlists));
226 }
227
228 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
229 {
230         struct delayed_work *dwork = to_delayed_work(work);
231         struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
232                                                 destroy_dwork);
233         struct cgroup_pidlist *tofree = NULL;
234
235         mutex_lock(&l->owner->pidlist_mutex);
236
237         /*
238          * Destroy iff we didn't get queued again.  The state won't change
239          * as destroy_dwork can only be queued while locked.
240          */
241         if (!delayed_work_pending(dwork)) {
242                 list_del(&l->links);
243                 pidlist_free(l->list);
244                 put_pid_ns(l->key.ns);
245                 tofree = l;
246         }
247
248         mutex_unlock(&l->owner->pidlist_mutex);
249         kfree(tofree);
250 }
251
252 /*
253  * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
254  * Returns the number of unique elements.
255  */
256 static int pidlist_uniq(pid_t *list, int length)
257 {
258         int src, dest = 1;
259
260         /*
261          * we presume the 0th element is unique, so i starts at 1. trivial
262          * edge cases first; no work needs to be done for either
263          */
264         if (length == 0 || length == 1)
265                 return length;
266         /* src and dest walk down the list; dest counts unique elements */
267         for (src = 1; src < length; src++) {
268                 /* find next unique element */
269                 while (list[src] == list[src-1]) {
270                         src++;
271                         if (src == length)
272                                 goto after;
273                 }
274                 /* dest always points to where the next unique element goes */
275                 list[dest] = list[src];
276                 dest++;
277         }
278 after:
279         return dest;
280 }
281
282 /*
283  * The two pid files - task and cgroup.procs - guaranteed that the result
284  * is sorted, which forced this whole pidlist fiasco.  As pid order is
285  * different per namespace, each namespace needs differently sorted list,
286  * making it impossible to use, for example, single rbtree of member tasks
287  * sorted by task pointer.  As pidlists can be fairly large, allocating one
288  * per open file is dangerous, so cgroup had to implement shared pool of
289  * pidlists keyed by cgroup and namespace.
290  */
291 static int cmppid(const void *a, const void *b)
292 {
293         return *(pid_t *)a - *(pid_t *)b;
294 }
295
296 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
297                                                   enum cgroup_filetype type)
298 {
299         struct cgroup_pidlist *l;
300         /* don't need task_nsproxy() if we're looking at ourself */
301         struct pid_namespace *ns = task_active_pid_ns(current);
302
303         lockdep_assert_held(&cgrp->pidlist_mutex);
304
305         list_for_each_entry(l, &cgrp->pidlists, links)
306                 if (l->key.type == type && l->key.ns == ns)
307                         return l;
308         return NULL;
309 }
310
311 /*
312  * find the appropriate pidlist for our purpose (given procs vs tasks)
313  * returns with the lock on that pidlist already held, and takes care
314  * of the use count, or returns NULL with no locks held if we're out of
315  * memory.
316  */
317 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
318                                                 enum cgroup_filetype type)
319 {
320         struct cgroup_pidlist *l;
321
322         lockdep_assert_held(&cgrp->pidlist_mutex);
323
324         l = cgroup_pidlist_find(cgrp, type);
325         if (l)
326                 return l;
327
328         /* entry not found; create a new one */
329         l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
330         if (!l)
331                 return l;
332
333         INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
334         l->key.type = type;
335         /* don't need task_nsproxy() if we're looking at ourself */
336         l->key.ns = get_pid_ns(task_active_pid_ns(current));
337         l->owner = cgrp;
338         list_add(&l->links, &cgrp->pidlists);
339         return l;
340 }
341
342 /**
343  * cgroup_task_count - count the number of tasks in a cgroup.
344  * @cgrp: the cgroup in question
345  */
346 int cgroup_task_count(const struct cgroup *cgrp)
347 {
348         int count = 0;
349         struct cgrp_cset_link *link;
350
351         spin_lock_irq(&css_set_lock);
352         list_for_each_entry(link, &cgrp->cset_links, cset_link)
353                 count += link->cset->nr_tasks;
354         spin_unlock_irq(&css_set_lock);
355         return count;
356 }
357
358 /*
359  * Load a cgroup's pidarray with either procs' tgids or tasks' pids
360  */
361 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
362                               struct cgroup_pidlist **lp)
363 {
364         pid_t *array;
365         int length;
366         int pid, n = 0; /* used for populating the array */
367         struct css_task_iter it;
368         struct task_struct *tsk;
369         struct cgroup_pidlist *l;
370
371         lockdep_assert_held(&cgrp->pidlist_mutex);
372
373         /*
374          * If cgroup gets more users after we read count, we won't have
375          * enough space - tough.  This race is indistinguishable to the
376          * caller from the case that the additional cgroup users didn't
377          * show up until sometime later on.
378          */
379         length = cgroup_task_count(cgrp);
380         array = pidlist_allocate(length);
381         if (!array)
382                 return -ENOMEM;
383         /* now, populate the array */
384         css_task_iter_start(&cgrp->self, 0, &it);
385         while ((tsk = css_task_iter_next(&it))) {
386                 if (unlikely(n == length))
387                         break;
388                 /* get tgid or pid for procs or tasks file respectively */
389                 if (type == CGROUP_FILE_PROCS)
390                         pid = task_tgid_vnr(tsk);
391                 else
392                         pid = task_pid_vnr(tsk);
393                 if (pid > 0) /* make sure to only use valid results */
394                         array[n++] = pid;
395         }
396         css_task_iter_end(&it);
397         length = n;
398         /* now sort & (if procs) strip out duplicates */
399         sort(array, length, sizeof(pid_t), cmppid, NULL);
400         if (type == CGROUP_FILE_PROCS)
401                 length = pidlist_uniq(array, length);
402
403         l = cgroup_pidlist_find_create(cgrp, type);
404         if (!l) {
405                 pidlist_free(array);
406                 return -ENOMEM;
407         }
408
409         /* store array, freeing old if necessary */
410         pidlist_free(l->list);
411         l->list = array;
412         l->length = length;
413         *lp = l;
414         return 0;
415 }
416
417 /*
418  * seq_file methods for the tasks/procs files. The seq_file position is the
419  * next pid to display; the seq_file iterator is a pointer to the pid
420  * in the cgroup->l->list array.
421  */
422
423 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
424 {
425         /*
426          * Initially we receive a position value that corresponds to
427          * one more than the last pid shown (or 0 on the first call or
428          * after a seek to the start). Use a binary-search to find the
429          * next pid to display, if any
430          */
431         struct kernfs_open_file *of = s->private;
432         struct cgroup_file_ctx *ctx = of->priv;
433         struct cgroup *cgrp = seq_css(s)->cgroup;
434         struct cgroup_pidlist *l;
435         enum cgroup_filetype type = seq_cft(s)->private;
436         int index = 0, pid = *pos;
437         int *iter, ret;
438
439         mutex_lock(&cgrp->pidlist_mutex);
440
441         /*
442          * !NULL @ctx->procs1.pidlist indicates that this isn't the first
443          * start() after open. If the matching pidlist is around, we can use
444          * that. Look for it. Note that @ctx->procs1.pidlist can't be used
445          * directly. It could already have been destroyed.
446          */
447         if (ctx->procs1.pidlist)
448                 ctx->procs1.pidlist = cgroup_pidlist_find(cgrp, type);
449
450         /*
451          * Either this is the first start() after open or the matching
452          * pidlist has been destroyed inbetween.  Create a new one.
453          */
454         if (!ctx->procs1.pidlist) {
455                 ret = pidlist_array_load(cgrp, type, &ctx->procs1.pidlist);
456                 if (ret)
457                         return ERR_PTR(ret);
458         }
459         l = ctx->procs1.pidlist;
460
461         if (pid) {
462                 int end = l->length;
463
464                 while (index < end) {
465                         int mid = (index + end) / 2;
466                         if (l->list[mid] == pid) {
467                                 index = mid;
468                                 break;
469                         } else if (l->list[mid] <= pid)
470                                 index = mid + 1;
471                         else
472                                 end = mid;
473                 }
474         }
475         /* If we're off the end of the array, we're done */
476         if (index >= l->length)
477                 return NULL;
478         /* Update the abstract position to be the actual pid that we found */
479         iter = l->list + index;
480         *pos = *iter;
481         return iter;
482 }
483
484 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
485 {
486         struct kernfs_open_file *of = s->private;
487         struct cgroup_file_ctx *ctx = of->priv;
488         struct cgroup_pidlist *l = ctx->procs1.pidlist;
489
490         if (l)
491                 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
492                                  CGROUP_PIDLIST_DESTROY_DELAY);
493         mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
494 }
495
496 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
497 {
498         struct kernfs_open_file *of = s->private;
499         struct cgroup_file_ctx *ctx = of->priv;
500         struct cgroup_pidlist *l = ctx->procs1.pidlist;
501         pid_t *p = v;
502         pid_t *end = l->list + l->length;
503         /*
504          * Advance to the next pid in the array. If this goes off the
505          * end, we're done
506          */
507         p++;
508         if (p >= end) {
509                 (*pos)++;
510                 return NULL;
511         } else {
512                 *pos = *p;
513                 return p;
514         }
515 }
516
517 static int cgroup_pidlist_show(struct seq_file *s, void *v)
518 {
519         seq_printf(s, "%d\n", *(int *)v);
520
521         return 0;
522 }
523
524 static ssize_t __cgroup1_procs_write(struct kernfs_open_file *of,
525                                      char *buf, size_t nbytes, loff_t off,
526                                      bool threadgroup)
527 {
528         struct cgroup *cgrp;
529         struct task_struct *task;
530         const struct cred *cred, *tcred;
531         ssize_t ret;
532
533         cgrp = cgroup_kn_lock_live(of->kn, false);
534         if (!cgrp)
535                 return -ENODEV;
536
537         task = cgroup_procs_write_start(buf, threadgroup);
538         ret = PTR_ERR_OR_ZERO(task);
539         if (ret)
540                 goto out_unlock;
541
542         /*
543          * Even if we're attaching all tasks in the thread group, we only need
544          * to check permissions on one of them. Check permissions using the
545          * credentials from file open to protect against inherited fd attacks.
546          */
547         cred = of->file->f_cred;
548         tcred = get_task_cred(task);
549         if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
550             !uid_eq(cred->euid, tcred->uid) &&
551             !uid_eq(cred->euid, tcred->suid))
552                 ret = -EACCES;
553         put_cred(tcred);
554         if (ret)
555                 goto out_finish;
556
557         ret = cgroup_attach_task(cgrp, task, threadgroup);
558
559 out_finish:
560         cgroup_procs_write_finish(task);
561 out_unlock:
562         cgroup_kn_unlock(of->kn);
563
564         return ret ?: nbytes;
565 }
566
567 static ssize_t cgroup1_procs_write(struct kernfs_open_file *of,
568                                    char *buf, size_t nbytes, loff_t off)
569 {
570         return __cgroup1_procs_write(of, buf, nbytes, off, true);
571 }
572
573 static ssize_t cgroup1_tasks_write(struct kernfs_open_file *of,
574                                    char *buf, size_t nbytes, loff_t off)
575 {
576         return __cgroup1_procs_write(of, buf, nbytes, off, false);
577 }
578
579 static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
580                                           char *buf, size_t nbytes, loff_t off)
581 {
582         struct cgroup *cgrp;
583
584         BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
585
586         /*
587          * Release agent gets called with all capabilities,
588          * require capabilities to set release agent.
589          */
590         if ((of->file->f_cred->user_ns != &init_user_ns) ||
591             !capable(CAP_SYS_ADMIN))
592                 return -EPERM;
593
594         cgrp = cgroup_kn_lock_live(of->kn, false);
595         if (!cgrp)
596                 return -ENODEV;
597         spin_lock(&release_agent_path_lock);
598         strlcpy(cgrp->root->release_agent_path, strstrip(buf),
599                 sizeof(cgrp->root->release_agent_path));
600         spin_unlock(&release_agent_path_lock);
601         cgroup_kn_unlock(of->kn);
602         return nbytes;
603 }
604
605 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
606 {
607         struct cgroup *cgrp = seq_css(seq)->cgroup;
608
609         spin_lock(&release_agent_path_lock);
610         seq_puts(seq, cgrp->root->release_agent_path);
611         spin_unlock(&release_agent_path_lock);
612         seq_putc(seq, '\n');
613         return 0;
614 }
615
616 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
617 {
618         seq_puts(seq, "0\n");
619         return 0;
620 }
621
622 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
623                                          struct cftype *cft)
624 {
625         return notify_on_release(css->cgroup);
626 }
627
628 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
629                                           struct cftype *cft, u64 val)
630 {
631         if (val)
632                 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
633         else
634                 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
635         return 0;
636 }
637
638 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
639                                       struct cftype *cft)
640 {
641         return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
642 }
643
644 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
645                                        struct cftype *cft, u64 val)
646 {
647         if (val)
648                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
649         else
650                 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
651         return 0;
652 }
653
654 /* cgroup core interface files for the legacy hierarchies */
655 struct cftype cgroup1_base_files[] = {
656         {
657                 .name = "cgroup.procs",
658                 .seq_start = cgroup_pidlist_start,
659                 .seq_next = cgroup_pidlist_next,
660                 .seq_stop = cgroup_pidlist_stop,
661                 .seq_show = cgroup_pidlist_show,
662                 .private = CGROUP_FILE_PROCS,
663                 .write = cgroup1_procs_write,
664         },
665         {
666                 .name = "cgroup.clone_children",
667                 .read_u64 = cgroup_clone_children_read,
668                 .write_u64 = cgroup_clone_children_write,
669         },
670         {
671                 .name = "cgroup.sane_behavior",
672                 .flags = CFTYPE_ONLY_ON_ROOT,
673                 .seq_show = cgroup_sane_behavior_show,
674         },
675         {
676                 .name = "tasks",
677                 .seq_start = cgroup_pidlist_start,
678                 .seq_next = cgroup_pidlist_next,
679                 .seq_stop = cgroup_pidlist_stop,
680                 .seq_show = cgroup_pidlist_show,
681                 .private = CGROUP_FILE_TASKS,
682                 .write = cgroup1_tasks_write,
683         },
684         {
685                 .name = "notify_on_release",
686                 .read_u64 = cgroup_read_notify_on_release,
687                 .write_u64 = cgroup_write_notify_on_release,
688         },
689         {
690                 .name = "release_agent",
691                 .flags = CFTYPE_ONLY_ON_ROOT,
692                 .seq_show = cgroup_release_agent_show,
693                 .write = cgroup_release_agent_write,
694                 .max_write_len = PATH_MAX - 1,
695         },
696         { }     /* terminate */
697 };
698
699 /* Display information about each subsystem and each hierarchy */
700 int proc_cgroupstats_show(struct seq_file *m, void *v)
701 {
702         struct cgroup_subsys *ss;
703         int i;
704
705         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
706         /*
707          * ideally we don't want subsystems moving around while we do this.
708          * cgroup_mutex is also necessary to guarantee an atomic snapshot of
709          * subsys/hierarchy state.
710          */
711         mutex_lock(&cgroup_mutex);
712
713         for_each_subsys(ss, i)
714                 seq_printf(m, "%s\t%d\t%d\t%d\n",
715                            ss->legacy_name, ss->root->hierarchy_id,
716                            atomic_read(&ss->root->nr_cgrps),
717                            cgroup_ssid_enabled(i));
718
719         mutex_unlock(&cgroup_mutex);
720         return 0;
721 }
722
723 /**
724  * cgroupstats_build - build and fill cgroupstats
725  * @stats: cgroupstats to fill information into
726  * @dentry: A dentry entry belonging to the cgroup for which stats have
727  * been requested.
728  *
729  * Build and fill cgroupstats so that taskstats can export it to user
730  * space.
731  */
732 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
733 {
734         struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
735         struct cgroup *cgrp;
736         struct css_task_iter it;
737         struct task_struct *tsk;
738
739         /* it should be kernfs_node belonging to cgroupfs and is a directory */
740         if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
741             kernfs_type(kn) != KERNFS_DIR)
742                 return -EINVAL;
743
744         mutex_lock(&cgroup_mutex);
745
746         /*
747          * We aren't being called from kernfs and there's no guarantee on
748          * @kn->priv's validity.  For this and css_tryget_online_from_dir(),
749          * @kn->priv is RCU safe.  Let's do the RCU dancing.
750          */
751         rcu_read_lock();
752         cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
753         if (!cgrp || cgroup_is_dead(cgrp)) {
754                 rcu_read_unlock();
755                 mutex_unlock(&cgroup_mutex);
756                 return -ENOENT;
757         }
758         rcu_read_unlock();
759
760         css_task_iter_start(&cgrp->self, 0, &it);
761         while ((tsk = css_task_iter_next(&it))) {
762                 switch (tsk->state) {
763                 case TASK_RUNNING:
764                         stats->nr_running++;
765                         break;
766                 case TASK_INTERRUPTIBLE:
767                         stats->nr_sleeping++;
768                         break;
769                 case TASK_UNINTERRUPTIBLE:
770                         stats->nr_uninterruptible++;
771                         break;
772                 case TASK_STOPPED:
773                         stats->nr_stopped++;
774                         break;
775                 default:
776                         if (delayacct_is_task_waiting_on_io(tsk))
777                                 stats->nr_io_wait++;
778                         break;
779                 }
780         }
781         css_task_iter_end(&it);
782
783         mutex_unlock(&cgroup_mutex);
784         return 0;
785 }
786
787 void cgroup1_check_for_release(struct cgroup *cgrp)
788 {
789         if (notify_on_release(cgrp) && !cgroup_is_populated(cgrp) &&
790             !css_has_online_children(&cgrp->self) && !cgroup_is_dead(cgrp))
791                 schedule_work(&cgrp->release_agent_work);
792 }
793
794 /*
795  * Notify userspace when a cgroup is released, by running the
796  * configured release agent with the name of the cgroup (path
797  * relative to the root of cgroup file system) as the argument.
798  *
799  * Most likely, this user command will try to rmdir this cgroup.
800  *
801  * This races with the possibility that some other task will be
802  * attached to this cgroup before it is removed, or that some other
803  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
804  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
805  * unused, and this cgroup will be reprieved from its death sentence,
806  * to continue to serve a useful existence.  Next time it's released,
807  * we will get notified again, if it still has 'notify_on_release' set.
808  *
809  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
810  * means only wait until the task is successfully execve()'d.  The
811  * separate release agent task is forked by call_usermodehelper(),
812  * then control in this thread returns here, without waiting for the
813  * release agent task.  We don't bother to wait because the caller of
814  * this routine has no use for the exit status of the release agent
815  * task, so no sense holding our caller up for that.
816  */
817 void cgroup1_release_agent(struct work_struct *work)
818 {
819         struct cgroup *cgrp =
820                 container_of(work, struct cgroup, release_agent_work);
821         char *pathbuf = NULL, *agentbuf = NULL;
822         char *argv[3], *envp[3];
823         int ret;
824
825         mutex_lock(&cgroup_mutex);
826
827         pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
828         agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
829         if (!pathbuf || !agentbuf || !strlen(agentbuf))
830                 goto out;
831
832         spin_lock_irq(&css_set_lock);
833         ret = cgroup_path_ns_locked(cgrp, pathbuf, PATH_MAX, &init_cgroup_ns);
834         spin_unlock_irq(&css_set_lock);
835         if (ret < 0 || ret >= PATH_MAX)
836                 goto out;
837
838         argv[0] = agentbuf;
839         argv[1] = pathbuf;
840         argv[2] = NULL;
841
842         /* minimal command environment */
843         envp[0] = "HOME=/";
844         envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
845         envp[2] = NULL;
846
847         mutex_unlock(&cgroup_mutex);
848         call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
849         goto out_free;
850 out:
851         mutex_unlock(&cgroup_mutex);
852 out_free:
853         kfree(agentbuf);
854         kfree(pathbuf);
855 }
856
857 /*
858  * cgroup_rename - Only allow simple rename of directories in place.
859  */
860 static int cgroup1_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
861                           const char *new_name_str)
862 {
863         struct cgroup *cgrp = kn->priv;
864         int ret;
865
866         /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
867         if (strchr(new_name_str, '\n'))
868                 return -EINVAL;
869
870         if (kernfs_type(kn) != KERNFS_DIR)
871                 return -ENOTDIR;
872         if (kn->parent != new_parent)
873                 return -EIO;
874
875         /*
876          * We're gonna grab cgroup_mutex which nests outside kernfs
877          * active_ref.  kernfs_rename() doesn't require active_ref
878          * protection.  Break them before grabbing cgroup_mutex.
879          */
880         kernfs_break_active_protection(new_parent);
881         kernfs_break_active_protection(kn);
882
883         mutex_lock(&cgroup_mutex);
884
885         ret = kernfs_rename(kn, new_parent, new_name_str);
886         if (!ret)
887                 TRACE_CGROUP_PATH(rename, cgrp);
888
889         mutex_unlock(&cgroup_mutex);
890
891         kernfs_unbreak_active_protection(kn);
892         kernfs_unbreak_active_protection(new_parent);
893         return ret;
894 }
895
896 static int cgroup1_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
897 {
898         struct cgroup_root *root = cgroup_root_from_kf(kf_root);
899         struct cgroup_subsys *ss;
900         int ssid;
901
902         for_each_subsys(ss, ssid)
903                 if (root->subsys_mask & (1 << ssid))
904                         seq_show_option(seq, ss->legacy_name, NULL);
905         if (root->flags & CGRP_ROOT_NOPREFIX)
906                 seq_puts(seq, ",noprefix");
907         if (root->flags & CGRP_ROOT_XATTR)
908                 seq_puts(seq, ",xattr");
909         if (root->flags & CGRP_ROOT_CPUSET_V2_MODE)
910                 seq_puts(seq, ",cpuset_v2_mode");
911
912         spin_lock(&release_agent_path_lock);
913         if (strlen(root->release_agent_path))
914                 seq_show_option(seq, "release_agent",
915                                 root->release_agent_path);
916         spin_unlock(&release_agent_path_lock);
917
918         if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
919                 seq_puts(seq, ",clone_children");
920         if (strlen(root->name))
921                 seq_show_option(seq, "name", root->name);
922         return 0;
923 }
924
925 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
926 {
927         char *token, *o = data;
928         bool all_ss = false, one_ss = false;
929         u16 mask = U16_MAX;
930         struct cgroup_subsys *ss;
931         int nr_opts = 0;
932         int i;
933
934 #ifdef CONFIG_CPUSETS
935         mask = ~((u16)1 << cpuset_cgrp_id);
936 #endif
937
938         memset(opts, 0, sizeof(*opts));
939
940         while ((token = strsep(&o, ",")) != NULL) {
941                 nr_opts++;
942
943                 if (!*token)
944                         return -EINVAL;
945                 if (!strcmp(token, "none")) {
946                         /* Explicitly have no subsystems */
947                         opts->none = true;
948                         continue;
949                 }
950                 if (!strcmp(token, "all")) {
951                         /* Mutually exclusive option 'all' + subsystem name */
952                         if (one_ss)
953                                 return -EINVAL;
954                         all_ss = true;
955                         continue;
956                 }
957                 if (!strcmp(token, "noprefix")) {
958                         opts->flags |= CGRP_ROOT_NOPREFIX;
959                         continue;
960                 }
961                 if (!strcmp(token, "clone_children")) {
962                         opts->cpuset_clone_children = true;
963                         continue;
964                 }
965                 if (!strcmp(token, "cpuset_v2_mode")) {
966                         opts->flags |= CGRP_ROOT_CPUSET_V2_MODE;
967                         continue;
968                 }
969                 if (!strcmp(token, "xattr")) {
970                         opts->flags |= CGRP_ROOT_XATTR;
971                         continue;
972                 }
973                 if (!strncmp(token, "release_agent=", 14)) {
974                         /* Specifying two release agents is forbidden */
975                         if (opts->release_agent)
976                                 return -EINVAL;
977                         opts->release_agent =
978                                 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
979                         if (!opts->release_agent)
980                                 return -ENOMEM;
981                         continue;
982                 }
983                 if (!strncmp(token, "name=", 5)) {
984                         const char *name = token + 5;
985                         /* Can't specify an empty name */
986                         if (!strlen(name))
987                                 return -EINVAL;
988                         /* Must match [\w.-]+ */
989                         for (i = 0; i < strlen(name); i++) {
990                                 char c = name[i];
991                                 if (isalnum(c))
992                                         continue;
993                                 if ((c == '.') || (c == '-') || (c == '_'))
994                                         continue;
995                                 return -EINVAL;
996                         }
997                         /* Specifying two names is forbidden */
998                         if (opts->name)
999                                 return -EINVAL;
1000                         opts->name = kstrndup(name,
1001                                               MAX_CGROUP_ROOT_NAMELEN - 1,
1002                                               GFP_KERNEL);
1003                         if (!opts->name)
1004                                 return -ENOMEM;
1005
1006                         continue;
1007                 }
1008
1009                 for_each_subsys(ss, i) {
1010                         if (strcmp(token, ss->legacy_name))
1011                                 continue;
1012                         if (!cgroup_ssid_enabled(i))
1013                                 continue;
1014                         if (cgroup1_ssid_disabled(i))
1015                                 continue;
1016
1017                         /* Mutually exclusive option 'all' + subsystem name */
1018                         if (all_ss)
1019                                 return -EINVAL;
1020                         opts->subsys_mask |= (1 << i);
1021                         one_ss = true;
1022
1023                         break;
1024                 }
1025                 if (i == CGROUP_SUBSYS_COUNT)
1026                         return -ENOENT;
1027         }
1028
1029         /*
1030          * If the 'all' option was specified select all the subsystems,
1031          * otherwise if 'none', 'name=' and a subsystem name options were
1032          * not specified, let's default to 'all'
1033          */
1034         if (all_ss || (!one_ss && !opts->none && !opts->name))
1035                 for_each_subsys(ss, i)
1036                         if (cgroup_ssid_enabled(i) && !cgroup1_ssid_disabled(i))
1037                                 opts->subsys_mask |= (1 << i);
1038
1039         /*
1040          * We either have to specify by name or by subsystems. (So all
1041          * empty hierarchies must have a name).
1042          */
1043         if (!opts->subsys_mask && !opts->name)
1044                 return -EINVAL;
1045
1046         /*
1047          * Option noprefix was introduced just for backward compatibility
1048          * with the old cpuset, so we allow noprefix only if mounting just
1049          * the cpuset subsystem.
1050          */
1051         if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1052                 return -EINVAL;
1053
1054         /* Can't specify "none" and some subsystems */
1055         if (opts->subsys_mask && opts->none)
1056                 return -EINVAL;
1057
1058         return 0;
1059 }
1060
1061 static int cgroup1_remount(struct kernfs_root *kf_root, int *flags, char *data)
1062 {
1063         int ret = 0;
1064         struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1065         struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
1066         struct cgroup_sb_opts opts;
1067         u16 added_mask, removed_mask;
1068
1069         cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1070
1071         /* See what subsystems are wanted */
1072         ret = parse_cgroupfs_options(data, &opts);
1073         if (ret)
1074                 goto out_unlock;
1075
1076         if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1077                 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1078                         task_tgid_nr(current), current->comm);
1079         /* See cgroup1_mount release_agent handling */
1080         if (opts.release_agent &&
1081             ((ns->user_ns != &init_user_ns) || !capable(CAP_SYS_ADMIN))) {
1082                 ret = -EINVAL;
1083                 goto out_unlock;
1084         }
1085
1086         added_mask = opts.subsys_mask & ~root->subsys_mask;
1087         removed_mask = root->subsys_mask & ~opts.subsys_mask;
1088
1089         /* Don't allow flags or name to change at remount */
1090         if ((opts.flags ^ root->flags) ||
1091             (opts.name && strcmp(opts.name, root->name))) {
1092                 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1093                        opts.flags, opts.name ?: "", root->flags, root->name);
1094                 ret = -EINVAL;
1095                 goto out_unlock;
1096         }
1097
1098         /* remounting is not allowed for populated hierarchies */
1099         if (!list_empty(&root->cgrp.self.children)) {
1100                 ret = -EBUSY;
1101                 goto out_unlock;
1102         }
1103
1104         ret = rebind_subsystems(root, added_mask);
1105         if (ret)
1106                 goto out_unlock;
1107
1108         WARN_ON(rebind_subsystems(&cgrp_dfl_root, removed_mask));
1109
1110         if (opts.release_agent) {
1111                 spin_lock(&release_agent_path_lock);
1112                 strcpy(root->release_agent_path, opts.release_agent);
1113                 spin_unlock(&release_agent_path_lock);
1114         }
1115
1116         trace_cgroup_remount(root);
1117
1118  out_unlock:
1119         kfree(opts.release_agent);
1120         kfree(opts.name);
1121         mutex_unlock(&cgroup_mutex);
1122         return ret;
1123 }
1124
1125 struct kernfs_syscall_ops cgroup1_kf_syscall_ops = {
1126         .rename                 = cgroup1_rename,
1127         .show_options           = cgroup1_show_options,
1128         .remount_fs             = cgroup1_remount,
1129         .mkdir                  = cgroup_mkdir,
1130         .rmdir                  = cgroup_rmdir,
1131         .show_path              = cgroup_show_path,
1132 };
1133
1134 struct dentry *cgroup1_mount(struct file_system_type *fs_type, int flags,
1135                              void *data, unsigned long magic,
1136                              struct cgroup_namespace *ns)
1137 {
1138         struct super_block *pinned_sb = NULL;
1139         struct cgroup_sb_opts opts;
1140         struct cgroup_root *root;
1141         struct cgroup_subsys *ss;
1142         struct dentry *dentry;
1143         int i, ret;
1144         bool new_root = false;
1145
1146         cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1147
1148         /* First find the desired set of subsystems */
1149         ret = parse_cgroupfs_options(data, &opts);
1150         if (ret)
1151                 goto out_unlock;
1152
1153         /*
1154          * Destruction of cgroup root is asynchronous, so subsystems may
1155          * still be dying after the previous unmount.  Let's drain the
1156          * dying subsystems.  We just need to ensure that the ones
1157          * unmounted previously finish dying and don't care about new ones
1158          * starting.  Testing ref liveliness is good enough.
1159          */
1160         for_each_subsys(ss, i) {
1161                 if (!(opts.subsys_mask & (1 << i)) ||
1162                     ss->root == &cgrp_dfl_root)
1163                         continue;
1164
1165                 if (!percpu_ref_tryget_live(&ss->root->cgrp.self.refcnt)) {
1166                         mutex_unlock(&cgroup_mutex);
1167                         msleep(10);
1168                         ret = restart_syscall();
1169                         goto out_free;
1170                 }
1171                 cgroup_put(&ss->root->cgrp);
1172         }
1173
1174         for_each_root(root) {
1175                 bool name_match = false;
1176
1177                 if (root == &cgrp_dfl_root)
1178                         continue;
1179
1180                 /*
1181                  * If we asked for a name then it must match.  Also, if
1182                  * name matches but sybsys_mask doesn't, we should fail.
1183                  * Remember whether name matched.
1184                  */
1185                 if (opts.name) {
1186                         if (strcmp(opts.name, root->name))
1187                                 continue;
1188                         name_match = true;
1189                 }
1190
1191                 /*
1192                  * If we asked for subsystems (or explicitly for no
1193                  * subsystems) then they must match.
1194                  */
1195                 if ((opts.subsys_mask || opts.none) &&
1196                     (opts.subsys_mask != root->subsys_mask)) {
1197                         if (!name_match)
1198                                 continue;
1199                         ret = -EBUSY;
1200                         goto out_unlock;
1201                 }
1202
1203                 if (root->flags ^ opts.flags)
1204                         pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1205
1206                 /*
1207                  * We want to reuse @root whose lifetime is governed by its
1208                  * ->cgrp.  Let's check whether @root is alive and keep it
1209                  * that way.  As cgroup_kill_sb() can happen anytime, we
1210                  * want to block it by pinning the sb so that @root doesn't
1211                  * get killed before mount is complete.
1212                  *
1213                  * With the sb pinned, tryget_live can reliably indicate
1214                  * whether @root can be reused.  If it's being killed,
1215                  * drain it.  We can use wait_queue for the wait but this
1216                  * path is super cold.  Let's just sleep a bit and retry.
1217                  */
1218                 pinned_sb = kernfs_pin_sb(root->kf_root, NULL);
1219                 if (IS_ERR(pinned_sb) ||
1220                     !percpu_ref_tryget_live(&root->cgrp.self.refcnt)) {
1221                         mutex_unlock(&cgroup_mutex);
1222                         if (!IS_ERR_OR_NULL(pinned_sb))
1223                                 deactivate_super(pinned_sb);
1224                         msleep(10);
1225                         ret = restart_syscall();
1226                         goto out_free;
1227                 }
1228
1229                 ret = 0;
1230                 goto out_unlock;
1231         }
1232
1233         /*
1234          * No such thing, create a new one.  name= matching without subsys
1235          * specification is allowed for already existing hierarchies but we
1236          * can't create new one without subsys specification.
1237          */
1238         if (!opts.subsys_mask && !opts.none) {
1239                 ret = -EINVAL;
1240                 goto out_unlock;
1241         }
1242
1243         /* Hierarchies may only be created in the initial cgroup namespace. */
1244         if (ns != &init_cgroup_ns) {
1245                 ret = -EPERM;
1246                 goto out_unlock;
1247         }
1248         /*
1249          * Release agent gets called with all capabilities,
1250          * require capabilities to set release agent.
1251          */
1252         if (opts.release_agent &&
1253             ((ns->user_ns != &init_user_ns) || !capable(CAP_SYS_ADMIN))) {
1254                 ret = -EINVAL;
1255                 goto out_unlock;
1256         }
1257
1258         root = kzalloc(sizeof(*root), GFP_KERNEL);
1259         if (!root) {
1260                 ret = -ENOMEM;
1261                 goto out_unlock;
1262         }
1263         new_root = true;
1264
1265         init_cgroup_root(root, &opts);
1266
1267         ret = cgroup_setup_root(root, opts.subsys_mask, PERCPU_REF_INIT_DEAD);
1268         if (ret)
1269                 cgroup_free_root(root);
1270
1271 out_unlock:
1272         mutex_unlock(&cgroup_mutex);
1273 out_free:
1274         kfree(opts.release_agent);
1275         kfree(opts.name);
1276
1277         if (ret)
1278                 return ERR_PTR(ret);
1279
1280         dentry = cgroup_do_mount(&cgroup_fs_type, flags, root,
1281                                  CGROUP_SUPER_MAGIC, ns);
1282
1283         /*
1284          * There's a race window after we release cgroup_mutex and before
1285          * allocating a superblock. Make sure a concurrent process won't
1286          * be able to re-use the root during this window by delaying the
1287          * initialization of root refcnt.
1288          */
1289         if (new_root) {
1290                 mutex_lock(&cgroup_mutex);
1291                 percpu_ref_reinit(&root->cgrp.self.refcnt);
1292                 mutex_unlock(&cgroup_mutex);
1293         }
1294
1295         /*
1296          * If @pinned_sb, we're reusing an existing root and holding an
1297          * extra ref on its sb.  Mount is complete.  Put the extra ref.
1298          */
1299         if (pinned_sb)
1300                 deactivate_super(pinned_sb);
1301
1302         return dentry;
1303 }
1304
1305 static int __init cgroup1_wq_init(void)
1306 {
1307         /*
1308          * Used to destroy pidlists and separate to serve as flush domain.
1309          * Cap @max_active to 1 too.
1310          */
1311         cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
1312                                                     0, 1);
1313         BUG_ON(!cgroup_pidlist_destroy_wq);
1314         return 0;
1315 }
1316 core_initcall(cgroup1_wq_init);
1317
1318 static int __init cgroup_no_v1(char *str)
1319 {
1320         struct cgroup_subsys *ss;
1321         char *token;
1322         int i;
1323
1324         while ((token = strsep(&str, ",")) != NULL) {
1325                 if (!*token)
1326                         continue;
1327
1328                 if (!strcmp(token, "all")) {
1329                         cgroup_no_v1_mask = U16_MAX;
1330                         break;
1331                 }
1332
1333                 for_each_subsys(ss, i) {
1334                         if (strcmp(token, ss->name) &&
1335                             strcmp(token, ss->legacy_name))
1336                                 continue;
1337
1338                         cgroup_no_v1_mask |= 1 << i;
1339                 }
1340         }
1341         return 1;
1342 }
1343 __setup("cgroup_no_v1=", cgroup_no_v1);