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