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

source code of linux/kernel/cgroup/cgroup.c