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