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