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