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