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