FROMLIST: psi: introduce psi monitor
[GitHub/LineageOS/android_kernel_motorola_exynos9610.git] / kernel / cgroup / cgroup.c
1 /*
2 * Generic process-grouping system.
3 *
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
6 *
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
10 *
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
15 *
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
18 *
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
23 *
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
27 */
28
29 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
30
31 #include "cgroup-internal.h"
32
33 #include <linux/cred.h>
34 #include <linux/errno.h>
35 #include <linux/init_task.h>
36 #include <linux/kernel.h>
37 #include <linux/magic.h>
38 #include <linux/mutex.h>
39 #include <linux/mount.h>
40 #include <linux/pagemap.h>
41 #include <linux/proc_fs.h>
42 #include <linux/rcupdate.h>
43 #include <linux/sched.h>
44 #include <linux/sched/task.h>
45 #include <linux/slab.h>
46 #include <linux/spinlock.h>
47 #include <linux/percpu-rwsem.h>
48 #include <linux/string.h>
49 #include <linux/hashtable.h>
50 #include <linux/idr.h>
51 #include <linux/kthread.h>
52 #include <linux/atomic.h>
53 #include <linux/cpuset.h>
54 #include <linux/proc_ns.h>
55 #include <linux/nsproxy.h>
56 #include <linux/file.h>
57 #include <linux/psi.h>
58 #include <net/sock.h>
59
60 #define CREATE_TRACE_POINTS
61 #include <trace/events/cgroup.h>
62
63 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
64 MAX_CFTYPE_NAME + 2)
65
66 /*
67 * cgroup_mutex is the master lock. Any modification to cgroup or its
68 * hierarchy must be performed while holding it.
69 *
70 * css_set_lock protects task->cgroups pointer, the list of css_set
71 * objects, and the chain of tasks off each css_set.
72 *
73 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
74 * cgroup.h can use them for lockdep annotations.
75 */
76 DEFINE_MUTEX(cgroup_mutex);
77 DEFINE_SPINLOCK(css_set_lock);
78
79 #ifdef CONFIG_PROVE_RCU
80 EXPORT_SYMBOL_GPL(cgroup_mutex);
81 EXPORT_SYMBOL_GPL(css_set_lock);
82 #endif
83
84 /*
85 * Protects cgroup_idr and css_idr so that IDs can be released without
86 * grabbing cgroup_mutex.
87 */
88 static DEFINE_SPINLOCK(cgroup_idr_lock);
89
90 /*
91 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
92 * against file removal/re-creation across css hiding.
93 */
94 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
95
96 struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
97
98 #define cgroup_assert_mutex_or_rcu_locked() \
99 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
100 !lockdep_is_held(&cgroup_mutex), \
101 "cgroup_mutex or RCU read lock required");
102
103 /*
104 * cgroup destruction makes heavy use of work items and there can be a lot
105 * of concurrent destructions. Use a separate workqueue so that cgroup
106 * destruction work items don't end up filling up max_active of system_wq
107 * which may lead to deadlock.
108 */
109 static struct workqueue_struct *cgroup_destroy_wq;
110
111 /* generate an array of cgroup subsystem pointers */
112 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
113 struct cgroup_subsys *cgroup_subsys[] = {
114 #include <linux/cgroup_subsys.h>
115 };
116 #undef SUBSYS
117
118 /* array of cgroup subsystem names */
119 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
120 static const char *cgroup_subsys_name[] = {
121 #include <linux/cgroup_subsys.h>
122 };
123 #undef SUBSYS
124
125 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
126 #define SUBSYS(_x) \
127 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
128 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
129 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
130 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
131 #include <linux/cgroup_subsys.h>
132 #undef SUBSYS
133
134 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
135 static struct static_key_true *cgroup_subsys_enabled_key[] = {
136 #include <linux/cgroup_subsys.h>
137 };
138 #undef SUBSYS
139
140 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
141 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
142 #include <linux/cgroup_subsys.h>
143 };
144 #undef SUBSYS
145
146 /*
147 * The default hierarchy, reserved for the subsystems that are otherwise
148 * unattached - it never has more than a single cgroup, and all tasks are
149 * part of that cgroup.
150 */
151 struct cgroup_root cgrp_dfl_root;
152 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
153
154 /*
155 * The default hierarchy always exists but is hidden until mounted for the
156 * first time. This is for backward compatibility.
157 */
158 static bool cgrp_dfl_visible;
159
160 /* some controllers are not supported in the default hierarchy */
161 static u16 cgrp_dfl_inhibit_ss_mask;
162
163 /* some controllers are implicitly enabled on the default hierarchy */
164 static u16 cgrp_dfl_implicit_ss_mask;
165
166 /* some controllers can be threaded on the default hierarchy */
167 static u16 cgrp_dfl_threaded_ss_mask;
168
169 /* The list of hierarchy roots */
170 LIST_HEAD(cgroup_roots);
171 static int cgroup_root_count;
172
173 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
174 static DEFINE_IDR(cgroup_hierarchy_idr);
175
176 /*
177 * Assign a monotonically increasing serial number to csses. It guarantees
178 * cgroups with bigger numbers are newer than those with smaller numbers.
179 * Also, as csses are always appended to the parent's ->children list, it
180 * guarantees that sibling csses are always sorted in the ascending serial
181 * number order on the list. Protected by cgroup_mutex.
182 */
183 static u64 css_serial_nr_next = 1;
184
185 /*
186 * These bitmasks identify subsystems with specific features to avoid
187 * having to do iterative checks repeatedly.
188 */
189 static u16 have_fork_callback __read_mostly;
190 static u16 have_exit_callback __read_mostly;
191 static u16 have_release_callback __read_mostly;
192 static u16 have_canfork_callback __read_mostly;
193
194 /* cgroup namespace for init task */
195 struct cgroup_namespace init_cgroup_ns = {
196 .count = REFCOUNT_INIT(2),
197 .user_ns = &init_user_ns,
198 .ns.ops = &cgroupns_operations,
199 .ns.inum = PROC_CGROUP_INIT_INO,
200 .root_cset = &init_css_set,
201 };
202
203 static struct file_system_type cgroup2_fs_type;
204 static struct cftype cgroup_base_files[];
205
206 static int cgroup_apply_control(struct cgroup *cgrp);
207 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
208 static void css_task_iter_advance(struct css_task_iter *it);
209 static int cgroup_destroy_locked(struct cgroup *cgrp);
210 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
211 struct cgroup_subsys *ss);
212 static void css_release(struct percpu_ref *ref);
213 static void kill_css(struct cgroup_subsys_state *css);
214 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
215 struct cgroup *cgrp, struct cftype cfts[],
216 bool is_add);
217
218 /**
219 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
220 * @ssid: subsys ID of interest
221 *
222 * cgroup_subsys_enabled() can only be used with literal subsys names which
223 * is fine for individual subsystems but unsuitable for cgroup core. This
224 * is slower static_key_enabled() based test indexed by @ssid.
225 */
226 bool cgroup_ssid_enabled(int ssid)
227 {
228 if (CGROUP_SUBSYS_COUNT == 0)
229 return false;
230
231 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
232 }
233
234 /**
235 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
236 * @cgrp: the cgroup of interest
237 *
238 * The default hierarchy is the v2 interface of cgroup and this function
239 * can be used to test whether a cgroup is on the default hierarchy for
240 * cases where a subsystem should behave differnetly depending on the
241 * interface version.
242 *
243 * The set of behaviors which change on the default hierarchy are still
244 * being determined and the mount option is prefixed with __DEVEL__.
245 *
246 * List of changed behaviors:
247 *
248 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
249 * and "name" are disallowed.
250 *
251 * - When mounting an existing superblock, mount options should match.
252 *
253 * - Remount is disallowed.
254 *
255 * - rename(2) is disallowed.
256 *
257 * - "tasks" is removed. Everything should be at process granularity. Use
258 * "cgroup.procs" instead.
259 *
260 * - "cgroup.procs" is not sorted. pids will be unique unless they got
261 * recycled inbetween reads.
262 *
263 * - "release_agent" and "notify_on_release" are removed. Replacement
264 * notification mechanism will be implemented.
265 *
266 * - "cgroup.clone_children" is removed.
267 *
268 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
269 * and its descendants contain no task; otherwise, 1. The file also
270 * generates kernfs notification which can be monitored through poll and
271 * [di]notify when the value of the file changes.
272 *
273 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
274 * take masks of ancestors with non-empty cpus/mems, instead of being
275 * moved to an ancestor.
276 *
277 * - cpuset: a task can be moved into an empty cpuset, and again it takes
278 * masks of ancestors.
279 *
280 * - memcg: use_hierarchy is on by default and the cgroup file for the flag
281 * is not created.
282 *
283 * - blkcg: blk-throttle becomes properly hierarchical.
284 *
285 * - debug: disallowed on the default hierarchy.
286 */
287 bool cgroup_on_dfl(const struct cgroup *cgrp)
288 {
289 return cgrp->root == &cgrp_dfl_root;
290 }
291
292 /* IDR wrappers which synchronize using cgroup_idr_lock */
293 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
294 gfp_t gfp_mask)
295 {
296 int ret;
297
298 idr_preload(gfp_mask);
299 spin_lock_bh(&cgroup_idr_lock);
300 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
301 spin_unlock_bh(&cgroup_idr_lock);
302 idr_preload_end();
303 return ret;
304 }
305
306 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
307 {
308 void *ret;
309
310 spin_lock_bh(&cgroup_idr_lock);
311 ret = idr_replace(idr, ptr, id);
312 spin_unlock_bh(&cgroup_idr_lock);
313 return ret;
314 }
315
316 static void cgroup_idr_remove(struct idr *idr, int id)
317 {
318 spin_lock_bh(&cgroup_idr_lock);
319 idr_remove(idr, id);
320 spin_unlock_bh(&cgroup_idr_lock);
321 }
322
323 static bool cgroup_has_tasks(struct cgroup *cgrp)
324 {
325 return cgrp->nr_populated_csets;
326 }
327
328 bool cgroup_is_threaded(struct cgroup *cgrp)
329 {
330 return cgrp->dom_cgrp != cgrp;
331 }
332
333 /* can @cgrp host both domain and threaded children? */
334 static bool cgroup_is_mixable(struct cgroup *cgrp)
335 {
336 /*
337 * Root isn't under domain level resource control exempting it from
338 * the no-internal-process constraint, so it can serve as a thread
339 * root and a parent of resource domains at the same time.
340 */
341 return !cgroup_parent(cgrp);
342 }
343
344 /* can @cgrp become a thread root? should always be true for a thread root */
345 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
346 {
347 /* mixables don't care */
348 if (cgroup_is_mixable(cgrp))
349 return true;
350
351 /* domain roots can't be nested under threaded */
352 if (cgroup_is_threaded(cgrp))
353 return false;
354
355 /* can only have either domain or threaded children */
356 if (cgrp->nr_populated_domain_children)
357 return false;
358
359 /* and no domain controllers can be enabled */
360 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
361 return false;
362
363 return true;
364 }
365
366 /* is @cgrp root of a threaded subtree? */
367 bool cgroup_is_thread_root(struct cgroup *cgrp)
368 {
369 /* thread root should be a domain */
370 if (cgroup_is_threaded(cgrp))
371 return false;
372
373 /* a domain w/ threaded children is a thread root */
374 if (cgrp->nr_threaded_children)
375 return true;
376
377 /*
378 * A domain which has tasks and explicit threaded controllers
379 * enabled is a thread root.
380 */
381 if (cgroup_has_tasks(cgrp) &&
382 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
383 return true;
384
385 return false;
386 }
387
388 /* a domain which isn't connected to the root w/o brekage can't be used */
389 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
390 {
391 /* the cgroup itself can be a thread root */
392 if (cgroup_is_threaded(cgrp))
393 return false;
394
395 /* but the ancestors can't be unless mixable */
396 while ((cgrp = cgroup_parent(cgrp))) {
397 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
398 return false;
399 if (cgroup_is_threaded(cgrp))
400 return false;
401 }
402
403 return true;
404 }
405
406 /* subsystems visibly enabled on a cgroup */
407 static u16 cgroup_control(struct cgroup *cgrp)
408 {
409 struct cgroup *parent = cgroup_parent(cgrp);
410 u16 root_ss_mask = cgrp->root->subsys_mask;
411
412 if (parent) {
413 u16 ss_mask = parent->subtree_control;
414
415 /* threaded cgroups can only have threaded controllers */
416 if (cgroup_is_threaded(cgrp))
417 ss_mask &= cgrp_dfl_threaded_ss_mask;
418 return ss_mask;
419 }
420
421 if (cgroup_on_dfl(cgrp))
422 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
423 cgrp_dfl_implicit_ss_mask);
424 return root_ss_mask;
425 }
426
427 /* subsystems enabled on a cgroup */
428 static u16 cgroup_ss_mask(struct cgroup *cgrp)
429 {
430 struct cgroup *parent = cgroup_parent(cgrp);
431
432 if (parent) {
433 u16 ss_mask = parent->subtree_ss_mask;
434
435 /* threaded cgroups can only have threaded controllers */
436 if (cgroup_is_threaded(cgrp))
437 ss_mask &= cgrp_dfl_threaded_ss_mask;
438 return ss_mask;
439 }
440
441 return cgrp->root->subsys_mask;
442 }
443
444 /**
445 * cgroup_css - obtain a cgroup's css for the specified subsystem
446 * @cgrp: the cgroup of interest
447 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
448 *
449 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
450 * function must be called either under cgroup_mutex or rcu_read_lock() and
451 * the caller is responsible for pinning the returned css if it wants to
452 * keep accessing it outside the said locks. This function may return
453 * %NULL if @cgrp doesn't have @subsys_id enabled.
454 */
455 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
456 struct cgroup_subsys *ss)
457 {
458 if (ss)
459 return rcu_dereference_check(cgrp->subsys[ss->id],
460 lockdep_is_held(&cgroup_mutex));
461 else
462 return &cgrp->self;
463 }
464
465 /**
466 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
467 * @cgrp: the cgroup of interest
468 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
469 *
470 * Similar to cgroup_css() but returns the effective css, which is defined
471 * as the matching css of the nearest ancestor including self which has @ss
472 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
473 * function is guaranteed to return non-NULL css.
474 */
475 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
476 struct cgroup_subsys *ss)
477 {
478 lockdep_assert_held(&cgroup_mutex);
479
480 if (!ss)
481 return &cgrp->self;
482
483 /*
484 * This function is used while updating css associations and thus
485 * can't test the csses directly. Test ss_mask.
486 */
487 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
488 cgrp = cgroup_parent(cgrp);
489 if (!cgrp)
490 return NULL;
491 }
492
493 return cgroup_css(cgrp, ss);
494 }
495
496 /**
497 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
498 * @cgrp: the cgroup of interest
499 * @ss: the subsystem of interest
500 *
501 * Find and get the effective css of @cgrp for @ss. The effective css is
502 * defined as the matching css of the nearest ancestor including self which
503 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
504 * the root css is returned, so this function always returns a valid css.
505 * The returned css must be put using css_put().
506 */
507 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
508 struct cgroup_subsys *ss)
509 {
510 struct cgroup_subsys_state *css;
511
512 rcu_read_lock();
513
514 do {
515 css = cgroup_css(cgrp, ss);
516
517 if (css && css_tryget_online(css))
518 goto out_unlock;
519 cgrp = cgroup_parent(cgrp);
520 } while (cgrp);
521
522 css = init_css_set.subsys[ss->id];
523 css_get(css);
524 out_unlock:
525 rcu_read_unlock();
526 return css;
527 }
528
529 static void cgroup_get_live(struct cgroup *cgrp)
530 {
531 WARN_ON_ONCE(cgroup_is_dead(cgrp));
532 css_get(&cgrp->self);
533 }
534
535 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
536 {
537 struct cgroup *cgrp = of->kn->parent->priv;
538 struct cftype *cft = of_cft(of);
539
540 /*
541 * This is open and unprotected implementation of cgroup_css().
542 * seq_css() is only called from a kernfs file operation which has
543 * an active reference on the file. Because all the subsystem
544 * files are drained before a css is disassociated with a cgroup,
545 * the matching css from the cgroup's subsys table is guaranteed to
546 * be and stay valid until the enclosing operation is complete.
547 */
548 if (cft->ss)
549 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
550 else
551 return &cgrp->self;
552 }
553 EXPORT_SYMBOL_GPL(of_css);
554
555 /**
556 * for_each_css - iterate all css's of a cgroup
557 * @css: the iteration cursor
558 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
559 * @cgrp: the target cgroup to iterate css's of
560 *
561 * Should be called under cgroup_[tree_]mutex.
562 */
563 #define for_each_css(css, ssid, cgrp) \
564 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
565 if (!((css) = rcu_dereference_check( \
566 (cgrp)->subsys[(ssid)], \
567 lockdep_is_held(&cgroup_mutex)))) { } \
568 else
569
570 /**
571 * for_each_e_css - iterate all effective css's of a cgroup
572 * @css: the iteration cursor
573 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
574 * @cgrp: the target cgroup to iterate css's of
575 *
576 * Should be called under cgroup_[tree_]mutex.
577 */
578 #define for_each_e_css(css, ssid, cgrp) \
579 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
580 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
581 ; \
582 else
583
584 /**
585 * do_each_subsys_mask - filter for_each_subsys with a bitmask
586 * @ss: the iteration cursor
587 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
588 * @ss_mask: the bitmask
589 *
590 * The block will only run for cases where the ssid-th bit (1 << ssid) of
591 * @ss_mask is set.
592 */
593 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
594 unsigned long __ss_mask = (ss_mask); \
595 if (!CGROUP_SUBSYS_COUNT) { /* to avoid spurious gcc warning */ \
596 (ssid) = 0; \
597 break; \
598 } \
599 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
600 (ss) = cgroup_subsys[ssid]; \
601 {
602
603 #define while_each_subsys_mask() \
604 } \
605 } \
606 } while (false)
607
608 /* iterate over child cgrps, lock should be held throughout iteration */
609 #define cgroup_for_each_live_child(child, cgrp) \
610 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
611 if (({ lockdep_assert_held(&cgroup_mutex); \
612 cgroup_is_dead(child); })) \
613 ; \
614 else
615
616 /* walk live descendants in preorder */
617 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
618 css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
619 if (({ lockdep_assert_held(&cgroup_mutex); \
620 (dsct) = (d_css)->cgroup; \
621 cgroup_is_dead(dsct); })) \
622 ; \
623 else
624
625 /* walk live descendants in postorder */
626 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
627 css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
628 if (({ lockdep_assert_held(&cgroup_mutex); \
629 (dsct) = (d_css)->cgroup; \
630 cgroup_is_dead(dsct); })) \
631 ; \
632 else
633
634 /*
635 * The default css_set - used by init and its children prior to any
636 * hierarchies being mounted. It contains a pointer to the root state
637 * for each subsystem. Also used to anchor the list of css_sets. Not
638 * reference-counted, to improve performance when child cgroups
639 * haven't been created.
640 */
641 struct css_set init_css_set = {
642 .refcount = REFCOUNT_INIT(1),
643 .dom_cset = &init_css_set,
644 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
645 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
646 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
647 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
648 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
649 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
650 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
651 };
652
653 static int css_set_count = 1; /* 1 for init_css_set */
654
655 static bool css_set_threaded(struct css_set *cset)
656 {
657 return cset->dom_cset != cset;
658 }
659
660 /**
661 * css_set_populated - does a css_set contain any tasks?
662 * @cset: target css_set
663 *
664 * css_set_populated() should be the same as !!cset->nr_tasks at steady
665 * state. However, css_set_populated() can be called while a task is being
666 * added to or removed from the linked list before the nr_tasks is
667 * properly updated. Hence, we can't just look at ->nr_tasks here.
668 */
669 static bool css_set_populated(struct css_set *cset)
670 {
671 lockdep_assert_held(&css_set_lock);
672
673 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
674 }
675
676 /**
677 * cgroup_update_populated - update the populated count of a cgroup
678 * @cgrp: the target cgroup
679 * @populated: inc or dec populated count
680 *
681 * One of the css_sets associated with @cgrp is either getting its first
682 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
683 * count is propagated towards root so that a given cgroup's
684 * nr_populated_children is zero iff none of its descendants contain any
685 * tasks.
686 *
687 * @cgrp's interface file "cgroup.populated" is zero if both
688 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
689 * 1 otherwise. When the sum changes from or to zero, userland is notified
690 * that the content of the interface file has changed. This can be used to
691 * detect when @cgrp and its descendants become populated or empty.
692 */
693 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
694 {
695 struct cgroup *child = NULL;
696 int adj = populated ? 1 : -1;
697
698 lockdep_assert_held(&css_set_lock);
699
700 do {
701 bool was_populated = cgroup_is_populated(cgrp);
702
703 if (!child) {
704 cgrp->nr_populated_csets += adj;
705 } else {
706 if (cgroup_is_threaded(child))
707 cgrp->nr_populated_threaded_children += adj;
708 else
709 cgrp->nr_populated_domain_children += adj;
710 }
711
712 if (was_populated == cgroup_is_populated(cgrp))
713 break;
714
715 cgroup1_check_for_release(cgrp);
716 cgroup_file_notify(&cgrp->events_file);
717
718 child = cgrp;
719 cgrp = cgroup_parent(cgrp);
720 } while (cgrp);
721 }
722
723 /**
724 * css_set_update_populated - update populated state of a css_set
725 * @cset: target css_set
726 * @populated: whether @cset is populated or depopulated
727 *
728 * @cset is either getting the first task or losing the last. Update the
729 * populated counters of all associated cgroups accordingly.
730 */
731 static void css_set_update_populated(struct css_set *cset, bool populated)
732 {
733 struct cgrp_cset_link *link;
734
735 lockdep_assert_held(&css_set_lock);
736
737 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
738 cgroup_update_populated(link->cgrp, populated);
739 }
740
741 /**
742 * css_set_move_task - move a task from one css_set to another
743 * @task: task being moved
744 * @from_cset: css_set @task currently belongs to (may be NULL)
745 * @to_cset: new css_set @task is being moved to (may be NULL)
746 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
747 *
748 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
749 * css_set, @from_cset can be NULL. If @task is being disassociated
750 * instead of moved, @to_cset can be NULL.
751 *
752 * This function automatically handles populated counter updates and
753 * css_task_iter adjustments but the caller is responsible for managing
754 * @from_cset and @to_cset's reference counts.
755 */
756 static void css_set_move_task(struct task_struct *task,
757 struct css_set *from_cset, struct css_set *to_cset,
758 bool use_mg_tasks)
759 {
760 lockdep_assert_held(&css_set_lock);
761
762 if (to_cset && !css_set_populated(to_cset))
763 css_set_update_populated(to_cset, true);
764
765 if (from_cset) {
766 struct css_task_iter *it, *pos;
767
768 WARN_ON_ONCE(list_empty(&task->cg_list));
769
770 /*
771 * @task is leaving, advance task iterators which are
772 * pointing to it so that they can resume at the next
773 * position. Advancing an iterator might remove it from
774 * the list, use safe walk. See css_task_iter_advance*()
775 * for details.
776 */
777 list_for_each_entry_safe(it, pos, &from_cset->task_iters,
778 iters_node)
779 if (it->task_pos == &task->cg_list)
780 css_task_iter_advance(it);
781
782 list_del_init(&task->cg_list);
783 if (!css_set_populated(from_cset))
784 css_set_update_populated(from_cset, false);
785 } else {
786 WARN_ON_ONCE(!list_empty(&task->cg_list));
787 }
788
789 if (to_cset) {
790 /*
791 * We are synchronized through cgroup_threadgroup_rwsem
792 * against PF_EXITING setting such that we can't race
793 * against cgroup_exit() changing the css_set to
794 * init_css_set and dropping the old one.
795 */
796 WARN_ON_ONCE(task->flags & PF_EXITING);
797
798 cgroup_move_task(task, to_cset);
799 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
800 &to_cset->tasks);
801 }
802 }
803
804 /*
805 * hash table for cgroup groups. This improves the performance to find
806 * an existing css_set. This hash doesn't (currently) take into
807 * account cgroups in empty hierarchies.
808 */
809 #define CSS_SET_HASH_BITS 7
810 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
811
812 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
813 {
814 unsigned long key = 0UL;
815 struct cgroup_subsys *ss;
816 int i;
817
818 for_each_subsys(ss, i)
819 key += (unsigned long)css[i];
820 key = (key >> 16) ^ key;
821
822 return key;
823 }
824
825 void put_css_set_locked(struct css_set *cset)
826 {
827 struct cgrp_cset_link *link, *tmp_link;
828 struct cgroup_subsys *ss;
829 int ssid;
830
831 lockdep_assert_held(&css_set_lock);
832
833 if (!refcount_dec_and_test(&cset->refcount))
834 return;
835
836 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
837
838 /* This css_set is dead. unlink it and release cgroup and css refs */
839 for_each_subsys(ss, ssid) {
840 list_del(&cset->e_cset_node[ssid]);
841 css_put(cset->subsys[ssid]);
842 }
843 hash_del(&cset->hlist);
844 css_set_count--;
845
846 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
847 list_del(&link->cset_link);
848 list_del(&link->cgrp_link);
849 if (cgroup_parent(link->cgrp))
850 cgroup_put(link->cgrp);
851 kfree(link);
852 }
853
854 if (css_set_threaded(cset)) {
855 list_del(&cset->threaded_csets_node);
856 put_css_set_locked(cset->dom_cset);
857 }
858
859 kfree_rcu(cset, rcu_head);
860 }
861
862 /**
863 * compare_css_sets - helper function for find_existing_css_set().
864 * @cset: candidate css_set being tested
865 * @old_cset: existing css_set for a task
866 * @new_cgrp: cgroup that's being entered by the task
867 * @template: desired set of css pointers in css_set (pre-calculated)
868 *
869 * Returns true if "cset" matches "old_cset" except for the hierarchy
870 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
871 */
872 static bool compare_css_sets(struct css_set *cset,
873 struct css_set *old_cset,
874 struct cgroup *new_cgrp,
875 struct cgroup_subsys_state *template[])
876 {
877 struct cgroup *new_dfl_cgrp;
878 struct list_head *l1, *l2;
879
880 /*
881 * On the default hierarchy, there can be csets which are
882 * associated with the same set of cgroups but different csses.
883 * Let's first ensure that csses match.
884 */
885 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
886 return false;
887
888
889 /* @cset's domain should match the default cgroup's */
890 if (cgroup_on_dfl(new_cgrp))
891 new_dfl_cgrp = new_cgrp;
892 else
893 new_dfl_cgrp = old_cset->dfl_cgrp;
894
895 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
896 return false;
897
898 /*
899 * Compare cgroup pointers in order to distinguish between
900 * different cgroups in hierarchies. As different cgroups may
901 * share the same effective css, this comparison is always
902 * necessary.
903 */
904 l1 = &cset->cgrp_links;
905 l2 = &old_cset->cgrp_links;
906 while (1) {
907 struct cgrp_cset_link *link1, *link2;
908 struct cgroup *cgrp1, *cgrp2;
909
910 l1 = l1->next;
911 l2 = l2->next;
912 /* See if we reached the end - both lists are equal length. */
913 if (l1 == &cset->cgrp_links) {
914 BUG_ON(l2 != &old_cset->cgrp_links);
915 break;
916 } else {
917 BUG_ON(l2 == &old_cset->cgrp_links);
918 }
919 /* Locate the cgroups associated with these links. */
920 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
921 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
922 cgrp1 = link1->cgrp;
923 cgrp2 = link2->cgrp;
924 /* Hierarchies should be linked in the same order. */
925 BUG_ON(cgrp1->root != cgrp2->root);
926
927 /*
928 * If this hierarchy is the hierarchy of the cgroup
929 * that's changing, then we need to check that this
930 * css_set points to the new cgroup; if it's any other
931 * hierarchy, then this css_set should point to the
932 * same cgroup as the old css_set.
933 */
934 if (cgrp1->root == new_cgrp->root) {
935 if (cgrp1 != new_cgrp)
936 return false;
937 } else {
938 if (cgrp1 != cgrp2)
939 return false;
940 }
941 }
942 return true;
943 }
944
945 /**
946 * find_existing_css_set - init css array and find the matching css_set
947 * @old_cset: the css_set that we're using before the cgroup transition
948 * @cgrp: the cgroup that we're moving into
949 * @template: out param for the new set of csses, should be clear on entry
950 */
951 static struct css_set *find_existing_css_set(struct css_set *old_cset,
952 struct cgroup *cgrp,
953 struct cgroup_subsys_state *template[])
954 {
955 struct cgroup_root *root = cgrp->root;
956 struct cgroup_subsys *ss;
957 struct css_set *cset;
958 unsigned long key;
959 int i;
960
961 /*
962 * Build the set of subsystem state objects that we want to see in the
963 * new css_set. while subsystems can change globally, the entries here
964 * won't change, so no need for locking.
965 */
966 for_each_subsys(ss, i) {
967 if (root->subsys_mask & (1UL << i)) {
968 /*
969 * @ss is in this hierarchy, so we want the
970 * effective css from @cgrp.
971 */
972 template[i] = cgroup_e_css(cgrp, ss);
973 } else {
974 /*
975 * @ss is not in this hierarchy, so we don't want
976 * to change the css.
977 */
978 template[i] = old_cset->subsys[i];
979 }
980 }
981
982 key = css_set_hash(template);
983 hash_for_each_possible(css_set_table, cset, hlist, key) {
984 if (!compare_css_sets(cset, old_cset, cgrp, template))
985 continue;
986
987 /* This css_set matches what we need */
988 return cset;
989 }
990
991 /* No existing cgroup group matched */
992 return NULL;
993 }
994
995 static void free_cgrp_cset_links(struct list_head *links_to_free)
996 {
997 struct cgrp_cset_link *link, *tmp_link;
998
999 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1000 list_del(&link->cset_link);
1001 kfree(link);
1002 }
1003 }
1004
1005 /**
1006 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1007 * @count: the number of links to allocate
1008 * @tmp_links: list_head the allocated links are put on
1009 *
1010 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1011 * through ->cset_link. Returns 0 on success or -errno.
1012 */
1013 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1014 {
1015 struct cgrp_cset_link *link;
1016 int i;
1017
1018 INIT_LIST_HEAD(tmp_links);
1019
1020 for (i = 0; i < count; i++) {
1021 link = kzalloc(sizeof(*link), GFP_KERNEL);
1022 if (!link) {
1023 free_cgrp_cset_links(tmp_links);
1024 return -ENOMEM;
1025 }
1026 list_add(&link->cset_link, tmp_links);
1027 }
1028 return 0;
1029 }
1030
1031 /**
1032 * link_css_set - a helper function to link a css_set to a cgroup
1033 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1034 * @cset: the css_set to be linked
1035 * @cgrp: the destination cgroup
1036 */
1037 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1038 struct cgroup *cgrp)
1039 {
1040 struct cgrp_cset_link *link;
1041
1042 BUG_ON(list_empty(tmp_links));
1043
1044 if (cgroup_on_dfl(cgrp))
1045 cset->dfl_cgrp = cgrp;
1046
1047 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1048 link->cset = cset;
1049 link->cgrp = cgrp;
1050
1051 /*
1052 * Always add links to the tail of the lists so that the lists are
1053 * in choronological order.
1054 */
1055 list_move_tail(&link->cset_link, &cgrp->cset_links);
1056 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1057
1058 if (cgroup_parent(cgrp))
1059 cgroup_get_live(cgrp);
1060 }
1061
1062 /**
1063 * find_css_set - return a new css_set with one cgroup updated
1064 * @old_cset: the baseline css_set
1065 * @cgrp: the cgroup to be updated
1066 *
1067 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1068 * substituted into the appropriate hierarchy.
1069 */
1070 static struct css_set *find_css_set(struct css_set *old_cset,
1071 struct cgroup *cgrp)
1072 {
1073 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1074 struct css_set *cset;
1075 struct list_head tmp_links;
1076 struct cgrp_cset_link *link;
1077 struct cgroup_subsys *ss;
1078 unsigned long key;
1079 int ssid;
1080
1081 lockdep_assert_held(&cgroup_mutex);
1082
1083 /* First see if we already have a cgroup group that matches
1084 * the desired set */
1085 spin_lock_irq(&css_set_lock);
1086 cset = find_existing_css_set(old_cset, cgrp, template);
1087 if (cset)
1088 get_css_set(cset);
1089 spin_unlock_irq(&css_set_lock);
1090
1091 if (cset)
1092 return cset;
1093
1094 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1095 if (!cset)
1096 return NULL;
1097
1098 /* Allocate all the cgrp_cset_link objects that we'll need */
1099 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1100 kfree(cset);
1101 return NULL;
1102 }
1103
1104 refcount_set(&cset->refcount, 1);
1105 cset->dom_cset = cset;
1106 INIT_LIST_HEAD(&cset->tasks);
1107 INIT_LIST_HEAD(&cset->mg_tasks);
1108 INIT_LIST_HEAD(&cset->task_iters);
1109 INIT_LIST_HEAD(&cset->threaded_csets);
1110 INIT_HLIST_NODE(&cset->hlist);
1111 INIT_LIST_HEAD(&cset->cgrp_links);
1112 INIT_LIST_HEAD(&cset->mg_preload_node);
1113 INIT_LIST_HEAD(&cset->mg_node);
1114
1115 /* Copy the set of subsystem state objects generated in
1116 * find_existing_css_set() */
1117 memcpy(cset->subsys, template, sizeof(cset->subsys));
1118
1119 spin_lock_irq(&css_set_lock);
1120 /* Add reference counts and links from the new css_set. */
1121 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1122 struct cgroup *c = link->cgrp;
1123
1124 if (c->root == cgrp->root)
1125 c = cgrp;
1126 link_css_set(&tmp_links, cset, c);
1127 }
1128
1129 BUG_ON(!list_empty(&tmp_links));
1130
1131 css_set_count++;
1132
1133 /* Add @cset to the hash table */
1134 key = css_set_hash(cset->subsys);
1135 hash_add(css_set_table, &cset->hlist, key);
1136
1137 for_each_subsys(ss, ssid) {
1138 struct cgroup_subsys_state *css = cset->subsys[ssid];
1139
1140 list_add_tail(&cset->e_cset_node[ssid],
1141 &css->cgroup->e_csets[ssid]);
1142 css_get(css);
1143 }
1144
1145 spin_unlock_irq(&css_set_lock);
1146
1147 /*
1148 * If @cset should be threaded, look up the matching dom_cset and
1149 * link them up. We first fully initialize @cset then look for the
1150 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1151 * to stay empty until we return.
1152 */
1153 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1154 struct css_set *dcset;
1155
1156 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1157 if (!dcset) {
1158 put_css_set(cset);
1159 return NULL;
1160 }
1161
1162 spin_lock_irq(&css_set_lock);
1163 cset->dom_cset = dcset;
1164 list_add_tail(&cset->threaded_csets_node,
1165 &dcset->threaded_csets);
1166 spin_unlock_irq(&css_set_lock);
1167 }
1168
1169 return cset;
1170 }
1171
1172 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1173 {
1174 struct cgroup *root_cgrp = kf_root->kn->priv;
1175
1176 return root_cgrp->root;
1177 }
1178
1179 static int cgroup_init_root_id(struct cgroup_root *root)
1180 {
1181 int id;
1182
1183 lockdep_assert_held(&cgroup_mutex);
1184
1185 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1186 if (id < 0)
1187 return id;
1188
1189 root->hierarchy_id = id;
1190 return 0;
1191 }
1192
1193 static void cgroup_exit_root_id(struct cgroup_root *root)
1194 {
1195 lockdep_assert_held(&cgroup_mutex);
1196
1197 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1198 }
1199
1200 void cgroup_free_root(struct cgroup_root *root)
1201 {
1202 if (root) {
1203 idr_destroy(&root->cgroup_idr);
1204 kfree(root);
1205 }
1206 }
1207
1208 static void cgroup_destroy_root(struct cgroup_root *root)
1209 {
1210 struct cgroup *cgrp = &root->cgrp;
1211 struct cgrp_cset_link *link, *tmp_link;
1212
1213 trace_cgroup_destroy_root(root);
1214
1215 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1216
1217 BUG_ON(atomic_read(&root->nr_cgrps));
1218 BUG_ON(!list_empty(&cgrp->self.children));
1219
1220 /* Rebind all subsystems back to the default hierarchy */
1221 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1222
1223 /*
1224 * Release all the links from cset_links to this hierarchy's
1225 * root cgroup
1226 */
1227 spin_lock_irq(&css_set_lock);
1228
1229 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1230 list_del(&link->cset_link);
1231 list_del(&link->cgrp_link);
1232 kfree(link);
1233 }
1234
1235 spin_unlock_irq(&css_set_lock);
1236
1237 if (!list_empty(&root->root_list)) {
1238 list_del(&root->root_list);
1239 cgroup_root_count--;
1240 }
1241
1242 cgroup_exit_root_id(root);
1243
1244 mutex_unlock(&cgroup_mutex);
1245
1246 kernfs_destroy_root(root->kf_root);
1247 cgroup_free_root(root);
1248 }
1249
1250 /*
1251 * look up cgroup associated with current task's cgroup namespace on the
1252 * specified hierarchy
1253 */
1254 static struct cgroup *
1255 current_cgns_cgroup_from_root(struct cgroup_root *root)
1256 {
1257 struct cgroup *res = NULL;
1258 struct css_set *cset;
1259
1260 lockdep_assert_held(&css_set_lock);
1261
1262 rcu_read_lock();
1263
1264 cset = current->nsproxy->cgroup_ns->root_cset;
1265 if (cset == &init_css_set) {
1266 res = &root->cgrp;
1267 } else {
1268 struct cgrp_cset_link *link;
1269
1270 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1271 struct cgroup *c = link->cgrp;
1272
1273 if (c->root == root) {
1274 res = c;
1275 break;
1276 }
1277 }
1278 }
1279 rcu_read_unlock();
1280
1281 BUG_ON(!res);
1282 return res;
1283 }
1284
1285 /* look up cgroup associated with given css_set on the specified hierarchy */
1286 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1287 struct cgroup_root *root)
1288 {
1289 struct cgroup *res = NULL;
1290
1291 lockdep_assert_held(&cgroup_mutex);
1292 lockdep_assert_held(&css_set_lock);
1293
1294 if (cset == &init_css_set) {
1295 res = &root->cgrp;
1296 } else if (root == &cgrp_dfl_root) {
1297 res = cset->dfl_cgrp;
1298 } else {
1299 struct cgrp_cset_link *link;
1300
1301 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1302 struct cgroup *c = link->cgrp;
1303
1304 if (c->root == root) {
1305 res = c;
1306 break;
1307 }
1308 }
1309 }
1310
1311 BUG_ON(!res);
1312 return res;
1313 }
1314
1315 /*
1316 * Return the cgroup for "task" from the given hierarchy. Must be
1317 * called with cgroup_mutex and css_set_lock held.
1318 */
1319 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1320 struct cgroup_root *root)
1321 {
1322 /*
1323 * No need to lock the task - since we hold cgroup_mutex the
1324 * task can't change groups, so the only thing that can happen
1325 * is that it exits and its css is set back to init_css_set.
1326 */
1327 return cset_cgroup_from_root(task_css_set(task), root);
1328 }
1329
1330 /*
1331 * A task must hold cgroup_mutex to modify cgroups.
1332 *
1333 * Any task can increment and decrement the count field without lock.
1334 * So in general, code holding cgroup_mutex can't rely on the count
1335 * field not changing. However, if the count goes to zero, then only
1336 * cgroup_attach_task() can increment it again. Because a count of zero
1337 * means that no tasks are currently attached, therefore there is no
1338 * way a task attached to that cgroup can fork (the other way to
1339 * increment the count). So code holding cgroup_mutex can safely
1340 * assume that if the count is zero, it will stay zero. Similarly, if
1341 * a task holds cgroup_mutex on a cgroup with zero count, it
1342 * knows that the cgroup won't be removed, as cgroup_rmdir()
1343 * needs that mutex.
1344 *
1345 * A cgroup can only be deleted if both its 'count' of using tasks
1346 * is zero, and its list of 'children' cgroups is empty. Since all
1347 * tasks in the system use _some_ cgroup, and since there is always at
1348 * least one task in the system (init, pid == 1), therefore, root cgroup
1349 * always has either children cgroups and/or using tasks. So we don't
1350 * need a special hack to ensure that root cgroup cannot be deleted.
1351 *
1352 * P.S. One more locking exception. RCU is used to guard the
1353 * update of a tasks cgroup pointer by cgroup_attach_task()
1354 */
1355
1356 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1357
1358 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1359 char *buf)
1360 {
1361 struct cgroup_subsys *ss = cft->ss;
1362
1363 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1364 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1365 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1366 cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1367 cft->name);
1368 else
1369 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1370 return buf;
1371 }
1372
1373 /**
1374 * cgroup_file_mode - deduce file mode of a control file
1375 * @cft: the control file in question
1376 *
1377 * S_IRUGO for read, S_IWUSR for write.
1378 */
1379 static umode_t cgroup_file_mode(const struct cftype *cft)
1380 {
1381 umode_t mode = 0;
1382
1383 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1384 mode |= S_IRUGO;
1385
1386 if (cft->write_u64 || cft->write_s64 || cft->write) {
1387 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1388 mode |= S_IWUGO;
1389 else
1390 mode |= S_IWUSR;
1391 }
1392
1393 return mode;
1394 }
1395
1396 /**
1397 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1398 * @subtree_control: the new subtree_control mask to consider
1399 * @this_ss_mask: available subsystems
1400 *
1401 * On the default hierarchy, a subsystem may request other subsystems to be
1402 * enabled together through its ->depends_on mask. In such cases, more
1403 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1404 *
1405 * This function calculates which subsystems need to be enabled if
1406 * @subtree_control is to be applied while restricted to @this_ss_mask.
1407 */
1408 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1409 {
1410 u16 cur_ss_mask = subtree_control;
1411 struct cgroup_subsys *ss;
1412 int ssid;
1413
1414 lockdep_assert_held(&cgroup_mutex);
1415
1416 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1417
1418 while (true) {
1419 u16 new_ss_mask = cur_ss_mask;
1420
1421 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1422 new_ss_mask |= ss->depends_on;
1423 } while_each_subsys_mask();
1424
1425 /*
1426 * Mask out subsystems which aren't available. This can
1427 * happen only if some depended-upon subsystems were bound
1428 * to non-default hierarchies.
1429 */
1430 new_ss_mask &= this_ss_mask;
1431
1432 if (new_ss_mask == cur_ss_mask)
1433 break;
1434 cur_ss_mask = new_ss_mask;
1435 }
1436
1437 return cur_ss_mask;
1438 }
1439
1440 /**
1441 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1442 * @kn: the kernfs_node being serviced
1443 *
1444 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1445 * the method finishes if locking succeeded. Note that once this function
1446 * returns the cgroup returned by cgroup_kn_lock_live() may become
1447 * inaccessible any time. If the caller intends to continue to access the
1448 * cgroup, it should pin it before invoking this function.
1449 */
1450 void cgroup_kn_unlock(struct kernfs_node *kn)
1451 {
1452 struct cgroup *cgrp;
1453
1454 if (kernfs_type(kn) == KERNFS_DIR)
1455 cgrp = kn->priv;
1456 else
1457 cgrp = kn->parent->priv;
1458
1459 mutex_unlock(&cgroup_mutex);
1460
1461 kernfs_unbreak_active_protection(kn);
1462 cgroup_put(cgrp);
1463 }
1464
1465 /**
1466 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1467 * @kn: the kernfs_node being serviced
1468 * @drain_offline: perform offline draining on the cgroup
1469 *
1470 * This helper is to be used by a cgroup kernfs method currently servicing
1471 * @kn. It breaks the active protection, performs cgroup locking and
1472 * verifies that the associated cgroup is alive. Returns the cgroup if
1473 * alive; otherwise, %NULL. A successful return should be undone by a
1474 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1475 * cgroup is drained of offlining csses before return.
1476 *
1477 * Any cgroup kernfs method implementation which requires locking the
1478 * associated cgroup should use this helper. It avoids nesting cgroup
1479 * locking under kernfs active protection and allows all kernfs operations
1480 * including self-removal.
1481 */
1482 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1483 {
1484 struct cgroup *cgrp;
1485
1486 if (kernfs_type(kn) == KERNFS_DIR)
1487 cgrp = kn->priv;
1488 else
1489 cgrp = kn->parent->priv;
1490
1491 /*
1492 * We're gonna grab cgroup_mutex which nests outside kernfs
1493 * active_ref. cgroup liveliness check alone provides enough
1494 * protection against removal. Ensure @cgrp stays accessible and
1495 * break the active_ref protection.
1496 */
1497 if (!cgroup_tryget(cgrp))
1498 return NULL;
1499 kernfs_break_active_protection(kn);
1500
1501 if (drain_offline)
1502 cgroup_lock_and_drain_offline(cgrp);
1503 else
1504 mutex_lock(&cgroup_mutex);
1505
1506 if (!cgroup_is_dead(cgrp))
1507 return cgrp;
1508
1509 cgroup_kn_unlock(kn);
1510 return NULL;
1511 }
1512
1513 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1514 {
1515 char name[CGROUP_FILE_NAME_MAX];
1516
1517 lockdep_assert_held(&cgroup_mutex);
1518
1519 if (cft->file_offset) {
1520 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1521 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1522
1523 spin_lock_irq(&cgroup_file_kn_lock);
1524 cfile->kn = NULL;
1525 spin_unlock_irq(&cgroup_file_kn_lock);
1526 }
1527
1528 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1529 }
1530
1531 /**
1532 * css_clear_dir - remove subsys files in a cgroup directory
1533 * @css: taget css
1534 */
1535 static void css_clear_dir(struct cgroup_subsys_state *css)
1536 {
1537 struct cgroup *cgrp = css->cgroup;
1538 struct cftype *cfts;
1539
1540 if (!(css->flags & CSS_VISIBLE))
1541 return;
1542
1543 css->flags &= ~CSS_VISIBLE;
1544
1545 list_for_each_entry(cfts, &css->ss->cfts, node)
1546 cgroup_addrm_files(css, cgrp, cfts, false);
1547 }
1548
1549 /**
1550 * css_populate_dir - create subsys files in a cgroup directory
1551 * @css: target css
1552 *
1553 * On failure, no file is added.
1554 */
1555 static int css_populate_dir(struct cgroup_subsys_state *css)
1556 {
1557 struct cgroup *cgrp = css->cgroup;
1558 struct cftype *cfts, *failed_cfts;
1559 int ret;
1560
1561 if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
1562 return 0;
1563
1564 if (!css->ss) {
1565 if (cgroup_on_dfl(cgrp))
1566 cfts = cgroup_base_files;
1567 else
1568 cfts = cgroup1_base_files;
1569
1570 return cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1571 }
1572
1573 list_for_each_entry(cfts, &css->ss->cfts, node) {
1574 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1575 if (ret < 0) {
1576 failed_cfts = cfts;
1577 goto err;
1578 }
1579 }
1580
1581 css->flags |= CSS_VISIBLE;
1582
1583 return 0;
1584 err:
1585 list_for_each_entry(cfts, &css->ss->cfts, node) {
1586 if (cfts == failed_cfts)
1587 break;
1588 cgroup_addrm_files(css, cgrp, cfts, false);
1589 }
1590 return ret;
1591 }
1592
1593 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1594 {
1595 struct cgroup *dcgrp = &dst_root->cgrp;
1596 struct cgroup_subsys *ss;
1597 int ssid, i, ret;
1598
1599 lockdep_assert_held(&cgroup_mutex);
1600
1601 do_each_subsys_mask(ss, ssid, ss_mask) {
1602 /*
1603 * If @ss has non-root csses attached to it, can't move.
1604 * If @ss is an implicit controller, it is exempt from this
1605 * rule and can be stolen.
1606 */
1607 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1608 !ss->implicit_on_dfl)
1609 return -EBUSY;
1610
1611 /* can't move between two non-dummy roots either */
1612 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1613 return -EBUSY;
1614 } while_each_subsys_mask();
1615
1616 do_each_subsys_mask(ss, ssid, ss_mask) {
1617 struct cgroup_root *src_root = ss->root;
1618 struct cgroup *scgrp = &src_root->cgrp;
1619 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1620 struct css_set *cset;
1621
1622 WARN_ON(!css || cgroup_css(dcgrp, ss));
1623
1624 /* disable from the source */
1625 src_root->subsys_mask &= ~(1 << ssid);
1626 WARN_ON(cgroup_apply_control(scgrp));
1627 cgroup_finalize_control(scgrp, 0);
1628
1629 /* rebind */
1630 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1631 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1632 ss->root = dst_root;
1633 css->cgroup = dcgrp;
1634
1635 spin_lock_irq(&css_set_lock);
1636 hash_for_each(css_set_table, i, cset, hlist)
1637 list_move_tail(&cset->e_cset_node[ss->id],
1638 &dcgrp->e_csets[ss->id]);
1639 spin_unlock_irq(&css_set_lock);
1640
1641 /* default hierarchy doesn't enable controllers by default */
1642 dst_root->subsys_mask |= 1 << ssid;
1643 if (dst_root == &cgrp_dfl_root) {
1644 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1645 } else {
1646 dcgrp->subtree_control |= 1 << ssid;
1647 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1648 }
1649
1650 ret = cgroup_apply_control(dcgrp);
1651 if (ret)
1652 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1653 ss->name, ret);
1654
1655 if (ss->bind)
1656 ss->bind(css);
1657 } while_each_subsys_mask();
1658
1659 kernfs_activate(dcgrp->kn);
1660 return 0;
1661 }
1662
1663 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1664 struct kernfs_root *kf_root)
1665 {
1666 int len = 0;
1667 char *buf = NULL;
1668 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1669 struct cgroup *ns_cgroup;
1670
1671 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1672 if (!buf)
1673 return -ENOMEM;
1674
1675 spin_lock_irq(&css_set_lock);
1676 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1677 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1678 spin_unlock_irq(&css_set_lock);
1679
1680 if (len >= PATH_MAX)
1681 len = -ERANGE;
1682 else if (len > 0) {
1683 seq_escape(sf, buf, " \t\n\\");
1684 len = 0;
1685 }
1686 kfree(buf);
1687 return len;
1688 }
1689
1690 static int parse_cgroup_root_flags(char *data, unsigned int *root_flags)
1691 {
1692 char *token;
1693
1694 *root_flags = 0;
1695
1696 if (!data || *data == '\0')
1697 return 0;
1698
1699 while ((token = strsep(&data, ",")) != NULL) {
1700 if (!strcmp(token, "nsdelegate")) {
1701 *root_flags |= CGRP_ROOT_NS_DELEGATE;
1702 continue;
1703 }
1704
1705 pr_err("cgroup2: unknown option \"%s\"\n", token);
1706 return -EINVAL;
1707 }
1708
1709 return 0;
1710 }
1711
1712 static void apply_cgroup_root_flags(unsigned int root_flags)
1713 {
1714 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1715 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1716 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1717 else
1718 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1719 }
1720 }
1721
1722 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1723 {
1724 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1725 seq_puts(seq, ",nsdelegate");
1726 return 0;
1727 }
1728
1729 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1730 {
1731 unsigned int root_flags;
1732 int ret;
1733
1734 ret = parse_cgroup_root_flags(data, &root_flags);
1735 if (ret)
1736 return ret;
1737
1738 apply_cgroup_root_flags(root_flags);
1739 return 0;
1740 }
1741
1742 /*
1743 * To reduce the fork() overhead for systems that are not actually using
1744 * their cgroups capability, we don't maintain the lists running through
1745 * each css_set to its tasks until we see the list actually used - in other
1746 * words after the first mount.
1747 */
1748 static bool use_task_css_set_links __read_mostly;
1749
1750 static void cgroup_enable_task_cg_lists(void)
1751 {
1752 struct task_struct *p, *g;
1753
1754 spin_lock_irq(&css_set_lock);
1755
1756 if (use_task_css_set_links)
1757 goto out_unlock;
1758
1759 use_task_css_set_links = true;
1760
1761 /*
1762 * We need tasklist_lock because RCU is not safe against
1763 * while_each_thread(). Besides, a forking task that has passed
1764 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1765 * is not guaranteed to have its child immediately visible in the
1766 * tasklist if we walk through it with RCU.
1767 */
1768 read_lock(&tasklist_lock);
1769 do_each_thread(g, p) {
1770 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1771 task_css_set(p) != &init_css_set);
1772
1773 /*
1774 * We should check if the process is exiting, otherwise
1775 * it will race with cgroup_exit() in that the list
1776 * entry won't be deleted though the process has exited.
1777 * Do it while holding siglock so that we don't end up
1778 * racing against cgroup_exit().
1779 *
1780 * Interrupts were already disabled while acquiring
1781 * the css_set_lock, so we do not need to disable it
1782 * again when acquiring the sighand->siglock here.
1783 */
1784 spin_lock(&p->sighand->siglock);
1785 if (!(p->flags & PF_EXITING)) {
1786 struct css_set *cset = task_css_set(p);
1787
1788 if (!css_set_populated(cset))
1789 css_set_update_populated(cset, true);
1790 list_add_tail(&p->cg_list, &cset->tasks);
1791 get_css_set(cset);
1792 cset->nr_tasks++;
1793 }
1794 spin_unlock(&p->sighand->siglock);
1795 } while_each_thread(g, p);
1796 read_unlock(&tasklist_lock);
1797 out_unlock:
1798 spin_unlock_irq(&css_set_lock);
1799 }
1800
1801 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1802 {
1803 struct cgroup_subsys *ss;
1804 int ssid;
1805
1806 INIT_LIST_HEAD(&cgrp->self.sibling);
1807 INIT_LIST_HEAD(&cgrp->self.children);
1808 INIT_LIST_HEAD(&cgrp->cset_links);
1809 INIT_LIST_HEAD(&cgrp->pidlists);
1810 mutex_init(&cgrp->pidlist_mutex);
1811 cgrp->self.cgroup = cgrp;
1812 cgrp->self.flags |= CSS_ONLINE;
1813 cgrp->dom_cgrp = cgrp;
1814 cgrp->max_descendants = INT_MAX;
1815 cgrp->max_depth = INT_MAX;
1816
1817 for_each_subsys(ss, ssid)
1818 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1819
1820 init_waitqueue_head(&cgrp->offline_waitq);
1821 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
1822 }
1823
1824 void init_cgroup_root(struct cgroup_root *root, struct cgroup_sb_opts *opts)
1825 {
1826 struct cgroup *cgrp = &root->cgrp;
1827
1828 INIT_LIST_HEAD(&root->root_list);
1829 atomic_set(&root->nr_cgrps, 1);
1830 cgrp->root = root;
1831 init_cgroup_housekeeping(cgrp);
1832 idr_init(&root->cgroup_idr);
1833
1834 root->flags = opts->flags;
1835 if (opts->release_agent)
1836 strcpy(root->release_agent_path, opts->release_agent);
1837 if (opts->name)
1838 strcpy(root->name, opts->name);
1839 if (opts->cpuset_clone_children)
1840 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1841 }
1842
1843 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask, int ref_flags)
1844 {
1845 LIST_HEAD(tmp_links);
1846 struct cgroup *root_cgrp = &root->cgrp;
1847 struct kernfs_syscall_ops *kf_sops;
1848 struct css_set *cset;
1849 int i, ret;
1850
1851 lockdep_assert_held(&cgroup_mutex);
1852
1853 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1854 if (ret < 0)
1855 goto out;
1856 root_cgrp->id = ret;
1857 root_cgrp->ancestor_ids[0] = ret;
1858
1859 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
1860 ref_flags, GFP_KERNEL);
1861 if (ret)
1862 goto out;
1863
1864 /*
1865 * We're accessing css_set_count without locking css_set_lock here,
1866 * but that's OK - it can only be increased by someone holding
1867 * cgroup_lock, and that's us. Later rebinding may disable
1868 * controllers on the default hierarchy and thus create new csets,
1869 * which can't be more than the existing ones. Allocate 2x.
1870 */
1871 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
1872 if (ret)
1873 goto cancel_ref;
1874
1875 ret = cgroup_init_root_id(root);
1876 if (ret)
1877 goto cancel_ref;
1878
1879 kf_sops = root == &cgrp_dfl_root ?
1880 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
1881
1882 root->kf_root = kernfs_create_root(kf_sops,
1883 KERNFS_ROOT_CREATE_DEACTIVATED |
1884 KERNFS_ROOT_SUPPORT_EXPORTOP,
1885 root_cgrp);
1886 if (IS_ERR(root->kf_root)) {
1887 ret = PTR_ERR(root->kf_root);
1888 goto exit_root_id;
1889 }
1890 root_cgrp->kn = root->kf_root->kn;
1891
1892 ret = css_populate_dir(&root_cgrp->self);
1893 if (ret)
1894 goto destroy_root;
1895
1896 ret = rebind_subsystems(root, ss_mask);
1897 if (ret)
1898 goto destroy_root;
1899
1900 trace_cgroup_setup_root(root);
1901
1902 /*
1903 * There must be no failure case after here, since rebinding takes
1904 * care of subsystems' refcounts, which are explicitly dropped in
1905 * the failure exit path.
1906 */
1907 list_add(&root->root_list, &cgroup_roots);
1908 cgroup_root_count++;
1909
1910 /*
1911 * Link the root cgroup in this hierarchy into all the css_set
1912 * objects.
1913 */
1914 spin_lock_irq(&css_set_lock);
1915 hash_for_each(css_set_table, i, cset, hlist) {
1916 link_css_set(&tmp_links, cset, root_cgrp);
1917 if (css_set_populated(cset))
1918 cgroup_update_populated(root_cgrp, true);
1919 }
1920 spin_unlock_irq(&css_set_lock);
1921
1922 BUG_ON(!list_empty(&root_cgrp->self.children));
1923 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1924
1925 kernfs_activate(root_cgrp->kn);
1926 ret = 0;
1927 goto out;
1928
1929 destroy_root:
1930 kernfs_destroy_root(root->kf_root);
1931 root->kf_root = NULL;
1932 exit_root_id:
1933 cgroup_exit_root_id(root);
1934 cancel_ref:
1935 percpu_ref_exit(&root_cgrp->self.refcnt);
1936 out:
1937 free_cgrp_cset_links(&tmp_links);
1938 return ret;
1939 }
1940
1941 struct dentry *cgroup_do_mount(struct file_system_type *fs_type, int flags,
1942 struct cgroup_root *root, unsigned long magic,
1943 struct cgroup_namespace *ns)
1944 {
1945 struct dentry *dentry;
1946 bool new_sb = false;
1947
1948 dentry = kernfs_mount(fs_type, flags, root->kf_root, magic, &new_sb);
1949
1950 /*
1951 * In non-init cgroup namespace, instead of root cgroup's dentry,
1952 * we return the dentry corresponding to the cgroupns->root_cgrp.
1953 */
1954 if (!IS_ERR(dentry) && ns != &init_cgroup_ns) {
1955 struct dentry *nsdentry;
1956 struct super_block *sb = dentry->d_sb;
1957 struct cgroup *cgrp;
1958
1959 mutex_lock(&cgroup_mutex);
1960 spin_lock_irq(&css_set_lock);
1961
1962 cgrp = cset_cgroup_from_root(ns->root_cset, root);
1963
1964 spin_unlock_irq(&css_set_lock);
1965 mutex_unlock(&cgroup_mutex);
1966
1967 nsdentry = kernfs_node_dentry(cgrp->kn, sb);
1968 dput(dentry);
1969 if (IS_ERR(nsdentry))
1970 deactivate_locked_super(sb);
1971 dentry = nsdentry;
1972 }
1973
1974 if (!new_sb)
1975 cgroup_put(&root->cgrp);
1976
1977 return dentry;
1978 }
1979
1980 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1981 int flags, const char *unused_dev_name,
1982 void *data)
1983 {
1984 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
1985 struct dentry *dentry;
1986 int ret;
1987
1988 get_cgroup_ns(ns);
1989
1990 /* Check if the caller has permission to mount. */
1991 if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) {
1992 put_cgroup_ns(ns);
1993 return ERR_PTR(-EPERM);
1994 }
1995
1996 /*
1997 * The first time anyone tries to mount a cgroup, enable the list
1998 * linking each css_set to its tasks and fix up all existing tasks.
1999 */
2000 if (!use_task_css_set_links)
2001 cgroup_enable_task_cg_lists();
2002
2003 if (fs_type == &cgroup2_fs_type) {
2004 unsigned int root_flags;
2005
2006 ret = parse_cgroup_root_flags(data, &root_flags);
2007 if (ret) {
2008 put_cgroup_ns(ns);
2009 return ERR_PTR(ret);
2010 }
2011
2012 cgrp_dfl_visible = true;
2013 cgroup_get_live(&cgrp_dfl_root.cgrp);
2014
2015 dentry = cgroup_do_mount(&cgroup2_fs_type, flags, &cgrp_dfl_root,
2016 CGROUP2_SUPER_MAGIC, ns);
2017 if (!IS_ERR(dentry))
2018 apply_cgroup_root_flags(root_flags);
2019 } else {
2020 dentry = cgroup1_mount(&cgroup_fs_type, flags, data,
2021 CGROUP_SUPER_MAGIC, ns);
2022 }
2023
2024 put_cgroup_ns(ns);
2025 return dentry;
2026 }
2027
2028 static void cgroup_kill_sb(struct super_block *sb)
2029 {
2030 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2031 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2032
2033 /*
2034 * If @root doesn't have any mounts or children, start killing it.
2035 * This prevents new mounts by disabling percpu_ref_tryget_live().
2036 * cgroup_mount() may wait for @root's release.
2037 *
2038 * And don't kill the default root.
2039 */
2040 if (!list_empty(&root->cgrp.self.children) ||
2041 root == &cgrp_dfl_root)
2042 cgroup_put(&root->cgrp);
2043 else
2044 percpu_ref_kill(&root->cgrp.self.refcnt);
2045
2046 kernfs_kill_sb(sb);
2047 }
2048
2049 struct file_system_type cgroup_fs_type = {
2050 .name = "cgroup",
2051 .mount = cgroup_mount,
2052 .kill_sb = cgroup_kill_sb,
2053 .fs_flags = FS_USERNS_MOUNT,
2054 };
2055
2056 static struct file_system_type cgroup2_fs_type = {
2057 .name = "cgroup2",
2058 .mount = cgroup_mount,
2059 .kill_sb = cgroup_kill_sb,
2060 .fs_flags = FS_USERNS_MOUNT,
2061 };
2062
2063 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2064 struct cgroup_namespace *ns)
2065 {
2066 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2067
2068 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2069 }
2070
2071 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2072 struct cgroup_namespace *ns)
2073 {
2074 int ret;
2075
2076 mutex_lock(&cgroup_mutex);
2077 spin_lock_irq(&css_set_lock);
2078
2079 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2080
2081 spin_unlock_irq(&css_set_lock);
2082 mutex_unlock(&cgroup_mutex);
2083
2084 return ret;
2085 }
2086 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2087
2088 /**
2089 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2090 * @task: target task
2091 * @buf: the buffer to write the path into
2092 * @buflen: the length of the buffer
2093 *
2094 * Determine @task's cgroup on the first (the one with the lowest non-zero
2095 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2096 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2097 * cgroup controller callbacks.
2098 *
2099 * Return value is the same as kernfs_path().
2100 */
2101 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2102 {
2103 struct cgroup_root *root;
2104 struct cgroup *cgrp;
2105 int hierarchy_id = 1;
2106 int ret;
2107
2108 mutex_lock(&cgroup_mutex);
2109 spin_lock_irq(&css_set_lock);
2110
2111 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2112
2113 if (root) {
2114 cgrp = task_cgroup_from_root(task, root);
2115 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2116 } else {
2117 /* if no hierarchy exists, everyone is in "/" */
2118 ret = strlcpy(buf, "/", buflen);
2119 }
2120
2121 spin_unlock_irq(&css_set_lock);
2122 mutex_unlock(&cgroup_mutex);
2123 return ret;
2124 }
2125 EXPORT_SYMBOL_GPL(task_cgroup_path);
2126
2127 /**
2128 * cgroup_migrate_add_task - add a migration target task to a migration context
2129 * @task: target task
2130 * @mgctx: target migration context
2131 *
2132 * Add @task, which is a migration target, to @mgctx->tset. This function
2133 * becomes noop if @task doesn't need to be migrated. @task's css_set
2134 * should have been added as a migration source and @task->cg_list will be
2135 * moved from the css_set's tasks list to mg_tasks one.
2136 */
2137 static void cgroup_migrate_add_task(struct task_struct *task,
2138 struct cgroup_mgctx *mgctx)
2139 {
2140 struct css_set *cset;
2141
2142 lockdep_assert_held(&css_set_lock);
2143
2144 /* @task either already exited or can't exit until the end */
2145 if (task->flags & PF_EXITING)
2146 return;
2147
2148 /* leave @task alone if post_fork() hasn't linked it yet */
2149 if (list_empty(&task->cg_list))
2150 return;
2151
2152 cset = task_css_set(task);
2153 if (!cset->mg_src_cgrp)
2154 return;
2155
2156 mgctx->tset.nr_tasks++;
2157
2158 list_move_tail(&task->cg_list, &cset->mg_tasks);
2159 if (list_empty(&cset->mg_node))
2160 list_add_tail(&cset->mg_node,
2161 &mgctx->tset.src_csets);
2162 if (list_empty(&cset->mg_dst_cset->mg_node))
2163 list_add_tail(&cset->mg_dst_cset->mg_node,
2164 &mgctx->tset.dst_csets);
2165 }
2166
2167 /**
2168 * cgroup_taskset_first - reset taskset and return the first task
2169 * @tset: taskset of interest
2170 * @dst_cssp: output variable for the destination css
2171 *
2172 * @tset iteration is initialized and the first task is returned.
2173 */
2174 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2175 struct cgroup_subsys_state **dst_cssp)
2176 {
2177 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2178 tset->cur_task = NULL;
2179
2180 return cgroup_taskset_next(tset, dst_cssp);
2181 }
2182
2183 /**
2184 * cgroup_taskset_next - iterate to the next task in taskset
2185 * @tset: taskset of interest
2186 * @dst_cssp: output variable for the destination css
2187 *
2188 * Return the next task in @tset. Iteration must have been initialized
2189 * with cgroup_taskset_first().
2190 */
2191 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2192 struct cgroup_subsys_state **dst_cssp)
2193 {
2194 struct css_set *cset = tset->cur_cset;
2195 struct task_struct *task = tset->cur_task;
2196
2197 while (&cset->mg_node != tset->csets) {
2198 if (!task)
2199 task = list_first_entry(&cset->mg_tasks,
2200 struct task_struct, cg_list);
2201 else
2202 task = list_next_entry(task, cg_list);
2203
2204 if (&task->cg_list != &cset->mg_tasks) {
2205 tset->cur_cset = cset;
2206 tset->cur_task = task;
2207
2208 /*
2209 * This function may be called both before and
2210 * after cgroup_taskset_migrate(). The two cases
2211 * can be distinguished by looking at whether @cset
2212 * has its ->mg_dst_cset set.
2213 */
2214 if (cset->mg_dst_cset)
2215 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2216 else
2217 *dst_cssp = cset->subsys[tset->ssid];
2218
2219 return task;
2220 }
2221
2222 cset = list_next_entry(cset, mg_node);
2223 task = NULL;
2224 }
2225
2226 return NULL;
2227 }
2228
2229 /**
2230 * cgroup_taskset_migrate - migrate a taskset
2231 * @mgctx: migration context
2232 *
2233 * Migrate tasks in @mgctx as setup by migration preparation functions.
2234 * This function fails iff one of the ->can_attach callbacks fails and
2235 * guarantees that either all or none of the tasks in @mgctx are migrated.
2236 * @mgctx is consumed regardless of success.
2237 */
2238 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2239 {
2240 struct cgroup_taskset *tset = &mgctx->tset;
2241 struct cgroup_subsys *ss;
2242 struct task_struct *task, *tmp_task;
2243 struct css_set *cset, *tmp_cset;
2244 int ssid, failed_ssid, ret;
2245
2246 /* check that we can legitimately attach to the cgroup */
2247 if (tset->nr_tasks) {
2248 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2249 if (ss->can_attach) {
2250 tset->ssid = ssid;
2251 ret = ss->can_attach(tset);
2252 if (ret) {
2253 failed_ssid = ssid;
2254 goto out_cancel_attach;
2255 }
2256 }
2257 } while_each_subsys_mask();
2258 }
2259
2260 /*
2261 * Now that we're guaranteed success, proceed to move all tasks to
2262 * the new cgroup. There are no failure cases after here, so this
2263 * is the commit point.
2264 */
2265 spin_lock_irq(&css_set_lock);
2266 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2267 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2268 struct css_set *from_cset = task_css_set(task);
2269 struct css_set *to_cset = cset->mg_dst_cset;
2270
2271 get_css_set(to_cset);
2272 to_cset->nr_tasks++;
2273 css_set_move_task(task, from_cset, to_cset, true);
2274 put_css_set_locked(from_cset);
2275 from_cset->nr_tasks--;
2276 }
2277 }
2278 spin_unlock_irq(&css_set_lock);
2279
2280 /*
2281 * Migration is committed, all target tasks are now on dst_csets.
2282 * Nothing is sensitive to fork() after this point. Notify
2283 * controllers that migration is complete.
2284 */
2285 tset->csets = &tset->dst_csets;
2286
2287 if (tset->nr_tasks) {
2288 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2289 if (ss->attach) {
2290 tset->ssid = ssid;
2291 ss->attach(tset);
2292 }
2293 } while_each_subsys_mask();
2294 }
2295
2296 ret = 0;
2297 goto out_release_tset;
2298
2299 out_cancel_attach:
2300 if (tset->nr_tasks) {
2301 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2302 if (ssid == failed_ssid)
2303 break;
2304 if (ss->cancel_attach) {
2305 tset->ssid = ssid;
2306 ss->cancel_attach(tset);
2307 }
2308 } while_each_subsys_mask();
2309 }
2310 out_release_tset:
2311 spin_lock_irq(&css_set_lock);
2312 list_splice_init(&tset->dst_csets, &tset->src_csets);
2313 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2314 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2315 list_del_init(&cset->mg_node);
2316 }
2317 spin_unlock_irq(&css_set_lock);
2318
2319 /*
2320 * Re-initialize the cgroup_taskset structure in case it is reused
2321 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2322 * iteration.
2323 */
2324 tset->nr_tasks = 0;
2325 tset->csets = &tset->src_csets;
2326 return ret;
2327 }
2328
2329 /**
2330 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2331 * @dst_cgrp: destination cgroup to test
2332 *
2333 * On the default hierarchy, except for the mixable, (possible) thread root
2334 * and threaded cgroups, subtree_control must be zero for migration
2335 * destination cgroups with tasks so that child cgroups don't compete
2336 * against tasks.
2337 */
2338 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2339 {
2340 /* v1 doesn't have any restriction */
2341 if (!cgroup_on_dfl(dst_cgrp))
2342 return 0;
2343
2344 /* verify @dst_cgrp can host resources */
2345 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2346 return -EOPNOTSUPP;
2347
2348 /* mixables don't care */
2349 if (cgroup_is_mixable(dst_cgrp))
2350 return 0;
2351
2352 /*
2353 * If @dst_cgrp is already or can become a thread root or is
2354 * threaded, it doesn't matter.
2355 */
2356 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2357 return 0;
2358
2359 /* apply no-internal-process constraint */
2360 if (dst_cgrp->subtree_control)
2361 return -EBUSY;
2362
2363 return 0;
2364 }
2365
2366 /**
2367 * cgroup_migrate_finish - cleanup after attach
2368 * @mgctx: migration context
2369 *
2370 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2371 * those functions for details.
2372 */
2373 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2374 {
2375 LIST_HEAD(preloaded);
2376 struct css_set *cset, *tmp_cset;
2377
2378 lockdep_assert_held(&cgroup_mutex);
2379
2380 spin_lock_irq(&css_set_lock);
2381
2382 list_splice_tail_init(&mgctx->preloaded_src_csets, &preloaded);
2383 list_splice_tail_init(&mgctx->preloaded_dst_csets, &preloaded);
2384
2385 list_for_each_entry_safe(cset, tmp_cset, &preloaded, mg_preload_node) {
2386 cset->mg_src_cgrp = NULL;
2387 cset->mg_dst_cgrp = NULL;
2388 cset->mg_dst_cset = NULL;
2389 list_del_init(&cset->mg_preload_node);
2390 put_css_set_locked(cset);
2391 }
2392
2393 spin_unlock_irq(&css_set_lock);
2394 }
2395
2396 /**
2397 * cgroup_migrate_add_src - add a migration source css_set
2398 * @src_cset: the source css_set to add
2399 * @dst_cgrp: the destination cgroup
2400 * @mgctx: migration context
2401 *
2402 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2403 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2404 * up by cgroup_migrate_finish().
2405 *
2406 * This function may be called without holding cgroup_threadgroup_rwsem
2407 * even if the target is a process. Threads may be created and destroyed
2408 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2409 * into play and the preloaded css_sets are guaranteed to cover all
2410 * migrations.
2411 */
2412 void cgroup_migrate_add_src(struct css_set *src_cset,
2413 struct cgroup *dst_cgrp,
2414 struct cgroup_mgctx *mgctx)
2415 {
2416 struct cgroup *src_cgrp;
2417
2418 lockdep_assert_held(&cgroup_mutex);
2419 lockdep_assert_held(&css_set_lock);
2420
2421 /*
2422 * If ->dead, @src_set is associated with one or more dead cgroups
2423 * and doesn't contain any migratable tasks. Ignore it early so
2424 * that the rest of migration path doesn't get confused by it.
2425 */
2426 if (src_cset->dead)
2427 return;
2428
2429 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2430
2431 if (!list_empty(&src_cset->mg_preload_node))
2432 return;
2433
2434 WARN_ON(src_cset->mg_src_cgrp);
2435 WARN_ON(src_cset->mg_dst_cgrp);
2436 WARN_ON(!list_empty(&src_cset->mg_tasks));
2437 WARN_ON(!list_empty(&src_cset->mg_node));
2438
2439 src_cset->mg_src_cgrp = src_cgrp;
2440 src_cset->mg_dst_cgrp = dst_cgrp;
2441 get_css_set(src_cset);
2442 list_add_tail(&src_cset->mg_preload_node, &mgctx->preloaded_src_csets);
2443 }
2444
2445 /**
2446 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2447 * @mgctx: migration context
2448 *
2449 * Tasks are about to be moved and all the source css_sets have been
2450 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2451 * pins all destination css_sets, links each to its source, and append them
2452 * to @mgctx->preloaded_dst_csets.
2453 *
2454 * This function must be called after cgroup_migrate_add_src() has been
2455 * called on each migration source css_set. After migration is performed
2456 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2457 * @mgctx.
2458 */
2459 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2460 {
2461 struct css_set *src_cset, *tmp_cset;
2462
2463 lockdep_assert_held(&cgroup_mutex);
2464
2465 /* look up the dst cset for each src cset and link it to src */
2466 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2467 mg_preload_node) {
2468 struct css_set *dst_cset;
2469 struct cgroup_subsys *ss;
2470 int ssid;
2471
2472 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2473 if (!dst_cset)
2474 goto err;
2475
2476 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2477
2478 /*
2479 * If src cset equals dst, it's noop. Drop the src.
2480 * cgroup_migrate() will skip the cset too. Note that we
2481 * can't handle src == dst as some nodes are used by both.
2482 */
2483 if (src_cset == dst_cset) {
2484 src_cset->mg_src_cgrp = NULL;
2485 src_cset->mg_dst_cgrp = NULL;
2486 list_del_init(&src_cset->mg_preload_node);
2487 put_css_set(src_cset);
2488 put_css_set(dst_cset);
2489 continue;
2490 }
2491
2492 src_cset->mg_dst_cset = dst_cset;
2493
2494 if (list_empty(&dst_cset->mg_preload_node))
2495 list_add_tail(&dst_cset->mg_preload_node,
2496 &mgctx->preloaded_dst_csets);
2497 else
2498 put_css_set(dst_cset);
2499
2500 for_each_subsys(ss, ssid)
2501 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2502 mgctx->ss_mask |= 1 << ssid;
2503 }
2504
2505 return 0;
2506 err:
2507 cgroup_migrate_finish(mgctx);
2508 return -ENOMEM;
2509 }
2510
2511 /**
2512 * cgroup_migrate - migrate a process or task to a cgroup
2513 * @leader: the leader of the process or the task to migrate
2514 * @threadgroup: whether @leader points to the whole process or a single task
2515 * @mgctx: migration context
2516 *
2517 * Migrate a process or task denoted by @leader. If migrating a process,
2518 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2519 * responsible for invoking cgroup_migrate_add_src() and
2520 * cgroup_migrate_prepare_dst() on the targets before invoking this
2521 * function and following up with cgroup_migrate_finish().
2522 *
2523 * As long as a controller's ->can_attach() doesn't fail, this function is
2524 * guaranteed to succeed. This means that, excluding ->can_attach()
2525 * failure, when migrating multiple targets, the success or failure can be
2526 * decided for all targets by invoking group_migrate_prepare_dst() before
2527 * actually starting migrating.
2528 */
2529 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2530 struct cgroup_mgctx *mgctx)
2531 {
2532 struct task_struct *task;
2533
2534 /*
2535 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2536 * already PF_EXITING could be freed from underneath us unless we
2537 * take an rcu_read_lock.
2538 */
2539 spin_lock_irq(&css_set_lock);
2540 rcu_read_lock();
2541 task = leader;
2542 do {
2543 cgroup_migrate_add_task(task, mgctx);
2544 if (!threadgroup)
2545 break;
2546 } while_each_thread(leader, task);
2547 rcu_read_unlock();
2548 spin_unlock_irq(&css_set_lock);
2549
2550 return cgroup_migrate_execute(mgctx);
2551 }
2552
2553 /**
2554 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2555 * @dst_cgrp: the cgroup to attach to
2556 * @leader: the task or the leader of the threadgroup to be attached
2557 * @threadgroup: attach the whole threadgroup?
2558 *
2559 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2560 */
2561 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2562 bool threadgroup)
2563 {
2564 DEFINE_CGROUP_MGCTX(mgctx);
2565 struct task_struct *task;
2566 int ret;
2567
2568 ret = cgroup_migrate_vet_dst(dst_cgrp);
2569 if (ret)
2570 return ret;
2571
2572 /* look up all src csets */
2573 spin_lock_irq(&css_set_lock);
2574 rcu_read_lock();
2575 task = leader;
2576 do {
2577 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2578 if (!threadgroup)
2579 break;
2580 } while_each_thread(leader, task);
2581 rcu_read_unlock();
2582 spin_unlock_irq(&css_set_lock);
2583
2584 /* prepare dst csets and commit */
2585 ret = cgroup_migrate_prepare_dst(&mgctx);
2586 if (!ret)
2587 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2588
2589 cgroup_migrate_finish(&mgctx);
2590
2591 if (!ret)
2592 trace_cgroup_attach_task(dst_cgrp, leader, threadgroup);
2593
2594 return ret;
2595 }
2596
2597 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup)
2598 __acquires(&cgroup_threadgroup_rwsem)
2599 {
2600 struct task_struct *tsk;
2601 pid_t pid;
2602
2603 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2604 return ERR_PTR(-EINVAL);
2605
2606 percpu_down_write(&cgroup_threadgroup_rwsem);
2607
2608 rcu_read_lock();
2609 if (pid) {
2610 tsk = find_task_by_vpid(pid);
2611 if (!tsk) {
2612 tsk = ERR_PTR(-ESRCH);
2613 goto out_unlock_threadgroup;
2614 }
2615 } else {
2616 tsk = current;
2617 }
2618
2619 if (threadgroup)
2620 tsk = tsk->group_leader;
2621
2622 /*
2623 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2624 * If userland migrates such a kthread to a non-root cgroup, it can
2625 * become trapped in a cpuset, or RT kthread may be born in a
2626 * cgroup with no rt_runtime allocated. Just say no.
2627 */
2628 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2629 tsk = ERR_PTR(-EINVAL);
2630 goto out_unlock_threadgroup;
2631 }
2632
2633 get_task_struct(tsk);
2634 goto out_unlock_rcu;
2635
2636 out_unlock_threadgroup:
2637 percpu_up_write(&cgroup_threadgroup_rwsem);
2638 out_unlock_rcu:
2639 rcu_read_unlock();
2640 return tsk;
2641 }
2642
2643 void cgroup_procs_write_finish(struct task_struct *task)
2644 __releases(&cgroup_threadgroup_rwsem)
2645 {
2646 struct cgroup_subsys *ss;
2647 int ssid;
2648
2649 /* release reference from cgroup_procs_write_start() */
2650 put_task_struct(task);
2651
2652 percpu_up_write(&cgroup_threadgroup_rwsem);
2653 for_each_subsys(ss, ssid)
2654 if (ss->post_attach)
2655 ss->post_attach();
2656 }
2657
2658 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2659 {
2660 struct cgroup_subsys *ss;
2661 bool printed = false;
2662 int ssid;
2663
2664 do_each_subsys_mask(ss, ssid, ss_mask) {
2665 if (printed)
2666 seq_putc(seq, ' ');
2667 seq_printf(seq, "%s", ss->name);
2668 printed = true;
2669 } while_each_subsys_mask();
2670 if (printed)
2671 seq_putc(seq, '\n');
2672 }
2673
2674 /* show controllers which are enabled from the parent */
2675 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2676 {
2677 struct cgroup *cgrp = seq_css(seq)->cgroup;
2678
2679 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2680 return 0;
2681 }
2682
2683 /* show controllers which are enabled for a given cgroup's children */
2684 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2685 {
2686 struct cgroup *cgrp = seq_css(seq)->cgroup;
2687
2688 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2689 return 0;
2690 }
2691
2692 /**
2693 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2694 * @cgrp: root of the subtree to update csses for
2695 *
2696 * @cgrp's control masks have changed and its subtree's css associations
2697 * need to be updated accordingly. This function looks up all css_sets
2698 * which are attached to the subtree, creates the matching updated css_sets
2699 * and migrates the tasks to the new ones.
2700 */
2701 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2702 {
2703 DEFINE_CGROUP_MGCTX(mgctx);
2704 struct cgroup_subsys_state *d_css;
2705 struct cgroup *dsct;
2706 struct css_set *src_cset;
2707 int ret;
2708
2709 lockdep_assert_held(&cgroup_mutex);
2710
2711 percpu_down_write(&cgroup_threadgroup_rwsem);
2712
2713 /* look up all csses currently attached to @cgrp's subtree */
2714 spin_lock_irq(&css_set_lock);
2715 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2716 struct cgrp_cset_link *link;
2717
2718 list_for_each_entry(link, &dsct->cset_links, cset_link)
2719 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2720 }
2721 spin_unlock_irq(&css_set_lock);
2722
2723 /* NULL dst indicates self on default hierarchy */
2724 ret = cgroup_migrate_prepare_dst(&mgctx);
2725 if (ret)
2726 goto out_finish;
2727
2728 spin_lock_irq(&css_set_lock);
2729 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets, mg_preload_node) {
2730 struct task_struct *task, *ntask;
2731
2732 /* all tasks in src_csets need to be migrated */
2733 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2734 cgroup_migrate_add_task(task, &mgctx);
2735 }
2736 spin_unlock_irq(&css_set_lock);
2737
2738 ret = cgroup_migrate_execute(&mgctx);
2739 out_finish:
2740 cgroup_migrate_finish(&mgctx);
2741 percpu_up_write(&cgroup_threadgroup_rwsem);
2742 return ret;
2743 }
2744
2745 /**
2746 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2747 * @cgrp: root of the target subtree
2748 *
2749 * Because css offlining is asynchronous, userland may try to re-enable a
2750 * controller while the previous css is still around. This function grabs
2751 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2752 */
2753 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2754 __acquires(&cgroup_mutex)
2755 {
2756 struct cgroup *dsct;
2757 struct cgroup_subsys_state *d_css;
2758 struct cgroup_subsys *ss;
2759 int ssid;
2760
2761 restart:
2762 mutex_lock(&cgroup_mutex);
2763
2764 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2765 for_each_subsys(ss, ssid) {
2766 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2767 DEFINE_WAIT(wait);
2768
2769 if (!css || !percpu_ref_is_dying(&css->refcnt))
2770 continue;
2771
2772 cgroup_get_live(dsct);
2773 prepare_to_wait(&dsct->offline_waitq, &wait,
2774 TASK_UNINTERRUPTIBLE);
2775
2776 mutex_unlock(&cgroup_mutex);
2777 schedule();
2778 finish_wait(&dsct->offline_waitq, &wait);
2779
2780 cgroup_put(dsct);
2781 goto restart;
2782 }
2783 }
2784 }
2785
2786 /**
2787 * cgroup_save_control - save control masks and dom_cgrp of a subtree
2788 * @cgrp: root of the target subtree
2789 *
2790 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
2791 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2792 * itself.
2793 */
2794 static void cgroup_save_control(struct cgroup *cgrp)
2795 {
2796 struct cgroup *dsct;
2797 struct cgroup_subsys_state *d_css;
2798
2799 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2800 dsct->old_subtree_control = dsct->subtree_control;
2801 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
2802 dsct->old_dom_cgrp = dsct->dom_cgrp;
2803 }
2804 }
2805
2806 /**
2807 * cgroup_propagate_control - refresh control masks of a subtree
2808 * @cgrp: root of the target subtree
2809 *
2810 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
2811 * ->subtree_control and propagate controller availability through the
2812 * subtree so that descendants don't have unavailable controllers enabled.
2813 */
2814 static void cgroup_propagate_control(struct cgroup *cgrp)
2815 {
2816 struct cgroup *dsct;
2817 struct cgroup_subsys_state *d_css;
2818
2819 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2820 dsct->subtree_control &= cgroup_control(dsct);
2821 dsct->subtree_ss_mask =
2822 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
2823 cgroup_ss_mask(dsct));
2824 }
2825 }
2826
2827 /**
2828 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
2829 * @cgrp: root of the target subtree
2830 *
2831 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
2832 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2833 * itself.
2834 */
2835 static void cgroup_restore_control(struct cgroup *cgrp)
2836 {
2837 struct cgroup *dsct;
2838 struct cgroup_subsys_state *d_css;
2839
2840 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2841 dsct->subtree_control = dsct->old_subtree_control;
2842 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
2843 dsct->dom_cgrp = dsct->old_dom_cgrp;
2844 }
2845 }
2846
2847 static bool css_visible(struct cgroup_subsys_state *css)
2848 {
2849 struct cgroup_subsys *ss = css->ss;
2850 struct cgroup *cgrp = css->cgroup;
2851
2852 if (cgroup_control(cgrp) & (1 << ss->id))
2853 return true;
2854 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
2855 return false;
2856 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
2857 }
2858
2859 /**
2860 * cgroup_apply_control_enable - enable or show csses according to control
2861 * @cgrp: root of the target subtree
2862 *
2863 * Walk @cgrp's subtree and create new csses or make the existing ones
2864 * visible. A css is created invisible if it's being implicitly enabled
2865 * through dependency. An invisible css is made visible when the userland
2866 * explicitly enables it.
2867 *
2868 * Returns 0 on success, -errno on failure. On failure, csses which have
2869 * been processed already aren't cleaned up. The caller is responsible for
2870 * cleaning up with cgroup_apply_control_disable().
2871 */
2872 static int cgroup_apply_control_enable(struct cgroup *cgrp)
2873 {
2874 struct cgroup *dsct;
2875 struct cgroup_subsys_state *d_css;
2876 struct cgroup_subsys *ss;
2877 int ssid, ret;
2878
2879 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2880 for_each_subsys(ss, ssid) {
2881 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2882
2883 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
2884
2885 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
2886 continue;
2887
2888 if (!css) {
2889 css = css_create(dsct, ss);
2890 if (IS_ERR(css))
2891 return PTR_ERR(css);
2892 }
2893
2894 if (css_visible(css)) {
2895 ret = css_populate_dir(css);
2896 if (ret)
2897 return ret;
2898 }
2899 }
2900 }
2901
2902 return 0;
2903 }
2904
2905 /**
2906 * cgroup_apply_control_disable - kill or hide csses according to control
2907 * @cgrp: root of the target subtree
2908 *
2909 * Walk @cgrp's subtree and kill and hide csses so that they match
2910 * cgroup_ss_mask() and cgroup_visible_mask().
2911 *
2912 * A css is hidden when the userland requests it to be disabled while other
2913 * subsystems are still depending on it. The css must not actively control
2914 * resources and be in the vanilla state if it's made visible again later.
2915 * Controllers which may be depended upon should provide ->css_reset() for
2916 * this purpose.
2917 */
2918 static void cgroup_apply_control_disable(struct cgroup *cgrp)
2919 {
2920 struct cgroup *dsct;
2921 struct cgroup_subsys_state *d_css;
2922 struct cgroup_subsys *ss;
2923 int ssid;
2924
2925 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2926 for_each_subsys(ss, ssid) {
2927 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2928
2929 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
2930
2931 if (!css)
2932 continue;
2933
2934 if (css->parent &&
2935 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
2936 kill_css(css);
2937 } else if (!css_visible(css)) {
2938 css_clear_dir(css);
2939 if (ss->css_reset)
2940 ss->css_reset(css);
2941 }
2942 }
2943 }
2944 }
2945
2946 /**
2947 * cgroup_apply_control - apply control mask updates to the subtree
2948 * @cgrp: root of the target subtree
2949 *
2950 * subsystems can be enabled and disabled in a subtree using the following
2951 * steps.
2952 *
2953 * 1. Call cgroup_save_control() to stash the current state.
2954 * 2. Update ->subtree_control masks in the subtree as desired.
2955 * 3. Call cgroup_apply_control() to apply the changes.
2956 * 4. Optionally perform other related operations.
2957 * 5. Call cgroup_finalize_control() to finish up.
2958 *
2959 * This function implements step 3 and propagates the mask changes
2960 * throughout @cgrp's subtree, updates csses accordingly and perform
2961 * process migrations.
2962 */
2963 static int cgroup_apply_control(struct cgroup *cgrp)
2964 {
2965 int ret;
2966
2967 cgroup_propagate_control(cgrp);
2968
2969 ret = cgroup_apply_control_enable(cgrp);
2970 if (ret)
2971 return ret;
2972
2973 /*
2974 * At this point, cgroup_e_css() results reflect the new csses
2975 * making the following cgroup_update_dfl_csses() properly update
2976 * css associations of all tasks in the subtree.
2977 */
2978 ret = cgroup_update_dfl_csses(cgrp);
2979 if (ret)
2980 return ret;
2981
2982 return 0;
2983 }
2984
2985 /**
2986 * cgroup_finalize_control - finalize control mask update
2987 * @cgrp: root of the target subtree
2988 * @ret: the result of the update
2989 *
2990 * Finalize control mask update. See cgroup_apply_control() for more info.
2991 */
2992 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
2993 {
2994 if (ret) {
2995 cgroup_restore_control(cgrp);
2996 cgroup_propagate_control(cgrp);
2997 }
2998
2999 cgroup_apply_control_disable(cgrp);
3000 }
3001
3002 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3003 {
3004 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3005
3006 /* if nothing is getting enabled, nothing to worry about */
3007 if (!enable)
3008 return 0;
3009
3010 /* can @cgrp host any resources? */
3011 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3012 return -EOPNOTSUPP;
3013
3014 /* mixables don't care */
3015 if (cgroup_is_mixable(cgrp))
3016 return 0;
3017
3018 if (domain_enable) {
3019 /* can't enable domain controllers inside a thread subtree */
3020 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3021 return -EOPNOTSUPP;
3022 } else {
3023 /*
3024 * Threaded controllers can handle internal competitions
3025 * and are always allowed inside a (prospective) thread
3026 * subtree.
3027 */
3028 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3029 return 0;
3030 }
3031
3032 /*
3033 * Controllers can't be enabled for a cgroup with tasks to avoid
3034 * child cgroups competing against tasks.
3035 */
3036 if (cgroup_has_tasks(cgrp))
3037 return -EBUSY;
3038
3039 return 0;
3040 }
3041
3042 /* change the enabled child controllers for a cgroup in the default hierarchy */
3043 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3044 char *buf, size_t nbytes,
3045 loff_t off)
3046 {
3047 u16 enable = 0, disable = 0;
3048 struct cgroup *cgrp, *child;
3049 struct cgroup_subsys *ss;
3050 char *tok;
3051 int ssid, ret;
3052
3053 /*
3054 * Parse input - space separated list of subsystem names prefixed
3055 * with either + or -.
3056 */
3057 buf = strstrip(buf);
3058 while ((tok = strsep(&buf, " "))) {
3059 if (tok[0] == '\0')
3060 continue;
3061 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3062 if (!cgroup_ssid_enabled(ssid) ||
3063 strcmp(tok + 1, ss->name))
3064 continue;
3065
3066 if (*tok == '+') {
3067 enable |= 1 << ssid;
3068 disable &= ~(1 << ssid);
3069 } else if (*tok == '-') {
3070 disable |= 1 << ssid;
3071 enable &= ~(1 << ssid);
3072 } else {
3073 return -EINVAL;
3074 }
3075 break;
3076 } while_each_subsys_mask();
3077 if (ssid == CGROUP_SUBSYS_COUNT)
3078 return -EINVAL;
3079 }
3080
3081 cgrp = cgroup_kn_lock_live(of->kn, true);
3082 if (!cgrp)
3083 return -ENODEV;
3084
3085 for_each_subsys(ss, ssid) {
3086 if (enable & (1 << ssid)) {
3087 if (cgrp->subtree_control & (1 << ssid)) {
3088 enable &= ~(1 << ssid);
3089 continue;
3090 }
3091
3092 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3093 ret = -ENOENT;
3094 goto out_unlock;
3095 }
3096 } else if (disable & (1 << ssid)) {
3097 if (!(cgrp->subtree_control & (1 << ssid))) {
3098 disable &= ~(1 << ssid);
3099 continue;
3100 }
3101
3102 /* a child has it enabled? */
3103 cgroup_for_each_live_child(child, cgrp) {
3104 if (child->subtree_control & (1 << ssid)) {
3105 ret = -EBUSY;
3106 goto out_unlock;
3107 }
3108 }
3109 }
3110 }
3111
3112 if (!enable && !disable) {
3113 ret = 0;
3114 goto out_unlock;
3115 }
3116
3117 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3118 if (ret)
3119 goto out_unlock;
3120
3121 /* save and update control masks and prepare csses */
3122 cgroup_save_control(cgrp);
3123
3124 cgrp->subtree_control |= enable;
3125 cgrp->subtree_control &= ~disable;
3126
3127 ret = cgroup_apply_control(cgrp);
3128 cgroup_finalize_control(cgrp, ret);
3129 if (ret)
3130 goto out_unlock;
3131
3132 kernfs_activate(cgrp->kn);
3133 out_unlock:
3134 cgroup_kn_unlock(of->kn);
3135 return ret ?: nbytes;
3136 }
3137
3138 /**
3139 * cgroup_enable_threaded - make @cgrp threaded
3140 * @cgrp: the target cgroup
3141 *
3142 * Called when "threaded" is written to the cgroup.type interface file and
3143 * tries to make @cgrp threaded and join the parent's resource domain.
3144 * This function is never called on the root cgroup as cgroup.type doesn't
3145 * exist on it.
3146 */
3147 static int cgroup_enable_threaded(struct cgroup *cgrp)
3148 {
3149 struct cgroup *parent = cgroup_parent(cgrp);
3150 struct cgroup *dom_cgrp = parent->dom_cgrp;
3151 struct cgroup *dsct;
3152 struct cgroup_subsys_state *d_css;
3153 int ret;
3154
3155 lockdep_assert_held(&cgroup_mutex);
3156
3157 /* noop if already threaded */
3158 if (cgroup_is_threaded(cgrp))
3159 return 0;
3160
3161 /*
3162 * If @cgroup is populated or has domain controllers enabled, it
3163 * can't be switched. While the below cgroup_can_be_thread_root()
3164 * test can catch the same conditions, that's only when @parent is
3165 * not mixable, so let's check it explicitly.
3166 */
3167 if (cgroup_is_populated(cgrp) ||
3168 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3169 return -EOPNOTSUPP;
3170
3171 /* we're joining the parent's domain, ensure its validity */
3172 if (!cgroup_is_valid_domain(dom_cgrp) ||
3173 !cgroup_can_be_thread_root(dom_cgrp))
3174 return -EOPNOTSUPP;
3175
3176 /*
3177 * The following shouldn't cause actual migrations and should
3178 * always succeed.
3179 */
3180 cgroup_save_control(cgrp);
3181
3182 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3183 if (dsct == cgrp || cgroup_is_threaded(dsct))
3184 dsct->dom_cgrp = dom_cgrp;
3185
3186 ret = cgroup_apply_control(cgrp);
3187 if (!ret)
3188 parent->nr_threaded_children++;
3189
3190 cgroup_finalize_control(cgrp, ret);
3191 return ret;
3192 }
3193
3194 static int cgroup_type_show(struct seq_file *seq, void *v)
3195 {
3196 struct cgroup *cgrp = seq_css(seq)->cgroup;
3197
3198 if (cgroup_is_threaded(cgrp))
3199 seq_puts(seq, "threaded\n");
3200 else if (!cgroup_is_valid_domain(cgrp))
3201 seq_puts(seq, "domain invalid\n");
3202 else if (cgroup_is_thread_root(cgrp))
3203 seq_puts(seq, "domain threaded\n");
3204 else
3205 seq_puts(seq, "domain\n");
3206
3207 return 0;
3208 }
3209
3210 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3211 size_t nbytes, loff_t off)
3212 {
3213 struct cgroup *cgrp;
3214 int ret;
3215
3216 /* only switching to threaded mode is supported */
3217 if (strcmp(strstrip(buf), "threaded"))
3218 return -EINVAL;
3219
3220 cgrp = cgroup_kn_lock_live(of->kn, false);
3221 if (!cgrp)
3222 return -ENOENT;
3223
3224 /* threaded can only be enabled */
3225 ret = cgroup_enable_threaded(cgrp);
3226
3227 cgroup_kn_unlock(of->kn);
3228 return ret ?: nbytes;
3229 }
3230
3231 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3232 {
3233 struct cgroup *cgrp = seq_css(seq)->cgroup;
3234 int descendants = READ_ONCE(cgrp->max_descendants);
3235
3236 if (descendants == INT_MAX)
3237 seq_puts(seq, "max\n");
3238 else
3239 seq_printf(seq, "%d\n", descendants);
3240
3241 return 0;
3242 }
3243
3244 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3245 char *buf, size_t nbytes, loff_t off)
3246 {
3247 struct cgroup *cgrp;
3248 int descendants;
3249 ssize_t ret;
3250
3251 buf = strstrip(buf);
3252 if (!strcmp(buf, "max")) {
3253 descendants = INT_MAX;
3254 } else {
3255 ret = kstrtoint(buf, 0, &descendants);
3256 if (ret)
3257 return ret;
3258 }
3259
3260 if (descendants < 0)
3261 return -ERANGE;
3262
3263 cgrp = cgroup_kn_lock_live(of->kn, false);
3264 if (!cgrp)
3265 return -ENOENT;
3266
3267 cgrp->max_descendants = descendants;
3268
3269 cgroup_kn_unlock(of->kn);
3270
3271 return nbytes;
3272 }
3273
3274 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3275 {
3276 struct cgroup *cgrp = seq_css(seq)->cgroup;
3277 int depth = READ_ONCE(cgrp->max_depth);
3278
3279 if (depth == INT_MAX)
3280 seq_puts(seq, "max\n");
3281 else
3282 seq_printf(seq, "%d\n", depth);
3283
3284 return 0;
3285 }
3286
3287 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3288 char *buf, size_t nbytes, loff_t off)
3289 {
3290 struct cgroup *cgrp;
3291 ssize_t ret;
3292 int depth;
3293
3294 buf = strstrip(buf);
3295 if (!strcmp(buf, "max")) {
3296 depth = INT_MAX;
3297 } else {
3298 ret = kstrtoint(buf, 0, &depth);
3299 if (ret)
3300 return ret;
3301 }
3302
3303 if (depth < 0)
3304 return -ERANGE;
3305
3306 cgrp = cgroup_kn_lock_live(of->kn, false);
3307 if (!cgrp)
3308 return -ENOENT;
3309
3310 cgrp->max_depth = depth;
3311
3312 cgroup_kn_unlock(of->kn);
3313
3314 return nbytes;
3315 }
3316
3317 static int cgroup_events_show(struct seq_file *seq, void *v)
3318 {
3319 seq_printf(seq, "populated %d\n",
3320 cgroup_is_populated(seq_css(seq)->cgroup));
3321 return 0;
3322 }
3323
3324 static int cgroup_stat_show(struct seq_file *seq, void *v)
3325 {
3326 struct cgroup *cgroup = seq_css(seq)->cgroup;
3327
3328 seq_printf(seq, "nr_descendants %d\n",
3329 cgroup->nr_descendants);
3330 seq_printf(seq, "nr_dying_descendants %d\n",
3331 cgroup->nr_dying_descendants);
3332
3333 return 0;
3334 }
3335
3336 #ifdef CONFIG_PSI
3337 static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
3338 {
3339 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_IO);
3340 }
3341 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
3342 {
3343 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_MEM);
3344 }
3345 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
3346 {
3347 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_CPU);
3348 }
3349
3350 static ssize_t cgroup_pressure_write(struct kernfs_open_file *of, char *buf,
3351 size_t nbytes, enum psi_res res)
3352 {
3353 struct psi_trigger *new;
3354 struct cgroup *cgrp;
3355
3356 cgrp = cgroup_kn_lock_live(of->kn, false);
3357 if (!cgrp)
3358 return -ENODEV;
3359
3360 cgroup_get(cgrp);
3361 cgroup_kn_unlock(of->kn);
3362
3363 new = psi_trigger_create(&cgrp->psi, buf, nbytes, res);
3364 if (IS_ERR(new)) {
3365 cgroup_put(cgrp);
3366 return PTR_ERR(new);
3367 }
3368
3369 psi_trigger_replace(&of->priv, new);
3370
3371 cgroup_put(cgrp);
3372
3373 return nbytes;
3374 }
3375
3376 static ssize_t cgroup_io_pressure_write(struct kernfs_open_file *of,
3377 char *buf, size_t nbytes,
3378 loff_t off)
3379 {
3380 return cgroup_pressure_write(of, buf, nbytes, PSI_IO);
3381 }
3382
3383 static ssize_t cgroup_memory_pressure_write(struct kernfs_open_file *of,
3384 char *buf, size_t nbytes,
3385 loff_t off)
3386 {
3387 return cgroup_pressure_write(of, buf, nbytes, PSI_MEM);
3388 }
3389
3390 static ssize_t cgroup_cpu_pressure_write(struct kernfs_open_file *of,
3391 char *buf, size_t nbytes,
3392 loff_t off)
3393 {
3394 return cgroup_pressure_write(of, buf, nbytes, PSI_CPU);
3395 }
3396
3397 static unsigned int cgroup_pressure_poll(struct kernfs_open_file *of,
3398 poll_table *pt)
3399 {
3400 return psi_trigger_poll(&of->priv, of->file, pt);
3401 }
3402
3403 static void cgroup_pressure_release(struct kernfs_open_file *of)
3404 {
3405 psi_trigger_replace(&of->priv, NULL);
3406 }
3407 #endif /* CONFIG_PSI */
3408
3409 static int cgroup_file_open(struct kernfs_open_file *of)
3410 {
3411 struct cftype *cft = of->kn->priv;
3412
3413 if (cft->open)
3414 return cft->open(of);
3415 return 0;
3416 }
3417
3418 static void cgroup_file_release(struct kernfs_open_file *of)
3419 {
3420 struct cftype *cft = of->kn->priv;
3421
3422 if (cft->release)
3423 cft->release(of);
3424 }
3425
3426 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3427 size_t nbytes, loff_t off)
3428 {
3429 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
3430 struct cgroup *cgrp = of->kn->parent->priv;
3431 struct cftype *cft = of->kn->priv;
3432 struct cgroup_subsys_state *css;
3433 int ret;
3434
3435 /*
3436 * If namespaces are delegation boundaries, disallow writes to
3437 * files in an non-init namespace root from inside the namespace
3438 * except for the files explicitly marked delegatable -
3439 * cgroup.procs and cgroup.subtree_control.
3440 */
3441 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3442 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3443 ns != &init_cgroup_ns && ns->root_cset->dfl_cgrp == cgrp)
3444 return -EPERM;
3445
3446 if (cft->write)
3447 return cft->write(of, buf, nbytes, off);
3448
3449 /*
3450 * kernfs guarantees that a file isn't deleted with operations in
3451 * flight, which means that the matching css is and stays alive and
3452 * doesn't need to be pinned. The RCU locking is not necessary
3453 * either. It's just for the convenience of using cgroup_css().
3454 */
3455 rcu_read_lock();
3456 css = cgroup_css(cgrp, cft->ss);
3457 rcu_read_unlock();
3458
3459 if (cft->write_u64) {
3460 unsigned long long v;
3461 ret = kstrtoull(buf, 0, &v);
3462 if (!ret)
3463 ret = cft->write_u64(css, cft, v);
3464 } else if (cft->write_s64) {
3465 long long v;
3466 ret = kstrtoll(buf, 0, &v);
3467 if (!ret)
3468 ret = cft->write_s64(css, cft, v);
3469 } else {
3470 ret = -EINVAL;
3471 }
3472
3473 return ret ?: nbytes;
3474 }
3475
3476 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3477 {
3478 return seq_cft(seq)->seq_start(seq, ppos);
3479 }
3480
3481 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3482 {
3483 return seq_cft(seq)->seq_next(seq, v, ppos);
3484 }
3485
3486 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3487 {
3488 if (seq_cft(seq)->seq_stop)
3489 seq_cft(seq)->seq_stop(seq, v);
3490 }
3491
3492 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3493 {
3494 struct cftype *cft = seq_cft(m);
3495 struct cgroup_subsys_state *css = seq_css(m);
3496
3497 if (cft->seq_show)
3498 return cft->seq_show(m, arg);
3499
3500 if (cft->read_u64)
3501 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3502 else if (cft->read_s64)
3503 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3504 else
3505 return -EINVAL;
3506 return 0;
3507 }
3508
3509 static struct kernfs_ops cgroup_kf_single_ops = {
3510 .atomic_write_len = PAGE_SIZE,
3511 .open = cgroup_file_open,
3512 .release = cgroup_file_release,
3513 .write = cgroup_file_write,
3514 .seq_show = cgroup_seqfile_show,
3515 };
3516
3517 static struct kernfs_ops cgroup_kf_ops = {
3518 .atomic_write_len = PAGE_SIZE,
3519 .open = cgroup_file_open,
3520 .release = cgroup_file_release,
3521 .write = cgroup_file_write,
3522 .seq_start = cgroup_seqfile_start,
3523 .seq_next = cgroup_seqfile_next,
3524 .seq_stop = cgroup_seqfile_stop,
3525 .seq_show = cgroup_seqfile_show,
3526 };
3527
3528 /* set uid and gid of cgroup dirs and files to that of the creator */
3529 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3530 {
3531 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3532 .ia_uid = current_fsuid(),
3533 .ia_gid = current_fsgid(), };
3534
3535 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3536 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3537 return 0;
3538
3539 return kernfs_setattr(kn, &iattr);
3540 }
3541
3542 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
3543 struct cftype *cft)
3544 {
3545 char name[CGROUP_FILE_NAME_MAX];
3546 struct kernfs_node *kn;
3547 struct lock_class_key *key = NULL;
3548 int ret;
3549
3550 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3551 key = &cft->lockdep_key;
3552 #endif
3553 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3554 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
3555 NULL, key);
3556 if (IS_ERR(kn))
3557 return PTR_ERR(kn);
3558
3559 ret = cgroup_kn_set_ugid(kn);
3560 if (ret) {
3561 kernfs_remove(kn);
3562 return ret;
3563 }
3564
3565 if (cft->file_offset) {
3566 struct cgroup_file *cfile = (void *)css + cft->file_offset;
3567
3568 spin_lock_irq(&cgroup_file_kn_lock);
3569 cfile->kn = kn;
3570 spin_unlock_irq(&cgroup_file_kn_lock);
3571 }
3572
3573 return 0;
3574 }
3575
3576 /**
3577 * cgroup_addrm_files - add or remove files to a cgroup directory
3578 * @css: the target css
3579 * @cgrp: the target cgroup (usually css->cgroup)
3580 * @cfts: array of cftypes to be added
3581 * @is_add: whether to add or remove
3582 *
3583 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3584 * For removals, this function never fails.
3585 */
3586 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
3587 struct cgroup *cgrp, struct cftype cfts[],
3588 bool is_add)
3589 {
3590 struct cftype *cft, *cft_end = NULL;
3591 int ret = 0;
3592
3593 lockdep_assert_held(&cgroup_mutex);
3594
3595 restart:
3596 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
3597 /* does cft->flags tell us to skip this file on @cgrp? */
3598 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3599 continue;
3600 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3601 continue;
3602 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3603 continue;
3604 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3605 continue;
3606
3607 if (is_add) {
3608 ret = cgroup_add_file(css, cgrp, cft);
3609 if (ret) {
3610 pr_warn("%s: failed to add %s, err=%d\n",
3611 __func__, cft->name, ret);
3612 cft_end = cft;
3613 is_add = false;
3614 goto restart;
3615 }
3616 } else {
3617 cgroup_rm_file(cgrp, cft);
3618 }
3619 }
3620 return ret;
3621 }
3622
3623 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3624 {
3625 struct cgroup_subsys *ss = cfts[0].ss;
3626 struct cgroup *root = &ss->root->cgrp;
3627 struct cgroup_subsys_state *css;
3628 int ret = 0;
3629
3630 lockdep_assert_held(&cgroup_mutex);
3631
3632 /* add/rm files for all cgroups created before */
3633 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3634 struct cgroup *cgrp = css->cgroup;
3635
3636 if (!(css->flags & CSS_VISIBLE))
3637 continue;
3638
3639 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
3640 if (ret)
3641 break;
3642 }
3643
3644 if (is_add && !ret)
3645 kernfs_activate(root->kn);
3646 return ret;
3647 }
3648
3649 static void cgroup_exit_cftypes(struct cftype *cfts)
3650 {
3651 struct cftype *cft;
3652
3653 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3654 /* free copy for custom atomic_write_len, see init_cftypes() */
3655 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3656 kfree(cft->kf_ops);
3657 cft->kf_ops = NULL;
3658 cft->ss = NULL;
3659
3660 /* revert flags set by cgroup core while adding @cfts */
3661 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3662 }
3663 }
3664
3665 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3666 {
3667 struct cftype *cft;
3668
3669 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3670 struct kernfs_ops *kf_ops;
3671
3672 WARN_ON(cft->ss || cft->kf_ops);
3673
3674 if (cft->seq_start)
3675 kf_ops = &cgroup_kf_ops;
3676 else
3677 kf_ops = &cgroup_kf_single_ops;
3678
3679 /*
3680 * Ugh... if @cft wants a custom max_write_len, we need to
3681 * make a copy of kf_ops to set its atomic_write_len.
3682 */
3683 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3684 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3685 if (!kf_ops) {
3686 cgroup_exit_cftypes(cfts);
3687 return -ENOMEM;
3688 }
3689 kf_ops->atomic_write_len = cft->max_write_len;
3690 }
3691
3692 cft->kf_ops = kf_ops;
3693 cft->ss = ss;
3694 }
3695
3696 return 0;
3697 }
3698
3699 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3700 {
3701 lockdep_assert_held(&cgroup_mutex);
3702
3703 if (!cfts || !cfts[0].ss)
3704 return -ENOENT;
3705
3706 list_del(&cfts->node);
3707 cgroup_apply_cftypes(cfts, false);
3708 cgroup_exit_cftypes(cfts);
3709 return 0;
3710 }
3711
3712 /**
3713 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3714 * @cfts: zero-length name terminated array of cftypes
3715 *
3716 * Unregister @cfts. Files described by @cfts are removed from all
3717 * existing cgroups and all future cgroups won't have them either. This
3718 * function can be called anytime whether @cfts' subsys is attached or not.
3719 *
3720 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3721 * registered.
3722 */
3723 int cgroup_rm_cftypes(struct cftype *cfts)
3724 {
3725 int ret;
3726
3727 mutex_lock(&cgroup_mutex);
3728 ret = cgroup_rm_cftypes_locked(cfts);
3729 mutex_unlock(&cgroup_mutex);
3730 return ret;
3731 }
3732
3733 /**
3734 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3735 * @ss: target cgroup subsystem
3736 * @cfts: zero-length name terminated array of cftypes
3737 *
3738 * Register @cfts to @ss. Files described by @cfts are created for all
3739 * existing cgroups to which @ss is attached and all future cgroups will
3740 * have them too. This function can be called anytime whether @ss is
3741 * attached or not.
3742 *
3743 * Returns 0 on successful registration, -errno on failure. Note that this
3744 * function currently returns 0 as long as @cfts registration is successful
3745 * even if some file creation attempts on existing cgroups fail.
3746 */
3747 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3748 {
3749 int ret;
3750
3751 if (!cgroup_ssid_enabled(ss->id))
3752 return 0;
3753
3754 if (!cfts || cfts[0].name[0] == '\0')
3755 return 0;
3756
3757 ret = cgroup_init_cftypes(ss, cfts);
3758 if (ret)
3759 return ret;
3760
3761 mutex_lock(&cgroup_mutex);
3762
3763 list_add_tail(&cfts->node, &ss->cfts);
3764 ret = cgroup_apply_cftypes(cfts, true);
3765 if (ret)
3766 cgroup_rm_cftypes_locked(cfts);
3767
3768 mutex_unlock(&cgroup_mutex);
3769 return ret;
3770 }
3771
3772 /**
3773 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3774 * @ss: target cgroup subsystem
3775 * @cfts: zero-length name terminated array of cftypes
3776 *
3777 * Similar to cgroup_add_cftypes() but the added files are only used for
3778 * the default hierarchy.
3779 */
3780 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3781 {
3782 struct cftype *cft;
3783
3784 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3785 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3786 return cgroup_add_cftypes(ss, cfts);
3787 }
3788
3789 /**
3790 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3791 * @ss: target cgroup subsystem
3792 * @cfts: zero-length name terminated array of cftypes
3793 *
3794 * Similar to cgroup_add_cftypes() but the added files are only used for
3795 * the legacy hierarchies.
3796 */
3797 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3798 {
3799 struct cftype *cft;
3800
3801 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3802 cft->flags |= __CFTYPE_NOT_ON_DFL;
3803 return cgroup_add_cftypes(ss, cfts);
3804 }
3805
3806 /**
3807 * cgroup_file_notify - generate a file modified event for a cgroup_file
3808 * @cfile: target cgroup_file
3809 *
3810 * @cfile must have been obtained by setting cftype->file_offset.
3811 */
3812 void cgroup_file_notify(struct cgroup_file *cfile)
3813 {
3814 unsigned long flags;
3815
3816 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
3817 if (cfile->kn)
3818 kernfs_notify(cfile->kn);
3819 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
3820 }
3821
3822 /**
3823 * css_next_child - find the next child of a given css
3824 * @pos: the current position (%NULL to initiate traversal)
3825 * @parent: css whose children to walk
3826 *
3827 * This function returns the next child of @parent and should be called
3828 * under either cgroup_mutex or RCU read lock. The only requirement is
3829 * that @parent and @pos are accessible. The next sibling is guaranteed to
3830 * be returned regardless of their states.
3831 *
3832 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3833 * css which finished ->css_online() is guaranteed to be visible in the
3834 * future iterations and will stay visible until the last reference is put.
3835 * A css which hasn't finished ->css_online() or already finished
3836 * ->css_offline() may show up during traversal. It's each subsystem's
3837 * responsibility to synchronize against on/offlining.
3838 */
3839 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3840 struct cgroup_subsys_state *parent)
3841 {
3842 struct cgroup_subsys_state *next;
3843
3844 cgroup_assert_mutex_or_rcu_locked();
3845
3846 /*
3847 * @pos could already have been unlinked from the sibling list.
3848 * Once a cgroup is removed, its ->sibling.next is no longer
3849 * updated when its next sibling changes. CSS_RELEASED is set when
3850 * @pos is taken off list, at which time its next pointer is valid,
3851 * and, as releases are serialized, the one pointed to by the next
3852 * pointer is guaranteed to not have started release yet. This
3853 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3854 * critical section, the one pointed to by its next pointer is
3855 * guaranteed to not have finished its RCU grace period even if we
3856 * have dropped rcu_read_lock() inbetween iterations.
3857 *
3858 * If @pos has CSS_RELEASED set, its next pointer can't be
3859 * dereferenced; however, as each css is given a monotonically
3860 * increasing unique serial number and always appended to the
3861 * sibling list, the next one can be found by walking the parent's
3862 * children until the first css with higher serial number than
3863 * @pos's. While this path can be slower, it happens iff iteration
3864 * races against release and the race window is very small.
3865 */
3866 if (!pos) {
3867 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3868 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3869 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3870 } else {
3871 list_for_each_entry_rcu(next, &parent->children, sibling)
3872 if (next->serial_nr > pos->serial_nr)
3873 break;
3874 }
3875
3876 /*
3877 * @next, if not pointing to the head, can be dereferenced and is
3878 * the next sibling.
3879 */
3880 if (&next->sibling != &parent->children)
3881 return next;
3882 return NULL;
3883 }
3884
3885 /**
3886 * css_next_descendant_pre - find the next descendant for pre-order walk
3887 * @pos: the current position (%NULL to initiate traversal)
3888 * @root: css whose descendants to walk
3889 *
3890 * To be used by css_for_each_descendant_pre(). Find the next descendant
3891 * to visit for pre-order traversal of @root's descendants. @root is
3892 * included in the iteration and the first node to be visited.
3893 *
3894 * While this function requires cgroup_mutex or RCU read locking, it
3895 * doesn't require the whole traversal to be contained in a single critical
3896 * section. This function will return the correct next descendant as long
3897 * as both @pos and @root are accessible and @pos is a descendant of @root.
3898 *
3899 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3900 * css which finished ->css_online() is guaranteed to be visible in the
3901 * future iterations and will stay visible until the last reference is put.
3902 * A css which hasn't finished ->css_online() or already finished
3903 * ->css_offline() may show up during traversal. It's each subsystem's
3904 * responsibility to synchronize against on/offlining.
3905 */
3906 struct cgroup_subsys_state *
3907 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3908 struct cgroup_subsys_state *root)
3909 {
3910 struct cgroup_subsys_state *next;
3911
3912 cgroup_assert_mutex_or_rcu_locked();
3913
3914 /* if first iteration, visit @root */
3915 if (!pos)
3916 return root;
3917
3918 /* visit the first child if exists */
3919 next = css_next_child(NULL, pos);
3920 if (next)
3921 return next;
3922
3923 /* no child, visit my or the closest ancestor's next sibling */
3924 while (pos != root) {
3925 next = css_next_child(pos, pos->parent);
3926 if (next)
3927 return next;
3928 pos = pos->parent;
3929 }
3930
3931 return NULL;
3932 }
3933
3934 /**
3935 * css_rightmost_descendant - return the rightmost descendant of a css
3936 * @pos: css of interest
3937 *
3938 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3939 * is returned. This can be used during pre-order traversal to skip
3940 * subtree of @pos.
3941 *
3942 * While this function requires cgroup_mutex or RCU read locking, it
3943 * doesn't require the whole traversal to be contained in a single critical
3944 * section. This function will return the correct rightmost descendant as
3945 * long as @pos is accessible.
3946 */
3947 struct cgroup_subsys_state *
3948 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3949 {
3950 struct cgroup_subsys_state *last, *tmp;
3951
3952 cgroup_assert_mutex_or_rcu_locked();
3953
3954 do {
3955 last = pos;
3956 /* ->prev isn't RCU safe, walk ->next till the end */
3957 pos = NULL;
3958 css_for_each_child(tmp, last)
3959 pos = tmp;
3960 } while (pos);
3961
3962 return last;
3963 }
3964
3965 static struct cgroup_subsys_state *
3966 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3967 {
3968 struct cgroup_subsys_state *last;
3969
3970 do {
3971 last = pos;
3972 pos = css_next_child(NULL, pos);
3973 } while (pos);
3974
3975 return last;
3976 }
3977
3978 /**
3979 * css_next_descendant_post - find the next descendant for post-order walk
3980 * @pos: the current position (%NULL to initiate traversal)
3981 * @root: css whose descendants to walk
3982 *
3983 * To be used by css_for_each_descendant_post(). Find the next descendant
3984 * to visit for post-order traversal of @root's descendants. @root is
3985 * included in the iteration and the last node to be visited.
3986 *
3987 * While this function requires cgroup_mutex or RCU read locking, it
3988 * doesn't require the whole traversal to be contained in a single critical
3989 * section. This function will return the correct next descendant as long
3990 * as both @pos and @cgroup are accessible and @pos is a descendant of
3991 * @cgroup.
3992 *
3993 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3994 * css which finished ->css_online() is guaranteed to be visible in the
3995 * future iterations and will stay visible until the last reference is put.
3996 * A css which hasn't finished ->css_online() or already finished
3997 * ->css_offline() may show up during traversal. It's each subsystem's
3998 * responsibility to synchronize against on/offlining.
3999 */
4000 struct cgroup_subsys_state *
4001 css_next_descendant_post(struct cgroup_subsys_state *pos,
4002 struct cgroup_subsys_state *root)
4003 {
4004 struct cgroup_subsys_state *next;
4005
4006 cgroup_assert_mutex_or_rcu_locked();
4007
4008 /* if first iteration, visit leftmost descendant which may be @root */
4009 if (!pos)
4010 return css_leftmost_descendant(root);
4011
4012 /* if we visited @root, we're done */
4013 if (pos == root)
4014 return NULL;
4015
4016 /* if there's an unvisited sibling, visit its leftmost descendant */
4017 next = css_next_child(pos, pos->parent);
4018 if (next)
4019 return css_leftmost_descendant(next);
4020
4021 /* no sibling left, visit parent */
4022 return pos->parent;
4023 }
4024
4025 /**
4026 * css_has_online_children - does a css have online children
4027 * @css: the target css
4028 *
4029 * Returns %true if @css has any online children; otherwise, %false. This
4030 * function can be called from any context but the caller is responsible
4031 * for synchronizing against on/offlining as necessary.
4032 */
4033 bool css_has_online_children(struct cgroup_subsys_state *css)
4034 {
4035 struct cgroup_subsys_state *child;
4036 bool ret = false;
4037
4038 rcu_read_lock();
4039 css_for_each_child(child, css) {
4040 if (child->flags & CSS_ONLINE) {
4041 ret = true;
4042 break;
4043 }
4044 }
4045 rcu_read_unlock();
4046 return ret;
4047 }
4048
4049 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4050 {
4051 struct list_head *l;
4052 struct cgrp_cset_link *link;
4053 struct css_set *cset;
4054
4055 lockdep_assert_held(&css_set_lock);
4056
4057 /* find the next threaded cset */
4058 if (it->tcset_pos) {
4059 l = it->tcset_pos->next;
4060
4061 if (l != it->tcset_head) {
4062 it->tcset_pos = l;
4063 return container_of(l, struct css_set,
4064 threaded_csets_node);
4065 }
4066
4067 it->tcset_pos = NULL;
4068 }
4069
4070 /* find the next cset */
4071 l = it->cset_pos;
4072 l = l->next;
4073 if (l == it->cset_head) {
4074 it->cset_pos = NULL;
4075 return NULL;
4076 }
4077
4078 if (it->ss) {
4079 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4080 } else {
4081 link = list_entry(l, struct cgrp_cset_link, cset_link);
4082 cset = link->cset;
4083 }
4084
4085 it->cset_pos = l;
4086
4087 /* initialize threaded css_set walking */
4088 if (it->flags & CSS_TASK_ITER_THREADED) {
4089 if (it->cur_dcset)
4090 put_css_set_locked(it->cur_dcset);
4091 it->cur_dcset = cset;
4092 get_css_set(cset);
4093
4094 it->tcset_head = &cset->threaded_csets;
4095 it->tcset_pos = &cset->threaded_csets;
4096 }
4097
4098 return cset;
4099 }
4100
4101 /**
4102 * css_task_iter_advance_css_set - advance a task itererator to the next css_set
4103 * @it: the iterator to advance
4104 *
4105 * Advance @it to the next css_set to walk.
4106 */
4107 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4108 {
4109 struct css_set *cset;
4110
4111 lockdep_assert_held(&css_set_lock);
4112
4113 /* Advance to the next non-empty css_set */
4114 do {
4115 cset = css_task_iter_next_css_set(it);
4116 if (!cset) {
4117 it->task_pos = NULL;
4118 return;
4119 }
4120 } while (!css_set_populated(cset));
4121
4122 if (!list_empty(&cset->tasks))
4123 it->task_pos = cset->tasks.next;
4124 else
4125 it->task_pos = cset->mg_tasks.next;
4126
4127 it->tasks_head = &cset->tasks;
4128 it->mg_tasks_head = &cset->mg_tasks;
4129
4130 /*
4131 * We don't keep css_sets locked across iteration steps and thus
4132 * need to take steps to ensure that iteration can be resumed after
4133 * the lock is re-acquired. Iteration is performed at two levels -
4134 * css_sets and tasks in them.
4135 *
4136 * Once created, a css_set never leaves its cgroup lists, so a
4137 * pinned css_set is guaranteed to stay put and we can resume
4138 * iteration afterwards.
4139 *
4140 * Tasks may leave @cset across iteration steps. This is resolved
4141 * by registering each iterator with the css_set currently being
4142 * walked and making css_set_move_task() advance iterators whose
4143 * next task is leaving.
4144 */
4145 if (it->cur_cset) {
4146 list_del(&it->iters_node);
4147 put_css_set_locked(it->cur_cset);
4148 }
4149 get_css_set(cset);
4150 it->cur_cset = cset;
4151 list_add(&it->iters_node, &cset->task_iters);
4152 }
4153
4154 static void css_task_iter_advance(struct css_task_iter *it)
4155 {
4156 struct list_head *next;
4157
4158 lockdep_assert_held(&css_set_lock);
4159 repeat:
4160 if (it->task_pos) {
4161 /*
4162 * Advance iterator to find next entry. cset->tasks is
4163 * consumed first and then ->mg_tasks. After ->mg_tasks,
4164 * we move onto the next cset.
4165 */
4166 next = it->task_pos->next;
4167
4168 if (next == it->tasks_head)
4169 next = it->mg_tasks_head->next;
4170
4171 if (next == it->mg_tasks_head)
4172 css_task_iter_advance_css_set(it);
4173 else
4174 it->task_pos = next;
4175 } else {
4176 /* called from start, proceed to the first cset */
4177 css_task_iter_advance_css_set(it);
4178 }
4179
4180 /* if PROCS, skip over tasks which aren't group leaders */
4181 if ((it->flags & CSS_TASK_ITER_PROCS) && it->task_pos &&
4182 !thread_group_leader(list_entry(it->task_pos, struct task_struct,
4183 cg_list)))
4184 goto repeat;
4185 }
4186
4187 /**
4188 * css_task_iter_start - initiate task iteration
4189 * @css: the css to walk tasks of
4190 * @flags: CSS_TASK_ITER_* flags
4191 * @it: the task iterator to use
4192 *
4193 * Initiate iteration through the tasks of @css. The caller can call
4194 * css_task_iter_next() to walk through the tasks until the function
4195 * returns NULL. On completion of iteration, css_task_iter_end() must be
4196 * called.
4197 */
4198 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4199 struct css_task_iter *it)
4200 {
4201 /* no one should try to iterate before mounting cgroups */
4202 WARN_ON_ONCE(!use_task_css_set_links);
4203
4204 memset(it, 0, sizeof(*it));
4205
4206 spin_lock_irq(&css_set_lock);
4207
4208 it->ss = css->ss;
4209 it->flags = flags;
4210
4211 if (it->ss)
4212 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4213 else
4214 it->cset_pos = &css->cgroup->cset_links;
4215
4216 it->cset_head = it->cset_pos;
4217
4218 css_task_iter_advance(it);
4219
4220 spin_unlock_irq(&css_set_lock);
4221 }
4222
4223 /**
4224 * css_task_iter_next - return the next task for the iterator
4225 * @it: the task iterator being iterated
4226 *
4227 * The "next" function for task iteration. @it should have been
4228 * initialized via css_task_iter_start(). Returns NULL when the iteration
4229 * reaches the end.
4230 */
4231 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4232 {
4233 if (it->cur_task) {
4234 put_task_struct(it->cur_task);
4235 it->cur_task = NULL;
4236 }
4237
4238 spin_lock_irq(&css_set_lock);
4239
4240 if (it->task_pos) {
4241 it->cur_task = list_entry(it->task_pos, struct task_struct,
4242 cg_list);
4243 get_task_struct(it->cur_task);
4244 css_task_iter_advance(it);
4245 }
4246
4247 spin_unlock_irq(&css_set_lock);
4248
4249 return it->cur_task;
4250 }
4251
4252 /**
4253 * css_task_iter_end - finish task iteration
4254 * @it: the task iterator to finish
4255 *
4256 * Finish task iteration started by css_task_iter_start().
4257 */
4258 void css_task_iter_end(struct css_task_iter *it)
4259 {
4260 if (it->cur_cset) {
4261 spin_lock_irq(&css_set_lock);
4262 list_del(&it->iters_node);
4263 put_css_set_locked(it->cur_cset);
4264 spin_unlock_irq(&css_set_lock);
4265 }
4266
4267 if (it->cur_dcset)
4268 put_css_set(it->cur_dcset);
4269
4270 if (it->cur_task)
4271 put_task_struct(it->cur_task);
4272 }
4273
4274 static void cgroup_procs_release(struct kernfs_open_file *of)
4275 {
4276 if (of->priv) {
4277 css_task_iter_end(of->priv);
4278 kfree(of->priv);
4279 }
4280 }
4281
4282 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
4283 {
4284 struct kernfs_open_file *of = s->private;
4285 struct css_task_iter *it = of->priv;
4286
4287 return css_task_iter_next(it);
4288 }
4289
4290 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
4291 unsigned int iter_flags)
4292 {
4293 struct kernfs_open_file *of = s->private;
4294 struct cgroup *cgrp = seq_css(s)->cgroup;
4295 struct css_task_iter *it = of->priv;
4296
4297 /*
4298 * When a seq_file is seeked, it's always traversed sequentially
4299 * from position 0, so we can simply keep iterating on !0 *pos.
4300 */
4301 if (!it) {
4302 if (WARN_ON_ONCE((*pos)++))
4303 return ERR_PTR(-EINVAL);
4304
4305 it = kzalloc(sizeof(*it), GFP_KERNEL);
4306 if (!it)
4307 return ERR_PTR(-ENOMEM);
4308 of->priv = it;
4309 css_task_iter_start(&cgrp->self, iter_flags, it);
4310 } else if (!(*pos)++) {
4311 css_task_iter_end(it);
4312 css_task_iter_start(&cgrp->self, iter_flags, it);
4313 }
4314
4315 return cgroup_procs_next(s, NULL, NULL);
4316 }
4317
4318 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
4319 {
4320 struct cgroup *cgrp = seq_css(s)->cgroup;
4321
4322 /*
4323 * All processes of a threaded subtree belong to the domain cgroup
4324 * of the subtree. Only threads can be distributed across the
4325 * subtree. Reject reads on cgroup.procs in the subtree proper.
4326 * They're always empty anyway.
4327 */
4328 if (cgroup_is_threaded(cgrp))
4329 return ERR_PTR(-EOPNOTSUPP);
4330
4331 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
4332 CSS_TASK_ITER_THREADED);
4333 }
4334
4335 static int cgroup_procs_show(struct seq_file *s, void *v)
4336 {
4337 seq_printf(s, "%d\n", task_pid_vnr(v));
4338 return 0;
4339 }
4340
4341 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
4342 struct cgroup *dst_cgrp,
4343 struct super_block *sb)
4344 {
4345 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
4346 struct cgroup *com_cgrp = src_cgrp;
4347 struct inode *inode;
4348 int ret;
4349
4350 lockdep_assert_held(&cgroup_mutex);
4351
4352 /* find the common ancestor */
4353 while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
4354 com_cgrp = cgroup_parent(com_cgrp);
4355
4356 /* %current should be authorized to migrate to the common ancestor */
4357 inode = kernfs_get_inode(sb, com_cgrp->procs_file.kn);
4358 if (!inode)
4359 return -ENOMEM;
4360
4361 ret = inode_permission(inode, MAY_WRITE);
4362 iput(inode);
4363 if (ret)
4364 return ret;
4365
4366 /*
4367 * If namespaces are delegation boundaries, %current must be able
4368 * to see both source and destination cgroups from its namespace.
4369 */
4370 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
4371 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
4372 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
4373 return -ENOENT;
4374
4375 return 0;
4376 }
4377
4378 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
4379 char *buf, size_t nbytes, loff_t off)
4380 {
4381 struct cgroup *src_cgrp, *dst_cgrp;
4382 struct task_struct *task;
4383 ssize_t ret;
4384
4385 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4386 if (!dst_cgrp)
4387 return -ENODEV;
4388
4389 task = cgroup_procs_write_start(buf, true);
4390 ret = PTR_ERR_OR_ZERO(task);
4391 if (ret)
4392 goto out_unlock;
4393
4394 /* find the source cgroup */
4395 spin_lock_irq(&css_set_lock);
4396 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4397 spin_unlock_irq(&css_set_lock);
4398
4399 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4400 of->file->f_path.dentry->d_sb);
4401 if (ret)
4402 goto out_finish;
4403
4404 ret = cgroup_attach_task(dst_cgrp, task, true);
4405
4406 out_finish:
4407 cgroup_procs_write_finish(task);
4408 out_unlock:
4409 cgroup_kn_unlock(of->kn);
4410
4411 return ret ?: nbytes;
4412 }
4413
4414 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
4415 {
4416 return __cgroup_procs_start(s, pos, 0);
4417 }
4418
4419 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
4420 char *buf, size_t nbytes, loff_t off)
4421 {
4422 struct cgroup *src_cgrp, *dst_cgrp;
4423 struct task_struct *task;
4424 ssize_t ret;
4425
4426 buf = strstrip(buf);
4427
4428 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4429 if (!dst_cgrp)
4430 return -ENODEV;
4431
4432 task = cgroup_procs_write_start(buf, false);
4433 ret = PTR_ERR_OR_ZERO(task);
4434 if (ret)
4435 goto out_unlock;
4436
4437 /* find the source cgroup */
4438 spin_lock_irq(&css_set_lock);
4439 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4440 spin_unlock_irq(&css_set_lock);
4441
4442 /* thread migrations follow the cgroup.procs delegation rule */
4443 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4444 of->file->f_path.dentry->d_sb);
4445 if (ret)
4446 goto out_finish;
4447
4448 /* and must be contained in the same domain */
4449 ret = -EOPNOTSUPP;
4450 if (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp)
4451 goto out_finish;
4452
4453 ret = cgroup_attach_task(dst_cgrp, task, false);
4454
4455 out_finish:
4456 cgroup_procs_write_finish(task);
4457 out_unlock:
4458 cgroup_kn_unlock(of->kn);
4459
4460 return ret ?: nbytes;
4461 }
4462
4463 /* cgroup core interface files for the default hierarchy */
4464 static struct cftype cgroup_base_files[] = {
4465 {
4466 .name = "cgroup.type",
4467 .flags = CFTYPE_NOT_ON_ROOT,
4468 .seq_show = cgroup_type_show,
4469 .write = cgroup_type_write,
4470 },
4471 {
4472 .name = "cgroup.procs",
4473 .flags = CFTYPE_NS_DELEGATABLE,
4474 .file_offset = offsetof(struct cgroup, procs_file),
4475 .release = cgroup_procs_release,
4476 .seq_start = cgroup_procs_start,
4477 .seq_next = cgroup_procs_next,
4478 .seq_show = cgroup_procs_show,
4479 .write = cgroup_procs_write,
4480 },
4481 {
4482 .name = "cgroup.threads",
4483 .release = cgroup_procs_release,
4484 .seq_start = cgroup_threads_start,
4485 .seq_next = cgroup_procs_next,
4486 .seq_show = cgroup_procs_show,
4487 .write = cgroup_threads_write,
4488 },
4489 {
4490 .name = "cgroup.controllers",
4491 .seq_show = cgroup_controllers_show,
4492 },
4493 {
4494 .name = "cgroup.subtree_control",
4495 .flags = CFTYPE_NS_DELEGATABLE,
4496 .seq_show = cgroup_subtree_control_show,
4497 .write = cgroup_subtree_control_write,
4498 },
4499 {
4500 .name = "cgroup.events",
4501 .flags = CFTYPE_NOT_ON_ROOT,
4502 .file_offset = offsetof(struct cgroup, events_file),
4503 .seq_show = cgroup_events_show,
4504 },
4505 {
4506 .name = "cgroup.max.descendants",
4507 .seq_show = cgroup_max_descendants_show,
4508 .write = cgroup_max_descendants_write,
4509 },
4510 {
4511 .name = "cgroup.max.depth",
4512 .seq_show = cgroup_max_depth_show,
4513 .write = cgroup_max_depth_write,
4514 },
4515 {
4516 .name = "cgroup.stat",
4517 .seq_show = cgroup_stat_show,
4518 },
4519 #ifdef CONFIG_PSI
4520 {
4521 .name = "io.pressure",
4522 .flags = CFTYPE_NOT_ON_ROOT,
4523 .seq_show = cgroup_io_pressure_show,
4524 .write = cgroup_io_pressure_write,
4525 .poll = cgroup_pressure_poll,
4526 .release = cgroup_pressure_release,
4527 },
4528 {
4529 .name = "memory.pressure",
4530 .flags = CFTYPE_NOT_ON_ROOT,
4531 .seq_show = cgroup_memory_pressure_show,
4532 .write = cgroup_memory_pressure_write,
4533 .poll = cgroup_pressure_poll,
4534 .release = cgroup_pressure_release,
4535 },
4536 {
4537 .name = "cpu.pressure",
4538 .flags = CFTYPE_NOT_ON_ROOT,
4539 .seq_show = cgroup_cpu_pressure_show,
4540 .write = cgroup_cpu_pressure_write,
4541 .poll = cgroup_pressure_poll,
4542 .release = cgroup_pressure_release,
4543 },
4544 #endif /* CONFIG_PSI */
4545 { } /* terminate */
4546 };
4547
4548 /*
4549 * css destruction is four-stage process.
4550 *
4551 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4552 * Implemented in kill_css().
4553 *
4554 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4555 * and thus css_tryget_online() is guaranteed to fail, the css can be
4556 * offlined by invoking offline_css(). After offlining, the base ref is
4557 * put. Implemented in css_killed_work_fn().
4558 *
4559 * 3. When the percpu_ref reaches zero, the only possible remaining
4560 * accessors are inside RCU read sections. css_release() schedules the
4561 * RCU callback.
4562 *
4563 * 4. After the grace period, the css can be freed. Implemented in
4564 * css_free_work_fn().
4565 *
4566 * It is actually hairier because both step 2 and 4 require process context
4567 * and thus involve punting to css->destroy_work adding two additional
4568 * steps to the already complex sequence.
4569 */
4570 static void css_free_work_fn(struct work_struct *work)
4571 {
4572 struct cgroup_subsys_state *css =
4573 container_of(work, struct cgroup_subsys_state, destroy_work);
4574 struct cgroup_subsys *ss = css->ss;
4575 struct cgroup *cgrp = css->cgroup;
4576
4577 percpu_ref_exit(&css->refcnt);
4578
4579 if (ss) {
4580 /* css free path */
4581 struct cgroup_subsys_state *parent = css->parent;
4582 int id = css->id;
4583
4584 ss->css_free(css);
4585 cgroup_idr_remove(&ss->css_idr, id);
4586 cgroup_put(cgrp);
4587
4588 if (parent)
4589 css_put(parent);
4590 } else {
4591 /* cgroup free path */
4592 atomic_dec(&cgrp->root->nr_cgrps);
4593 cgroup1_pidlist_destroy_all(cgrp);
4594 cancel_work_sync(&cgrp->release_agent_work);
4595
4596 if (cgroup_parent(cgrp)) {
4597 /*
4598 * We get a ref to the parent, and put the ref when
4599 * this cgroup is being freed, so it's guaranteed
4600 * that the parent won't be destroyed before its
4601 * children.
4602 */
4603 cgroup_put(cgroup_parent(cgrp));
4604 kernfs_put(cgrp->kn);
4605 if (cgroup_on_dfl(cgrp))
4606 psi_cgroup_free(cgrp);
4607 kfree(cgrp);
4608 } else {
4609 /*
4610 * This is root cgroup's refcnt reaching zero,
4611 * which indicates that the root should be
4612 * released.
4613 */
4614 cgroup_destroy_root(cgrp->root);
4615 }
4616 }
4617 }
4618
4619 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4620 {
4621 struct cgroup_subsys_state *css =
4622 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4623
4624 INIT_WORK(&css->destroy_work, css_free_work_fn);
4625 queue_work(cgroup_destroy_wq, &css->destroy_work);
4626 }
4627
4628 static void css_release_work_fn(struct work_struct *work)
4629 {
4630 struct cgroup_subsys_state *css =
4631 container_of(work, struct cgroup_subsys_state, destroy_work);
4632 struct cgroup_subsys *ss = css->ss;
4633 struct cgroup *cgrp = css->cgroup;
4634
4635 mutex_lock(&cgroup_mutex);
4636
4637 css->flags |= CSS_RELEASED;
4638 list_del_rcu(&css->sibling);
4639
4640 if (ss) {
4641 /* css release path */
4642 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4643 if (ss->css_released)
4644 ss->css_released(css);
4645 } else {
4646 struct cgroup *tcgrp;
4647
4648 /* cgroup release path */
4649 trace_cgroup_release(cgrp);
4650
4651 for (tcgrp = cgroup_parent(cgrp); tcgrp;
4652 tcgrp = cgroup_parent(tcgrp))
4653 tcgrp->nr_dying_descendants--;
4654
4655 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4656 cgrp->id = -1;
4657
4658 /*
4659 * There are two control paths which try to determine
4660 * cgroup from dentry without going through kernfs -
4661 * cgroupstats_build() and css_tryget_online_from_dir().
4662 * Those are supported by RCU protecting clearing of
4663 * cgrp->kn->priv backpointer.
4664 */
4665 if (cgrp->kn)
4666 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
4667 NULL);
4668
4669 cgroup_bpf_put(cgrp);
4670 }
4671
4672 mutex_unlock(&cgroup_mutex);
4673
4674 call_rcu(&css->rcu_head, css_free_rcu_fn);
4675 }
4676
4677 static void css_release(struct percpu_ref *ref)
4678 {
4679 struct cgroup_subsys_state *css =
4680 container_of(ref, struct cgroup_subsys_state, refcnt);
4681
4682 INIT_WORK(&css->destroy_work, css_release_work_fn);
4683 queue_work(cgroup_destroy_wq, &css->destroy_work);
4684 }
4685
4686 static void init_and_link_css(struct cgroup_subsys_state *css,
4687 struct cgroup_subsys *ss, struct cgroup *cgrp)
4688 {
4689 lockdep_assert_held(&cgroup_mutex);
4690
4691 cgroup_get_live(cgrp);
4692
4693 memset(css, 0, sizeof(*css));
4694 css->cgroup = cgrp;
4695 css->ss = ss;
4696 css->id = -1;
4697 INIT_LIST_HEAD(&css->sibling);
4698 INIT_LIST_HEAD(&css->children);
4699 css->serial_nr = css_serial_nr_next++;
4700 atomic_set(&css->online_cnt, 0);
4701
4702 if (cgroup_parent(cgrp)) {
4703 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4704 css_get(css->parent);
4705 }
4706
4707 BUG_ON(cgroup_css(cgrp, ss));
4708 }
4709
4710 /* invoke ->css_online() on a new CSS and mark it online if successful */
4711 static int online_css(struct cgroup_subsys_state *css)
4712 {
4713 struct cgroup_subsys *ss = css->ss;
4714 int ret = 0;
4715
4716 lockdep_assert_held(&cgroup_mutex);
4717
4718 if (ss->css_online)
4719 ret = ss->css_online(css);
4720 if (!ret) {
4721 css->flags |= CSS_ONLINE;
4722 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4723
4724 atomic_inc(&css->online_cnt);
4725 if (css->parent)
4726 atomic_inc(&css->parent->online_cnt);
4727 }
4728 return ret;
4729 }
4730
4731 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4732 static void offline_css(struct cgroup_subsys_state *css)
4733 {
4734 struct cgroup_subsys *ss = css->ss;
4735
4736 lockdep_assert_held(&cgroup_mutex);
4737
4738 if (!(css->flags & CSS_ONLINE))
4739 return;
4740
4741 if (ss->css_offline)
4742 ss->css_offline(css);
4743
4744 css->flags &= ~CSS_ONLINE;
4745 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4746
4747 wake_up_all(&css->cgroup->offline_waitq);
4748 }
4749
4750 /**
4751 * css_create - create a cgroup_subsys_state
4752 * @cgrp: the cgroup new css will be associated with
4753 * @ss: the subsys of new css
4754 *
4755 * Create a new css associated with @cgrp - @ss pair. On success, the new
4756 * css is online and installed in @cgrp. This function doesn't create the
4757 * interface files. Returns 0 on success, -errno on failure.
4758 */
4759 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
4760 struct cgroup_subsys *ss)
4761 {
4762 struct cgroup *parent = cgroup_parent(cgrp);
4763 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4764 struct cgroup_subsys_state *css;
4765 int err;
4766
4767 lockdep_assert_held(&cgroup_mutex);
4768
4769 css = ss->css_alloc(parent_css);
4770 if (!css)
4771 css = ERR_PTR(-ENOMEM);
4772 if (IS_ERR(css))
4773 return css;
4774
4775 init_and_link_css(css, ss, cgrp);
4776
4777 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4778 if (err)
4779 goto err_free_css;
4780
4781 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
4782 if (err < 0)
4783 goto err_free_css;
4784 css->id = err;
4785
4786 /* @css is ready to be brought online now, make it visible */
4787 list_add_tail_rcu(&css->sibling, &parent_css->children);
4788 cgroup_idr_replace(&ss->css_idr, css, css->id);
4789
4790 err = online_css(css);
4791 if (err)
4792 goto err_list_del;
4793
4794 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4795 cgroup_parent(parent)) {
4796 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4797 current->comm, current->pid, ss->name);
4798 if (!strcmp(ss->name, "memory"))
4799 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4800 ss->warned_broken_hierarchy = true;
4801 }
4802
4803 return css;
4804
4805 err_list_del:
4806 list_del_rcu(&css->sibling);
4807 err_free_css:
4808 call_rcu(&css->rcu_head, css_free_rcu_fn);
4809 return ERR_PTR(err);
4810 }
4811
4812 /*
4813 * The returned cgroup is fully initialized including its control mask, but
4814 * it isn't associated with its kernfs_node and doesn't have the control
4815 * mask applied.
4816 */
4817 static struct cgroup *cgroup_create(struct cgroup *parent)
4818 {
4819 struct cgroup_root *root = parent->root;
4820 struct cgroup *cgrp, *tcgrp;
4821 int level = parent->level + 1;
4822 int ret;
4823
4824 /* allocate the cgroup and its ID, 0 is reserved for the root */
4825 cgrp = kzalloc(sizeof(*cgrp) +
4826 sizeof(cgrp->ancestor_ids[0]) * (level + 1), GFP_KERNEL);
4827 if (!cgrp)
4828 return ERR_PTR(-ENOMEM);
4829
4830 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
4831 if (ret)
4832 goto out_free_cgrp;
4833
4834 /*
4835 * Temporarily set the pointer to NULL, so idr_find() won't return
4836 * a half-baked cgroup.
4837 */
4838 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
4839 if (cgrp->id < 0) {
4840 ret = -ENOMEM;
4841 goto out_cancel_ref;
4842 }
4843
4844 init_cgroup_housekeeping(cgrp);
4845
4846 cgrp->self.parent = &parent->self;
4847 cgrp->root = root;
4848 cgrp->level = level;
4849
4850 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
4851 cgrp->ancestor_ids[tcgrp->level] = tcgrp->id;
4852
4853 if (tcgrp != cgrp)
4854 tcgrp->nr_descendants++;
4855 }
4856
4857 if (notify_on_release(parent))
4858 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4859
4860 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4861 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4862
4863 cgrp->self.serial_nr = css_serial_nr_next++;
4864
4865 /* allocation complete, commit to creation */
4866 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4867 atomic_inc(&root->nr_cgrps);
4868 cgroup_get_live(parent);
4869
4870 /*
4871 * @cgrp is now fully operational. If something fails after this
4872 * point, it'll be released via the normal destruction path.
4873 */
4874 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4875
4876 /*
4877 * On the default hierarchy, a child doesn't automatically inherit
4878 * subtree_control from the parent. Each is configured manually.
4879 */
4880 if (!cgroup_on_dfl(cgrp))
4881 cgrp->subtree_control = cgroup_control(cgrp);
4882
4883 if (cgroup_on_dfl(cgrp)) {
4884 ret = psi_cgroup_alloc(cgrp);
4885 if (ret)
4886 goto out_idr_free;
4887 }
4888
4889 if (parent)
4890 cgroup_bpf_inherit(cgrp, parent);
4891
4892 cgroup_propagate_control(cgrp);
4893
4894 return cgrp;
4895
4896 out_idr_free:
4897 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4898 out_cancel_ref:
4899 percpu_ref_exit(&cgrp->self.refcnt);
4900 out_free_cgrp:
4901 kfree(cgrp);
4902 return ERR_PTR(ret);
4903 }
4904
4905 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
4906 {
4907 struct cgroup *cgroup;
4908 int ret = false;
4909 int level = 1;
4910
4911 lockdep_assert_held(&cgroup_mutex);
4912
4913 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
4914 if (cgroup->nr_descendants >= cgroup->max_descendants)
4915 goto fail;
4916
4917 if (level > cgroup->max_depth)
4918 goto fail;
4919
4920 level++;
4921 }
4922
4923 ret = true;
4924 fail:
4925 return ret;
4926 }
4927
4928 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
4929 {
4930 struct cgroup *parent, *cgrp;
4931 struct kernfs_node *kn;
4932 int ret;
4933
4934 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
4935 if (strchr(name, '\n'))
4936 return -EINVAL;
4937
4938 parent = cgroup_kn_lock_live(parent_kn, false);
4939 if (!parent)
4940 return -ENODEV;
4941
4942 if (!cgroup_check_hierarchy_limits(parent)) {
4943 ret = -EAGAIN;
4944 goto out_unlock;
4945 }
4946
4947 cgrp = cgroup_create(parent);
4948 if (IS_ERR(cgrp)) {
4949 ret = PTR_ERR(cgrp);
4950 goto out_unlock;
4951 }
4952
4953 /* create the directory */
4954 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4955 if (IS_ERR(kn)) {
4956 ret = PTR_ERR(kn);
4957 goto out_destroy;
4958 }
4959 cgrp->kn = kn;
4960
4961 /*
4962 * This extra ref will be put in cgroup_free_fn() and guarantees
4963 * that @cgrp->kn is always accessible.
4964 */
4965 kernfs_get(kn);
4966
4967 ret = cgroup_kn_set_ugid(kn);
4968 if (ret)
4969 goto out_destroy;
4970
4971 ret = css_populate_dir(&cgrp->self);
4972 if (ret)
4973 goto out_destroy;
4974
4975 ret = cgroup_apply_control_enable(cgrp);
4976 if (ret)
4977 goto out_destroy;
4978
4979 trace_cgroup_mkdir(cgrp);
4980
4981 /* let's create and online css's */
4982 kernfs_activate(kn);
4983
4984 ret = 0;
4985 goto out_unlock;
4986
4987 out_destroy:
4988 cgroup_destroy_locked(cgrp);
4989 out_unlock:
4990 cgroup_kn_unlock(parent_kn);
4991 return ret;
4992 }
4993
4994 /*
4995 * This is called when the refcnt of a css is confirmed to be killed.
4996 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
4997 * initate destruction and put the css ref from kill_css().
4998 */
4999 static void css_killed_work_fn(struct work_struct *work)
5000 {
5001 struct cgroup_subsys_state *css =
5002 container_of(work, struct cgroup_subsys_state, destroy_work);
5003
5004 mutex_lock(&cgroup_mutex);
5005
5006 do {
5007 offline_css(css);
5008 css_put(css);
5009 /* @css can't go away while we're holding cgroup_mutex */
5010 css = css->parent;
5011 } while (css && atomic_dec_and_test(&css->online_cnt));
5012
5013 mutex_unlock(&cgroup_mutex);
5014 }
5015
5016 /* css kill confirmation processing requires process context, bounce */
5017 static void css_killed_ref_fn(struct percpu_ref *ref)
5018 {
5019 struct cgroup_subsys_state *css =
5020 container_of(ref, struct cgroup_subsys_state, refcnt);
5021
5022 if (atomic_dec_and_test(&css->online_cnt)) {
5023 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5024 queue_work(cgroup_destroy_wq, &css->destroy_work);
5025 }
5026 }
5027
5028 /**
5029 * kill_css - destroy a css
5030 * @css: css to destroy
5031 *
5032 * This function initiates destruction of @css by removing cgroup interface
5033 * files and putting its base reference. ->css_offline() will be invoked
5034 * asynchronously once css_tryget_online() is guaranteed to fail and when
5035 * the reference count reaches zero, @css will be released.
5036 */
5037 static void kill_css(struct cgroup_subsys_state *css)
5038 {
5039 lockdep_assert_held(&cgroup_mutex);
5040
5041 if (css->flags & CSS_DYING)
5042 return;
5043
5044 css->flags |= CSS_DYING;
5045
5046 /*
5047 * This must happen before css is disassociated with its cgroup.
5048 * See seq_css() for details.
5049 */
5050 css_clear_dir(css);
5051
5052 /*
5053 * Killing would put the base ref, but we need to keep it alive
5054 * until after ->css_offline().
5055 */
5056 css_get(css);
5057
5058 /*
5059 * cgroup core guarantees that, by the time ->css_offline() is
5060 * invoked, no new css reference will be given out via
5061 * css_tryget_online(). We can't simply call percpu_ref_kill() and
5062 * proceed to offlining css's because percpu_ref_kill() doesn't
5063 * guarantee that the ref is seen as killed on all CPUs on return.
5064 *
5065 * Use percpu_ref_kill_and_confirm() to get notifications as each
5066 * css is confirmed to be seen as killed on all CPUs.
5067 */
5068 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5069 }
5070
5071 /**
5072 * cgroup_destroy_locked - the first stage of cgroup destruction
5073 * @cgrp: cgroup to be destroyed
5074 *
5075 * css's make use of percpu refcnts whose killing latency shouldn't be
5076 * exposed to userland and are RCU protected. Also, cgroup core needs to
5077 * guarantee that css_tryget_online() won't succeed by the time
5078 * ->css_offline() is invoked. To satisfy all the requirements,
5079 * destruction is implemented in the following two steps.
5080 *
5081 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
5082 * userland visible parts and start killing the percpu refcnts of
5083 * css's. Set up so that the next stage will be kicked off once all
5084 * the percpu refcnts are confirmed to be killed.
5085 *
5086 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5087 * rest of destruction. Once all cgroup references are gone, the
5088 * cgroup is RCU-freed.
5089 *
5090 * This function implements s1. After this step, @cgrp is gone as far as
5091 * the userland is concerned and a new cgroup with the same name may be
5092 * created. As cgroup doesn't care about the names internally, this
5093 * doesn't cause any problem.
5094 */
5095 static int cgroup_destroy_locked(struct cgroup *cgrp)
5096 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5097 {
5098 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5099 struct cgroup_subsys_state *css;
5100 struct cgrp_cset_link *link;
5101 int ssid;
5102
5103 lockdep_assert_held(&cgroup_mutex);
5104
5105 /*
5106 * Only migration can raise populated from zero and we're already
5107 * holding cgroup_mutex.
5108 */
5109 if (cgroup_is_populated(cgrp))
5110 return -EBUSY;
5111
5112 /*
5113 * Make sure there's no live children. We can't test emptiness of
5114 * ->self.children as dead children linger on it while being
5115 * drained; otherwise, "rmdir parent/child parent" may fail.
5116 */
5117 if (css_has_online_children(&cgrp->self))
5118 return -EBUSY;
5119
5120 /*
5121 * Mark @cgrp and the associated csets dead. The former prevents
5122 * further task migration and child creation by disabling
5123 * cgroup_lock_live_group(). The latter makes the csets ignored by
5124 * the migration path.
5125 */
5126 cgrp->self.flags &= ~CSS_ONLINE;
5127
5128 spin_lock_irq(&css_set_lock);
5129 list_for_each_entry(link, &cgrp->cset_links, cset_link)
5130 link->cset->dead = true;
5131 spin_unlock_irq(&css_set_lock);
5132
5133 /* initiate massacre of all css's */
5134 for_each_css(css, ssid, cgrp)
5135 kill_css(css);
5136
5137 /*
5138 * Remove @cgrp directory along with the base files. @cgrp has an
5139 * extra ref on its kn.
5140 */
5141 kernfs_remove(cgrp->kn);
5142
5143 if (parent && cgroup_is_threaded(cgrp))
5144 parent->nr_threaded_children--;
5145
5146 for (tcgrp = cgroup_parent(cgrp); tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5147 tcgrp->nr_descendants--;
5148 tcgrp->nr_dying_descendants++;
5149 }
5150
5151 cgroup1_check_for_release(parent);
5152
5153 /* put the base reference */
5154 percpu_ref_kill(&cgrp->self.refcnt);
5155
5156 return 0;
5157 };
5158
5159 int cgroup_rmdir(struct kernfs_node *kn)
5160 {
5161 struct cgroup *cgrp;
5162 int ret = 0;
5163
5164 cgrp = cgroup_kn_lock_live(kn, false);
5165 if (!cgrp)
5166 return 0;
5167
5168 ret = cgroup_destroy_locked(cgrp);
5169
5170 if (!ret)
5171 trace_cgroup_rmdir(cgrp);
5172
5173 cgroup_kn_unlock(kn);
5174 return ret;
5175 }
5176
5177 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5178 .show_options = cgroup_show_options,
5179 .remount_fs = cgroup_remount,
5180 .mkdir = cgroup_mkdir,
5181 .rmdir = cgroup_rmdir,
5182 .show_path = cgroup_show_path,
5183 };
5184
5185 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5186 {
5187 struct cgroup_subsys_state *css;
5188
5189 pr_debug("Initializing cgroup subsys %s\n", ss->name);
5190
5191 mutex_lock(&cgroup_mutex);
5192
5193 idr_init(&ss->css_idr);
5194 INIT_LIST_HEAD(&ss->cfts);
5195
5196 /* Create the root cgroup state for this subsystem */
5197 ss->root = &cgrp_dfl_root;
5198 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5199 /* We don't handle early failures gracefully */
5200 BUG_ON(IS_ERR(css));
5201 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5202
5203 /*
5204 * Root csses are never destroyed and we can't initialize
5205 * percpu_ref during early init. Disable refcnting.
5206 */
5207 css->flags |= CSS_NO_REF;
5208
5209 if (early) {
5210 /* allocation can't be done safely during early init */
5211 css->id = 1;
5212 } else {
5213 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5214 BUG_ON(css->id < 0);
5215 }
5216
5217 /* Update the init_css_set to contain a subsys
5218 * pointer to this state - since the subsystem is
5219 * newly registered, all tasks and hence the
5220 * init_css_set is in the subsystem's root cgroup. */
5221 init_css_set.subsys[ss->id] = css;
5222
5223 have_fork_callback |= (bool)ss->fork << ss->id;
5224 have_exit_callback |= (bool)ss->exit << ss->id;
5225 have_release_callback |= (bool)ss->release << ss->id;
5226 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5227
5228 /* At system boot, before all subsystems have been
5229 * registered, no tasks have been forked, so we don't
5230 * need to invoke fork callbacks here. */
5231 BUG_ON(!list_empty(&init_task.tasks));
5232
5233 BUG_ON(online_css(css));
5234
5235 mutex_unlock(&cgroup_mutex);
5236 }
5237
5238 /**
5239 * cgroup_init_early - cgroup initialization at system boot
5240 *
5241 * Initialize cgroups at system boot, and initialize any
5242 * subsystems that request early init.
5243 */
5244 int __init cgroup_init_early(void)
5245 {
5246 static struct cgroup_sb_opts __initdata opts;
5247 struct cgroup_subsys *ss;
5248 int i;
5249
5250 init_cgroup_root(&cgrp_dfl_root, &opts);
5251 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5252
5253 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5254
5255 for_each_subsys(ss, i) {
5256 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5257 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
5258 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5259 ss->id, ss->name);
5260 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5261 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5262
5263 ss->id = i;
5264 ss->name = cgroup_subsys_name[i];
5265 if (!ss->legacy_name)
5266 ss->legacy_name = cgroup_subsys_name[i];
5267
5268 if (ss->early_init)
5269 cgroup_init_subsys(ss, true);
5270 }
5271 return 0;
5272 }
5273
5274 static u16 cgroup_disable_mask __initdata;
5275
5276 /**
5277 * cgroup_init - cgroup initialization
5278 *
5279 * Register cgroup filesystem and /proc file, and initialize
5280 * any subsystems that didn't request early init.
5281 */
5282 int __init cgroup_init(void)
5283 {
5284 struct cgroup_subsys *ss;
5285 int ssid;
5286
5287 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
5288 BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
5289 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
5290 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
5291
5292 /*
5293 * The latency of the synchronize_sched() is too high for cgroups,
5294 * avoid it at the cost of forcing all readers into the slow path.
5295 */
5296 rcu_sync_enter_start(&cgroup_threadgroup_rwsem.rss);
5297
5298 get_user_ns(init_cgroup_ns.user_ns);
5299
5300 mutex_lock(&cgroup_mutex);
5301
5302 /*
5303 * Add init_css_set to the hash table so that dfl_root can link to
5304 * it during init.
5305 */
5306 hash_add(css_set_table, &init_css_set.hlist,
5307 css_set_hash(init_css_set.subsys));
5308
5309 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0, 0));
5310
5311 mutex_unlock(&cgroup_mutex);
5312
5313 for_each_subsys(ss, ssid) {
5314 if (ss->early_init) {
5315 struct cgroup_subsys_state *css =
5316 init_css_set.subsys[ss->id];
5317
5318 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5319 GFP_KERNEL);
5320 BUG_ON(css->id < 0);
5321 } else {
5322 cgroup_init_subsys(ss, false);
5323 }
5324
5325 list_add_tail(&init_css_set.e_cset_node[ssid],
5326 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5327
5328 /*
5329 * Setting dfl_root subsys_mask needs to consider the
5330 * disabled flag and cftype registration needs kmalloc,
5331 * both of which aren't available during early_init.
5332 */
5333 if (cgroup_disable_mask & (1 << ssid)) {
5334 static_branch_disable(cgroup_subsys_enabled_key[ssid]);
5335 printk(KERN_INFO "Disabling %s control group subsystem\n",
5336 ss->name);
5337 continue;
5338 }
5339
5340 if (cgroup1_ssid_disabled(ssid))
5341 printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
5342 ss->name);
5343
5344 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5345
5346 /* implicit controllers must be threaded too */
5347 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
5348
5349 if (ss->implicit_on_dfl)
5350 cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
5351 else if (!ss->dfl_cftypes)
5352 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
5353
5354 if (ss->threaded)
5355 cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
5356
5357 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5358 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5359 } else {
5360 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5361 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5362 }
5363
5364 if (ss->bind)
5365 ss->bind(init_css_set.subsys[ssid]);
5366
5367 mutex_lock(&cgroup_mutex);
5368 css_populate_dir(init_css_set.subsys[ssid]);
5369 mutex_unlock(&cgroup_mutex);
5370 }
5371
5372 /* init_css_set.subsys[] has been updated, re-hash */
5373 hash_del(&init_css_set.hlist);
5374 hash_add(css_set_table, &init_css_set.hlist,
5375 css_set_hash(init_css_set.subsys));
5376
5377 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
5378 WARN_ON(register_filesystem(&cgroup_fs_type));
5379 WARN_ON(register_filesystem(&cgroup2_fs_type));
5380 WARN_ON(!proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations));
5381
5382 return 0;
5383 }
5384
5385 static int __init cgroup_wq_init(void)
5386 {
5387 /*
5388 * There isn't much point in executing destruction path in
5389 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5390 * Use 1 for @max_active.
5391 *
5392 * We would prefer to do this in cgroup_init() above, but that
5393 * is called before init_workqueues(): so leave this until after.
5394 */
5395 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5396 BUG_ON(!cgroup_destroy_wq);
5397 return 0;
5398 }
5399 core_initcall(cgroup_wq_init);
5400
5401 void cgroup_path_from_kernfs_id(const union kernfs_node_id *id,
5402 char *buf, size_t buflen)
5403 {
5404 struct kernfs_node *kn;
5405
5406 kn = kernfs_get_node_by_id(cgrp_dfl_root.kf_root, id);
5407 if (!kn)
5408 return;
5409 kernfs_path(kn, buf, buflen);
5410 kernfs_put(kn);
5411 }
5412
5413 /*
5414 * proc_cgroup_show()
5415 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5416 * - Used for /proc/<pid>/cgroup.
5417 */
5418 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5419 struct pid *pid, struct task_struct *tsk)
5420 {
5421 char *buf;
5422 int retval;
5423 struct cgroup_root *root;
5424
5425 retval = -ENOMEM;
5426 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5427 if (!buf)
5428 goto out;
5429
5430 mutex_lock(&cgroup_mutex);
5431 spin_lock_irq(&css_set_lock);
5432
5433 for_each_root(root) {
5434 struct cgroup_subsys *ss;
5435 struct cgroup *cgrp;
5436 int ssid, count = 0;
5437
5438 if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
5439 continue;
5440
5441 seq_printf(m, "%d:", root->hierarchy_id);
5442 if (root != &cgrp_dfl_root)
5443 for_each_subsys(ss, ssid)
5444 if (root->subsys_mask & (1 << ssid))
5445 seq_printf(m, "%s%s", count++ ? "," : "",
5446 ss->legacy_name);
5447 if (strlen(root->name))
5448 seq_printf(m, "%sname=%s", count ? "," : "",
5449 root->name);
5450 seq_putc(m, ':');
5451
5452 cgrp = task_cgroup_from_root(tsk, root);
5453
5454 /*
5455 * On traditional hierarchies, all zombie tasks show up as
5456 * belonging to the root cgroup. On the default hierarchy,
5457 * while a zombie doesn't show up in "cgroup.procs" and
5458 * thus can't be migrated, its /proc/PID/cgroup keeps
5459 * reporting the cgroup it belonged to before exiting. If
5460 * the cgroup is removed before the zombie is reaped,
5461 * " (deleted)" is appended to the cgroup path.
5462 */
5463 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
5464 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
5465 current->nsproxy->cgroup_ns);
5466 if (retval >= PATH_MAX)
5467 retval = -ENAMETOOLONG;
5468 if (retval < 0)
5469 goto out_unlock;
5470
5471 seq_puts(m, buf);
5472 } else {
5473 seq_puts(m, "/");
5474 }
5475
5476 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
5477 seq_puts(m, " (deleted)\n");
5478 else
5479 seq_putc(m, '\n');
5480 }
5481
5482 retval = 0;
5483 out_unlock:
5484 spin_unlock_irq(&css_set_lock);
5485 mutex_unlock(&cgroup_mutex);
5486 kfree(buf);
5487 out:
5488 return retval;
5489 }
5490
5491 /**
5492 * cgroup_fork - initialize cgroup related fields during copy_process()
5493 * @child: pointer to task_struct of forking parent process.
5494 *
5495 * A task is associated with the init_css_set until cgroup_post_fork()
5496 * attaches it to the parent's css_set. Empty cg_list indicates that
5497 * @child isn't holding reference to its css_set.
5498 */
5499 void cgroup_fork(struct task_struct *child)
5500 {
5501 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5502 INIT_LIST_HEAD(&child->cg_list);
5503 }
5504
5505 /**
5506 * cgroup_can_fork - called on a new task before the process is exposed
5507 * @child: the task in question.
5508 *
5509 * This calls the subsystem can_fork() callbacks. If the can_fork() callback
5510 * returns an error, the fork aborts with that error code. This allows for
5511 * a cgroup subsystem to conditionally allow or deny new forks.
5512 */
5513 int cgroup_can_fork(struct task_struct *child)
5514 {
5515 struct cgroup_subsys *ss;
5516 int i, j, ret;
5517
5518 do_each_subsys_mask(ss, i, have_canfork_callback) {
5519 ret = ss->can_fork(child);
5520 if (ret)
5521 goto out_revert;
5522 } while_each_subsys_mask();
5523
5524 return 0;
5525
5526 out_revert:
5527 for_each_subsys(ss, j) {
5528 if (j >= i)
5529 break;
5530 if (ss->cancel_fork)
5531 ss->cancel_fork(child);
5532 }
5533
5534 return ret;
5535 }
5536
5537 /**
5538 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
5539 * @child: the task in question
5540 *
5541 * This calls the cancel_fork() callbacks if a fork failed *after*
5542 * cgroup_can_fork() succeded.
5543 */
5544 void cgroup_cancel_fork(struct task_struct *child)
5545 {
5546 struct cgroup_subsys *ss;
5547 int i;
5548
5549 for_each_subsys(ss, i)
5550 if (ss->cancel_fork)
5551 ss->cancel_fork(child);
5552 }
5553
5554 /**
5555 * cgroup_post_fork - called on a new task after adding it to the task list
5556 * @child: the task in question
5557 *
5558 * Adds the task to the list running through its css_set if necessary and
5559 * call the subsystem fork() callbacks. Has to be after the task is
5560 * visible on the task list in case we race with the first call to
5561 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5562 * list.
5563 */
5564 void cgroup_post_fork(struct task_struct *child)
5565 {
5566 struct cgroup_subsys *ss;
5567 int i;
5568
5569 /*
5570 * This may race against cgroup_enable_task_cg_lists(). As that
5571 * function sets use_task_css_set_links before grabbing
5572 * tasklist_lock and we just went through tasklist_lock to add
5573 * @child, it's guaranteed that either we see the set
5574 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5575 * @child during its iteration.
5576 *
5577 * If we won the race, @child is associated with %current's
5578 * css_set. Grabbing css_set_lock guarantees both that the
5579 * association is stable, and, on completion of the parent's
5580 * migration, @child is visible in the source of migration or
5581 * already in the destination cgroup. This guarantee is necessary
5582 * when implementing operations which need to migrate all tasks of
5583 * a cgroup to another.
5584 *
5585 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5586 * will remain in init_css_set. This is safe because all tasks are
5587 * in the init_css_set before cg_links is enabled and there's no
5588 * operation which transfers all tasks out of init_css_set.
5589 */
5590 if (use_task_css_set_links) {
5591 struct css_set *cset;
5592
5593 spin_lock_irq(&css_set_lock);
5594 cset = task_css_set(current);
5595 if (list_empty(&child->cg_list)) {
5596 get_css_set(cset);
5597 cset->nr_tasks++;
5598 css_set_move_task(child, NULL, cset, false);
5599 }
5600 spin_unlock_irq(&css_set_lock);
5601 }
5602
5603 /*
5604 * Call ss->fork(). This must happen after @child is linked on
5605 * css_set; otherwise, @child might change state between ->fork()
5606 * and addition to css_set.
5607 */
5608 do_each_subsys_mask(ss, i, have_fork_callback) {
5609 ss->fork(child);
5610 } while_each_subsys_mask();
5611 }
5612
5613 /**
5614 * cgroup_exit - detach cgroup from exiting task
5615 * @tsk: pointer to task_struct of exiting process
5616 *
5617 * Description: Detach cgroup from @tsk and release it.
5618 *
5619 * Note that cgroups marked notify_on_release force every task in
5620 * them to take the global cgroup_mutex mutex when exiting.
5621 * This could impact scaling on very large systems. Be reluctant to
5622 * use notify_on_release cgroups where very high task exit scaling
5623 * is required on large systems.
5624 *
5625 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5626 * call cgroup_exit() while the task is still competent to handle
5627 * notify_on_release(), then leave the task attached to the root cgroup in
5628 * each hierarchy for the remainder of its exit. No need to bother with
5629 * init_css_set refcnting. init_css_set never goes away and we can't race
5630 * with migration path - PF_EXITING is visible to migration path.
5631 */
5632 void cgroup_exit(struct task_struct *tsk)
5633 {
5634 struct cgroup_subsys *ss;
5635 struct css_set *cset;
5636 int i;
5637
5638 /*
5639 * Unlink from @tsk from its css_set. As migration path can't race
5640 * with us, we can check css_set and cg_list without synchronization.
5641 */
5642 cset = task_css_set(tsk);
5643
5644 if (!list_empty(&tsk->cg_list)) {
5645 spin_lock_irq(&css_set_lock);
5646 css_set_move_task(tsk, cset, NULL, false);
5647 cset->nr_tasks--;
5648 spin_unlock_irq(&css_set_lock);
5649 } else {
5650 get_css_set(cset);
5651 }
5652
5653 /* see cgroup_post_fork() for details */
5654 do_each_subsys_mask(ss, i, have_exit_callback) {
5655 ss->exit(tsk);
5656 } while_each_subsys_mask();
5657 }
5658
5659 void cgroup_release(struct task_struct *task)
5660 {
5661 struct cgroup_subsys *ss;
5662 int ssid;
5663
5664 do_each_subsys_mask(ss, ssid, have_release_callback) {
5665 ss->release(task);
5666 } while_each_subsys_mask();
5667 }
5668
5669 void cgroup_free(struct task_struct *task)
5670 {
5671 struct css_set *cset = task_css_set(task);
5672 put_css_set(cset);
5673 }
5674
5675 static int __init cgroup_disable(char *str)
5676 {
5677 struct cgroup_subsys *ss;
5678 char *token;
5679 int i;
5680
5681 while ((token = strsep(&str, ",")) != NULL) {
5682 if (!*token)
5683 continue;
5684
5685 for_each_subsys(ss, i) {
5686 if (strcmp(token, ss->name) &&
5687 strcmp(token, ss->legacy_name))
5688 continue;
5689 cgroup_disable_mask |= 1 << i;
5690 }
5691 }
5692 return 1;
5693 }
5694 __setup("cgroup_disable=", cgroup_disable);
5695
5696 /**
5697 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5698 * @dentry: directory dentry of interest
5699 * @ss: subsystem of interest
5700 *
5701 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5702 * to get the corresponding css and return it. If such css doesn't exist
5703 * or can't be pinned, an ERR_PTR value is returned.
5704 */
5705 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5706 struct cgroup_subsys *ss)
5707 {
5708 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5709 struct file_system_type *s_type = dentry->d_sb->s_type;
5710 struct cgroup_subsys_state *css = NULL;
5711 struct cgroup *cgrp;
5712
5713 /* is @dentry a cgroup dir? */
5714 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
5715 !kn || kernfs_type(kn) != KERNFS_DIR)
5716 return ERR_PTR(-EBADF);
5717
5718 rcu_read_lock();
5719
5720 /*
5721 * This path doesn't originate from kernfs and @kn could already
5722 * have been or be removed at any point. @kn->priv is RCU
5723 * protected for this access. See css_release_work_fn() for details.
5724 */
5725 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
5726 if (cgrp)
5727 css = cgroup_css(cgrp, ss);
5728
5729 if (!css || !css_tryget_online(css))
5730 css = ERR_PTR(-ENOENT);
5731
5732 rcu_read_unlock();
5733 return css;
5734 }
5735
5736 /**
5737 * css_from_id - lookup css by id
5738 * @id: the cgroup id
5739 * @ss: cgroup subsys to be looked into
5740 *
5741 * Returns the css if there's valid one with @id, otherwise returns NULL.
5742 * Should be called under rcu_read_lock().
5743 */
5744 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5745 {
5746 WARN_ON_ONCE(!rcu_read_lock_held());
5747 return idr_find(&ss->css_idr, id);
5748 }
5749
5750 /**
5751 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
5752 * @path: path on the default hierarchy
5753 *
5754 * Find the cgroup at @path on the default hierarchy, increment its
5755 * reference count and return it. Returns pointer to the found cgroup on
5756 * success, ERR_PTR(-ENOENT) if @path doens't exist and ERR_PTR(-ENOTDIR)
5757 * if @path points to a non-directory.
5758 */
5759 struct cgroup *cgroup_get_from_path(const char *path)
5760 {
5761 struct kernfs_node *kn;
5762 struct cgroup *cgrp;
5763
5764 mutex_lock(&cgroup_mutex);
5765
5766 kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
5767 if (kn) {
5768 if (kernfs_type(kn) == KERNFS_DIR) {
5769 cgrp = kn->priv;
5770 cgroup_get_live(cgrp);
5771 } else {
5772 cgrp = ERR_PTR(-ENOTDIR);
5773 }
5774 kernfs_put(kn);
5775 } else {
5776 cgrp = ERR_PTR(-ENOENT);
5777 }
5778
5779 mutex_unlock(&cgroup_mutex);
5780 return cgrp;
5781 }
5782 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
5783
5784 /**
5785 * cgroup_get_from_fd - get a cgroup pointer from a fd
5786 * @fd: fd obtained by open(cgroup2_dir)
5787 *
5788 * Find the cgroup from a fd which should be obtained
5789 * by opening a cgroup directory. Returns a pointer to the
5790 * cgroup on success. ERR_PTR is returned if the cgroup
5791 * cannot be found.
5792 */
5793 struct cgroup *cgroup_get_from_fd(int fd)
5794 {
5795 struct cgroup_subsys_state *css;
5796 struct cgroup *cgrp;
5797 struct file *f;
5798
5799 f = fget_raw(fd);
5800 if (!f)
5801 return ERR_PTR(-EBADF);
5802
5803 css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
5804 fput(f);
5805 if (IS_ERR(css))
5806 return ERR_CAST(css);
5807
5808 cgrp = css->cgroup;
5809 if (!cgroup_on_dfl(cgrp)) {
5810 cgroup_put(cgrp);
5811 return ERR_PTR(-EBADF);
5812 }
5813
5814 return cgrp;
5815 }
5816 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
5817
5818 /*
5819 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
5820 * definition in cgroup-defs.h.
5821 */
5822 #ifdef CONFIG_SOCK_CGROUP_DATA
5823
5824 #if defined(CONFIG_CGROUP_NET_PRIO) || defined(CONFIG_CGROUP_NET_CLASSID)
5825
5826 DEFINE_SPINLOCK(cgroup_sk_update_lock);
5827 static bool cgroup_sk_alloc_disabled __read_mostly;
5828
5829 void cgroup_sk_alloc_disable(void)
5830 {
5831 if (cgroup_sk_alloc_disabled)
5832 return;
5833 pr_info("cgroup: disabling cgroup2 socket matching due to net_prio or net_cls activation\n");
5834 cgroup_sk_alloc_disabled = true;
5835 }
5836
5837 #else
5838
5839 #define cgroup_sk_alloc_disabled false
5840
5841 #endif
5842
5843 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
5844 {
5845 if (cgroup_sk_alloc_disabled)
5846 return;
5847
5848 /* Socket clone path */
5849 if (skcd->val) {
5850 /*
5851 * We might be cloning a socket which is left in an empty
5852 * cgroup and the cgroup might have already been rmdir'd.
5853 * Don't use cgroup_get_live().
5854 */
5855 cgroup_get(sock_cgroup_ptr(skcd));
5856 return;
5857 }
5858
5859 rcu_read_lock();
5860
5861 while (true) {
5862 struct css_set *cset;
5863
5864 cset = task_css_set(current);
5865 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
5866 skcd->val = (unsigned long)cset->dfl_cgrp;
5867 break;
5868 }
5869 cpu_relax();
5870 }
5871
5872 rcu_read_unlock();
5873 }
5874
5875 void cgroup_sk_free(struct sock_cgroup_data *skcd)
5876 {
5877 cgroup_put(sock_cgroup_ptr(skcd));
5878 }
5879
5880 #endif /* CONFIG_SOCK_CGROUP_DATA */
5881
5882 #ifdef CONFIG_CGROUP_BPF
5883 int cgroup_bpf_update(struct cgroup *cgrp, struct bpf_prog *prog,
5884 enum bpf_attach_type type, bool overridable)
5885 {
5886 struct cgroup *parent = cgroup_parent(cgrp);
5887 int ret;
5888
5889 mutex_lock(&cgroup_mutex);
5890 ret = __cgroup_bpf_update(cgrp, parent, prog, type, overridable);
5891 mutex_unlock(&cgroup_mutex);
5892 return ret;
5893 }
5894 #endif /* CONFIG_CGROUP_BPF */