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