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