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