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