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 {
2889 struct task_struct *tsk;
2890 pid_t pid;
2891 bool force_migration = false;
2892
2893 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2894 return ERR_PTR(-EINVAL);
2895
2896 /*
2897 * If we migrate a single thread, we don't care about threadgroup
2898 * stability. If the thread is `current`, it won't exit(2) under our
2899 * hands or change PID through exec(2). We exclude
2900 * cgroup_update_dfl_csses and other cgroup_{proc,thread}s_write
2901 * callers by cgroup_mutex.
2902 * Therefore, we can skip the global lock.
2903 */
2904 lockdep_assert_held(&cgroup_mutex);
2905 *threadgroup_locked = pid || threadgroup;
2906 cgroup_attach_lock(*threadgroup_locked);
2907
2908 rcu_read_lock();
2909 if (pid) {
2910 tsk = find_task_by_vpid(pid);
2911 if (!tsk) {
2912 tsk = ERR_PTR(-ESRCH);
2913 goto out_unlock_threadgroup;
2914 }
2915 } else {
2916 tsk = current;
2917 }
2918
2919 if (threadgroup)
2920 tsk = tsk->group_leader;
2921
2922 if (tsk->flags & PF_KTHREAD)
2923 trace_android_rvh_cgroup_force_kthread_migration(tsk, dst_cgrp, &force_migration);
2924
2925 /*
2926 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2927 * If userland migrates such a kthread to a non-root cgroup, it can
2928 * become trapped in a cpuset, or RT kthread may be born in a
2929 * cgroup with no rt_runtime allocated. Just say no.
2930 */
2931 if (!force_migration && (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY))) {
2932 tsk = ERR_PTR(-EINVAL);
2933 goto out_unlock_threadgroup;
2934 }
2935
2936 get_task_struct(tsk);
2937 goto out_unlock_rcu;
2938
2939 out_unlock_threadgroup:
2940 cgroup_attach_unlock(*threadgroup_locked);
2941 *threadgroup_locked = false;
2942 out_unlock_rcu:
2943 rcu_read_unlock();
2944 return tsk;
2945 }
2946
cgroup_procs_write_finish(struct task_struct * task,bool threadgroup_locked)2947 void cgroup_procs_write_finish(struct task_struct *task, bool threadgroup_locked)
2948 {
2949 struct cgroup_subsys *ss;
2950 int ssid;
2951
2952 /* release reference from cgroup_procs_write_start() */
2953 put_task_struct(task);
2954
2955 cgroup_attach_unlock(threadgroup_locked);
2956
2957 for_each_subsys(ss, ssid)
2958 if (ss->post_attach)
2959 ss->post_attach();
2960 }
2961
cgroup_print_ss_mask(struct seq_file * seq,u16 ss_mask)2962 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2963 {
2964 struct cgroup_subsys *ss;
2965 bool printed = false;
2966 int ssid;
2967
2968 do_each_subsys_mask(ss, ssid, ss_mask) {
2969 if (printed)
2970 seq_putc(seq, ' ');
2971 seq_puts(seq, ss->name);
2972 printed = true;
2973 } while_each_subsys_mask();
2974 if (printed)
2975 seq_putc(seq, '\n');
2976 }
2977
2978 /* show controllers which are enabled from the parent */
cgroup_controllers_show(struct seq_file * seq,void * v)2979 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2980 {
2981 struct cgroup *cgrp = seq_css(seq)->cgroup;
2982
2983 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2984 return 0;
2985 }
2986
2987 /* show controllers which are enabled for a given cgroup's children */
cgroup_subtree_control_show(struct seq_file * seq,void * v)2988 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2989 {
2990 struct cgroup *cgrp = seq_css(seq)->cgroup;
2991
2992 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2993 return 0;
2994 }
2995
2996 /**
2997 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2998 * @cgrp: root of the subtree to update csses for
2999 *
3000 * @cgrp's control masks have changed and its subtree's css associations
3001 * need to be updated accordingly. This function looks up all css_sets
3002 * which are attached to the subtree, creates the matching updated css_sets
3003 * and migrates the tasks to the new ones.
3004 */
cgroup_update_dfl_csses(struct cgroup * cgrp)3005 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
3006 {
3007 DEFINE_CGROUP_MGCTX(mgctx);
3008 struct cgroup_subsys_state *d_css;
3009 struct cgroup *dsct;
3010 struct css_set *src_cset;
3011 bool has_tasks;
3012 int ret;
3013
3014 lockdep_assert_held(&cgroup_mutex);
3015
3016 /* look up all csses currently attached to @cgrp's subtree */
3017 spin_lock_irq(&css_set_lock);
3018 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3019 struct cgrp_cset_link *link;
3020
3021 list_for_each_entry(link, &dsct->cset_links, cset_link)
3022 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
3023 }
3024 spin_unlock_irq(&css_set_lock);
3025
3026 /*
3027 * We need to write-lock threadgroup_rwsem while migrating tasks.
3028 * However, if there are no source csets for @cgrp, changing its
3029 * controllers isn't gonna produce any task migrations and the
3030 * write-locking can be skipped safely.
3031 */
3032 has_tasks = !list_empty(&mgctx.preloaded_src_csets);
3033 cgroup_attach_lock(has_tasks);
3034
3035 /* NULL dst indicates self on default hierarchy */
3036 ret = cgroup_migrate_prepare_dst(&mgctx);
3037 if (ret)
3038 goto out_finish;
3039
3040 spin_lock_irq(&css_set_lock);
3041 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets,
3042 mg_src_preload_node) {
3043 struct task_struct *task, *ntask;
3044
3045 /* all tasks in src_csets need to be migrated */
3046 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
3047 cgroup_migrate_add_task(task, &mgctx);
3048 }
3049 spin_unlock_irq(&css_set_lock);
3050
3051 ret = cgroup_migrate_execute(&mgctx);
3052 out_finish:
3053 cgroup_migrate_finish(&mgctx);
3054 cgroup_attach_unlock(has_tasks);
3055 return ret;
3056 }
3057
3058 /**
3059 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
3060 * @cgrp: root of the target subtree
3061 *
3062 * Because css offlining is asynchronous, userland may try to re-enable a
3063 * controller while the previous css is still around. This function grabs
3064 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
3065 */
cgroup_lock_and_drain_offline(struct cgroup * cgrp)3066 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
3067 __acquires(&cgroup_mutex)
3068 {
3069 struct cgroup *dsct;
3070 struct cgroup_subsys_state *d_css;
3071 struct cgroup_subsys *ss;
3072 int ssid;
3073
3074 restart:
3075 mutex_lock(&cgroup_mutex);
3076
3077 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3078 for_each_subsys(ss, ssid) {
3079 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3080 DEFINE_WAIT(wait);
3081
3082 if (!css || !percpu_ref_is_dying(&css->refcnt))
3083 continue;
3084
3085 cgroup_get_live(dsct);
3086 prepare_to_wait(&dsct->offline_waitq, &wait,
3087 TASK_UNINTERRUPTIBLE);
3088
3089 mutex_unlock(&cgroup_mutex);
3090 schedule();
3091 finish_wait(&dsct->offline_waitq, &wait);
3092
3093 cgroup_put(dsct);
3094 goto restart;
3095 }
3096 }
3097 }
3098
3099 /**
3100 * cgroup_save_control - save control masks and dom_cgrp of a subtree
3101 * @cgrp: root of the target subtree
3102 *
3103 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
3104 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3105 * itself.
3106 */
cgroup_save_control(struct cgroup * cgrp)3107 static void cgroup_save_control(struct cgroup *cgrp)
3108 {
3109 struct cgroup *dsct;
3110 struct cgroup_subsys_state *d_css;
3111
3112 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3113 dsct->old_subtree_control = dsct->subtree_control;
3114 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
3115 dsct->old_dom_cgrp = dsct->dom_cgrp;
3116 }
3117 }
3118
3119 /**
3120 * cgroup_propagate_control - refresh control masks of a subtree
3121 * @cgrp: root of the target subtree
3122 *
3123 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
3124 * ->subtree_control and propagate controller availability through the
3125 * subtree so that descendants don't have unavailable controllers enabled.
3126 */
cgroup_propagate_control(struct cgroup * cgrp)3127 static void cgroup_propagate_control(struct cgroup *cgrp)
3128 {
3129 struct cgroup *dsct;
3130 struct cgroup_subsys_state *d_css;
3131
3132 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3133 dsct->subtree_control &= cgroup_control(dsct);
3134 dsct->subtree_ss_mask =
3135 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
3136 cgroup_ss_mask(dsct));
3137 }
3138 }
3139
3140 /**
3141 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
3142 * @cgrp: root of the target subtree
3143 *
3144 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
3145 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3146 * itself.
3147 */
cgroup_restore_control(struct cgroup * cgrp)3148 static void cgroup_restore_control(struct cgroup *cgrp)
3149 {
3150 struct cgroup *dsct;
3151 struct cgroup_subsys_state *d_css;
3152
3153 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3154 dsct->subtree_control = dsct->old_subtree_control;
3155 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
3156 dsct->dom_cgrp = dsct->old_dom_cgrp;
3157 }
3158 }
3159
css_visible(struct cgroup_subsys_state * css)3160 static bool css_visible(struct cgroup_subsys_state *css)
3161 {
3162 struct cgroup_subsys *ss = css->ss;
3163 struct cgroup *cgrp = css->cgroup;
3164
3165 if (cgroup_control(cgrp) & (1 << ss->id))
3166 return true;
3167 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
3168 return false;
3169 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
3170 }
3171
3172 /**
3173 * cgroup_apply_control_enable - enable or show csses according to control
3174 * @cgrp: root of the target subtree
3175 *
3176 * Walk @cgrp's subtree and create new csses or make the existing ones
3177 * visible. A css is created invisible if it's being implicitly enabled
3178 * through dependency. An invisible css is made visible when the userland
3179 * explicitly enables it.
3180 *
3181 * Returns 0 on success, -errno on failure. On failure, csses which have
3182 * been processed already aren't cleaned up. The caller is responsible for
3183 * cleaning up with cgroup_apply_control_disable().
3184 */
cgroup_apply_control_enable(struct cgroup * cgrp)3185 static int cgroup_apply_control_enable(struct cgroup *cgrp)
3186 {
3187 struct cgroup *dsct;
3188 struct cgroup_subsys_state *d_css;
3189 struct cgroup_subsys *ss;
3190 int ssid, ret;
3191
3192 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3193 for_each_subsys(ss, ssid) {
3194 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3195
3196 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
3197 continue;
3198
3199 if (!css) {
3200 css = css_create(dsct, ss);
3201 if (IS_ERR(css))
3202 return PTR_ERR(css);
3203 }
3204
3205 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3206
3207 if (css_visible(css)) {
3208 ret = css_populate_dir(css);
3209 if (ret)
3210 return ret;
3211 }
3212 }
3213 }
3214
3215 return 0;
3216 }
3217
3218 /**
3219 * cgroup_apply_control_disable - kill or hide csses according to control
3220 * @cgrp: root of the target subtree
3221 *
3222 * Walk @cgrp's subtree and kill and hide csses so that they match
3223 * cgroup_ss_mask() and cgroup_visible_mask().
3224 *
3225 * A css is hidden when the userland requests it to be disabled while other
3226 * subsystems are still depending on it. The css must not actively control
3227 * resources and be in the vanilla state if it's made visible again later.
3228 * Controllers which may be depended upon should provide ->css_reset() for
3229 * this purpose.
3230 */
cgroup_apply_control_disable(struct cgroup * cgrp)3231 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3232 {
3233 struct cgroup *dsct;
3234 struct cgroup_subsys_state *d_css;
3235 struct cgroup_subsys *ss;
3236 int ssid;
3237
3238 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3239 for_each_subsys(ss, ssid) {
3240 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3241
3242 if (!css)
3243 continue;
3244
3245 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3246
3247 if (css->parent &&
3248 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3249 kill_css(css);
3250 } else if (!css_visible(css)) {
3251 css_clear_dir(css);
3252 if (ss->css_reset)
3253 ss->css_reset(css);
3254 }
3255 }
3256 }
3257 }
3258
3259 /**
3260 * cgroup_apply_control - apply control mask updates to the subtree
3261 * @cgrp: root of the target subtree
3262 *
3263 * subsystems can be enabled and disabled in a subtree using the following
3264 * steps.
3265 *
3266 * 1. Call cgroup_save_control() to stash the current state.
3267 * 2. Update ->subtree_control masks in the subtree as desired.
3268 * 3. Call cgroup_apply_control() to apply the changes.
3269 * 4. Optionally perform other related operations.
3270 * 5. Call cgroup_finalize_control() to finish up.
3271 *
3272 * This function implements step 3 and propagates the mask changes
3273 * throughout @cgrp's subtree, updates csses accordingly and perform
3274 * process migrations.
3275 */
cgroup_apply_control(struct cgroup * cgrp)3276 static int cgroup_apply_control(struct cgroup *cgrp)
3277 {
3278 int ret;
3279
3280 cgroup_propagate_control(cgrp);
3281
3282 ret = cgroup_apply_control_enable(cgrp);
3283 if (ret)
3284 return ret;
3285
3286 /*
3287 * At this point, cgroup_e_css_by_mask() results reflect the new csses
3288 * making the following cgroup_update_dfl_csses() properly update
3289 * css associations of all tasks in the subtree.
3290 */
3291 ret = cgroup_update_dfl_csses(cgrp);
3292 if (ret)
3293 return ret;
3294
3295 return 0;
3296 }
3297
3298 /**
3299 * cgroup_finalize_control - finalize control mask update
3300 * @cgrp: root of the target subtree
3301 * @ret: the result of the update
3302 *
3303 * Finalize control mask update. See cgroup_apply_control() for more info.
3304 */
cgroup_finalize_control(struct cgroup * cgrp,int ret)3305 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3306 {
3307 if (ret) {
3308 cgroup_restore_control(cgrp);
3309 cgroup_propagate_control(cgrp);
3310 }
3311
3312 cgroup_apply_control_disable(cgrp);
3313 }
3314
cgroup_vet_subtree_control_enable(struct cgroup * cgrp,u16 enable)3315 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3316 {
3317 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3318
3319 /* if nothing is getting enabled, nothing to worry about */
3320 if (!enable)
3321 return 0;
3322
3323 /* can @cgrp host any resources? */
3324 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3325 return -EOPNOTSUPP;
3326
3327 /* mixables don't care */
3328 if (cgroup_is_mixable(cgrp))
3329 return 0;
3330
3331 if (domain_enable) {
3332 /* can't enable domain controllers inside a thread subtree */
3333 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3334 return -EOPNOTSUPP;
3335 } else {
3336 /*
3337 * Threaded controllers can handle internal competitions
3338 * and are always allowed inside a (prospective) thread
3339 * subtree.
3340 */
3341 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3342 return 0;
3343 }
3344
3345 /*
3346 * Controllers can't be enabled for a cgroup with tasks to avoid
3347 * child cgroups competing against tasks.
3348 */
3349 if (cgroup_has_tasks(cgrp))
3350 return -EBUSY;
3351
3352 return 0;
3353 }
3354
3355 /* 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)3356 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3357 char *buf, size_t nbytes,
3358 loff_t off)
3359 {
3360 u16 enable = 0, disable = 0;
3361 struct cgroup *cgrp, *child;
3362 struct cgroup_subsys *ss;
3363 char *tok;
3364 int ssid, ret;
3365
3366 /*
3367 * Parse input - space separated list of subsystem names prefixed
3368 * with either + or -.
3369 */
3370 buf = strstrip(buf);
3371 while ((tok = strsep(&buf, " "))) {
3372 if (tok[0] == '\0')
3373 continue;
3374 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3375 if (!cgroup_ssid_enabled(ssid) ||
3376 strcmp(tok + 1, ss->name))
3377 continue;
3378
3379 if (*tok == '+') {
3380 enable |= 1 << ssid;
3381 disable &= ~(1 << ssid);
3382 } else if (*tok == '-') {
3383 disable |= 1 << ssid;
3384 enable &= ~(1 << ssid);
3385 } else {
3386 return -EINVAL;
3387 }
3388 break;
3389 } while_each_subsys_mask();
3390 if (ssid == CGROUP_SUBSYS_COUNT)
3391 return -EINVAL;
3392 }
3393
3394 cgrp = cgroup_kn_lock_live(of->kn, true);
3395 if (!cgrp)
3396 return -ENODEV;
3397
3398 for_each_subsys(ss, ssid) {
3399 if (enable & (1 << ssid)) {
3400 if (cgrp->subtree_control & (1 << ssid)) {
3401 enable &= ~(1 << ssid);
3402 continue;
3403 }
3404
3405 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3406 ret = -ENOENT;
3407 goto out_unlock;
3408 }
3409 } else if (disable & (1 << ssid)) {
3410 if (!(cgrp->subtree_control & (1 << ssid))) {
3411 disable &= ~(1 << ssid);
3412 continue;
3413 }
3414
3415 /* a child has it enabled? */
3416 cgroup_for_each_live_child(child, cgrp) {
3417 if (child->subtree_control & (1 << ssid)) {
3418 ret = -EBUSY;
3419 goto out_unlock;
3420 }
3421 }
3422 }
3423 }
3424
3425 if (!enable && !disable) {
3426 ret = 0;
3427 goto out_unlock;
3428 }
3429
3430 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3431 if (ret)
3432 goto out_unlock;
3433
3434 /* save and update control masks and prepare csses */
3435 cgroup_save_control(cgrp);
3436
3437 cgrp->subtree_control |= enable;
3438 cgrp->subtree_control &= ~disable;
3439
3440 ret = cgroup_apply_control(cgrp);
3441 cgroup_finalize_control(cgrp, ret);
3442 if (ret)
3443 goto out_unlock;
3444
3445 kernfs_activate(cgrp->kn);
3446 out_unlock:
3447 cgroup_kn_unlock(of->kn);
3448 return ret ?: nbytes;
3449 }
3450
3451 /**
3452 * cgroup_enable_threaded - make @cgrp threaded
3453 * @cgrp: the target cgroup
3454 *
3455 * Called when "threaded" is written to the cgroup.type interface file and
3456 * tries to make @cgrp threaded and join the parent's resource domain.
3457 * This function is never called on the root cgroup as cgroup.type doesn't
3458 * exist on it.
3459 */
cgroup_enable_threaded(struct cgroup * cgrp)3460 static int cgroup_enable_threaded(struct cgroup *cgrp)
3461 {
3462 struct cgroup *parent = cgroup_parent(cgrp);
3463 struct cgroup *dom_cgrp = parent->dom_cgrp;
3464 struct cgroup *dsct;
3465 struct cgroup_subsys_state *d_css;
3466 int ret;
3467
3468 lockdep_assert_held(&cgroup_mutex);
3469
3470 /* noop if already threaded */
3471 if (cgroup_is_threaded(cgrp))
3472 return 0;
3473
3474 /*
3475 * If @cgroup is populated or has domain controllers enabled, it
3476 * can't be switched. While the below cgroup_can_be_thread_root()
3477 * test can catch the same conditions, that's only when @parent is
3478 * not mixable, so let's check it explicitly.
3479 */
3480 if (cgroup_is_populated(cgrp) ||
3481 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3482 return -EOPNOTSUPP;
3483
3484 /* we're joining the parent's domain, ensure its validity */
3485 if (!cgroup_is_valid_domain(dom_cgrp) ||
3486 !cgroup_can_be_thread_root(dom_cgrp))
3487 return -EOPNOTSUPP;
3488
3489 /*
3490 * The following shouldn't cause actual migrations and should
3491 * always succeed.
3492 */
3493 cgroup_save_control(cgrp);
3494
3495 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3496 if (dsct == cgrp || cgroup_is_threaded(dsct))
3497 dsct->dom_cgrp = dom_cgrp;
3498
3499 ret = cgroup_apply_control(cgrp);
3500 if (!ret)
3501 parent->nr_threaded_children++;
3502
3503 cgroup_finalize_control(cgrp, ret);
3504 return ret;
3505 }
3506
cgroup_type_show(struct seq_file * seq,void * v)3507 static int cgroup_type_show(struct seq_file *seq, void *v)
3508 {
3509 struct cgroup *cgrp = seq_css(seq)->cgroup;
3510
3511 if (cgroup_is_threaded(cgrp))
3512 seq_puts(seq, "threaded\n");
3513 else if (!cgroup_is_valid_domain(cgrp))
3514 seq_puts(seq, "domain invalid\n");
3515 else if (cgroup_is_thread_root(cgrp))
3516 seq_puts(seq, "domain threaded\n");
3517 else
3518 seq_puts(seq, "domain\n");
3519
3520 return 0;
3521 }
3522
cgroup_type_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3523 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3524 size_t nbytes, loff_t off)
3525 {
3526 struct cgroup *cgrp;
3527 int ret;
3528
3529 /* only switching to threaded mode is supported */
3530 if (strcmp(strstrip(buf), "threaded"))
3531 return -EINVAL;
3532
3533 /* drain dying csses before we re-apply (threaded) subtree control */
3534 cgrp = cgroup_kn_lock_live(of->kn, true);
3535 if (!cgrp)
3536 return -ENOENT;
3537
3538 /* threaded can only be enabled */
3539 ret = cgroup_enable_threaded(cgrp);
3540
3541 cgroup_kn_unlock(of->kn);
3542 return ret ?: nbytes;
3543 }
3544
cgroup_max_descendants_show(struct seq_file * seq,void * v)3545 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3546 {
3547 struct cgroup *cgrp = seq_css(seq)->cgroup;
3548 int descendants = READ_ONCE(cgrp->max_descendants);
3549
3550 if (descendants == INT_MAX)
3551 seq_puts(seq, "max\n");
3552 else
3553 seq_printf(seq, "%d\n", descendants);
3554
3555 return 0;
3556 }
3557
cgroup_max_descendants_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3558 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3559 char *buf, size_t nbytes, loff_t off)
3560 {
3561 struct cgroup *cgrp;
3562 int descendants;
3563 ssize_t ret;
3564
3565 buf = strstrip(buf);
3566 if (!strcmp(buf, "max")) {
3567 descendants = INT_MAX;
3568 } else {
3569 ret = kstrtoint(buf, 0, &descendants);
3570 if (ret)
3571 return ret;
3572 }
3573
3574 if (descendants < 0)
3575 return -ERANGE;
3576
3577 cgrp = cgroup_kn_lock_live(of->kn, false);
3578 if (!cgrp)
3579 return -ENOENT;
3580
3581 cgrp->max_descendants = descendants;
3582
3583 cgroup_kn_unlock(of->kn);
3584
3585 return nbytes;
3586 }
3587
cgroup_max_depth_show(struct seq_file * seq,void * v)3588 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3589 {
3590 struct cgroup *cgrp = seq_css(seq)->cgroup;
3591 int depth = READ_ONCE(cgrp->max_depth);
3592
3593 if (depth == INT_MAX)
3594 seq_puts(seq, "max\n");
3595 else
3596 seq_printf(seq, "%d\n", depth);
3597
3598 return 0;
3599 }
3600
cgroup_max_depth_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3601 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3602 char *buf, size_t nbytes, loff_t off)
3603 {
3604 struct cgroup *cgrp;
3605 ssize_t ret;
3606 int depth;
3607
3608 buf = strstrip(buf);
3609 if (!strcmp(buf, "max")) {
3610 depth = INT_MAX;
3611 } else {
3612 ret = kstrtoint(buf, 0, &depth);
3613 if (ret)
3614 return ret;
3615 }
3616
3617 if (depth < 0)
3618 return -ERANGE;
3619
3620 cgrp = cgroup_kn_lock_live(of->kn, false);
3621 if (!cgrp)
3622 return -ENOENT;
3623
3624 cgrp->max_depth = depth;
3625
3626 cgroup_kn_unlock(of->kn);
3627
3628 return nbytes;
3629 }
3630
cgroup_events_show(struct seq_file * seq,void * v)3631 static int cgroup_events_show(struct seq_file *seq, void *v)
3632 {
3633 struct cgroup *cgrp = seq_css(seq)->cgroup;
3634
3635 seq_printf(seq, "populated %d\n", cgroup_is_populated(cgrp));
3636 seq_printf(seq, "frozen %d\n", test_bit(CGRP_FROZEN, &cgrp->flags));
3637
3638 return 0;
3639 }
3640
cgroup_stat_show(struct seq_file * seq,void * v)3641 static int cgroup_stat_show(struct seq_file *seq, void *v)
3642 {
3643 struct cgroup *cgroup = seq_css(seq)->cgroup;
3644
3645 seq_printf(seq, "nr_descendants %d\n",
3646 cgroup->nr_descendants);
3647 seq_printf(seq, "nr_dying_descendants %d\n",
3648 cgroup->nr_dying_descendants);
3649
3650 return 0;
3651 }
3652
cgroup_extra_stat_show(struct seq_file * seq,struct cgroup * cgrp,int ssid)3653 static int __maybe_unused cgroup_extra_stat_show(struct seq_file *seq,
3654 struct cgroup *cgrp, int ssid)
3655 {
3656 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3657 struct cgroup_subsys_state *css;
3658 int ret;
3659
3660 if (!ss->css_extra_stat_show)
3661 return 0;
3662
3663 css = cgroup_tryget_css(cgrp, ss);
3664 if (!css)
3665 return 0;
3666
3667 ret = ss->css_extra_stat_show(seq, css);
3668 css_put(css);
3669 return ret;
3670 }
3671
cpu_stat_show(struct seq_file * seq,void * v)3672 static int cpu_stat_show(struct seq_file *seq, void *v)
3673 {
3674 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3675 int ret = 0;
3676
3677 cgroup_base_stat_cputime_show(seq);
3678 #ifdef CONFIG_CGROUP_SCHED
3679 ret = cgroup_extra_stat_show(seq, cgrp, cpu_cgrp_id);
3680 #endif
3681 return ret;
3682 }
3683
3684 #ifdef CONFIG_PSI
cgroup_io_pressure_show(struct seq_file * seq,void * v)3685 static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
3686 {
3687 struct cgroup *cgrp = seq_css(seq)->cgroup;
3688 struct psi_group *psi = cgroup_ino(cgrp) == 1 ? &psi_system : &cgrp->psi;
3689
3690 return psi_show(seq, psi, PSI_IO);
3691 }
cgroup_memory_pressure_show(struct seq_file * seq,void * v)3692 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
3693 {
3694 struct cgroup *cgrp = seq_css(seq)->cgroup;
3695 struct psi_group *psi = cgroup_ino(cgrp) == 1 ? &psi_system : &cgrp->psi;
3696
3697 return psi_show(seq, psi, PSI_MEM);
3698 }
cgroup_cpu_pressure_show(struct seq_file * seq,void * v)3699 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
3700 {
3701 struct cgroup *cgrp = seq_css(seq)->cgroup;
3702 struct psi_group *psi = cgroup_ino(cgrp) == 1 ? &psi_system : &cgrp->psi;
3703
3704 return psi_show(seq, psi, PSI_CPU);
3705 }
3706
cgroup_pressure_write(struct kernfs_open_file * of,char * buf,size_t nbytes,enum psi_res res)3707 static ssize_t cgroup_pressure_write(struct kernfs_open_file *of, char *buf,
3708 size_t nbytes, enum psi_res res)
3709 {
3710 struct cgroup_file_ctx *ctx = of->priv;
3711 struct psi_trigger *new;
3712 struct cgroup *cgrp;
3713 struct psi_group *psi;
3714
3715 cgrp = cgroup_kn_lock_live(of->kn, false);
3716 if (!cgrp)
3717 return -ENODEV;
3718
3719 cgroup_get(cgrp);
3720 cgroup_kn_unlock(of->kn);
3721
3722 /* Allow only one trigger per file descriptor */
3723 if (ctx->psi.trigger) {
3724 cgroup_put(cgrp);
3725 return -EBUSY;
3726 }
3727
3728 psi = cgroup_ino(cgrp) == 1 ? &psi_system : &cgrp->psi;
3729 new = psi_trigger_create(psi, buf, nbytes, res);
3730 if (IS_ERR(new)) {
3731 cgroup_put(cgrp);
3732 return PTR_ERR(new);
3733 }
3734
3735 smp_store_release(&ctx->psi.trigger, new);
3736 cgroup_put(cgrp);
3737
3738 return nbytes;
3739 }
3740
cgroup_io_pressure_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3741 static ssize_t cgroup_io_pressure_write(struct kernfs_open_file *of,
3742 char *buf, size_t nbytes,
3743 loff_t off)
3744 {
3745 return cgroup_pressure_write(of, buf, nbytes, PSI_IO);
3746 }
3747
cgroup_memory_pressure_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3748 static ssize_t cgroup_memory_pressure_write(struct kernfs_open_file *of,
3749 char *buf, size_t nbytes,
3750 loff_t off)
3751 {
3752 return cgroup_pressure_write(of, buf, nbytes, PSI_MEM);
3753 }
3754
cgroup_cpu_pressure_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3755 static ssize_t cgroup_cpu_pressure_write(struct kernfs_open_file *of,
3756 char *buf, size_t nbytes,
3757 loff_t off)
3758 {
3759 return cgroup_pressure_write(of, buf, nbytes, PSI_CPU);
3760 }
3761
cgroup_pressure_poll(struct kernfs_open_file * of,poll_table * pt)3762 static __poll_t cgroup_pressure_poll(struct kernfs_open_file *of,
3763 poll_table *pt)
3764 {
3765 struct cgroup_file_ctx *ctx = of->priv;
3766
3767 return psi_trigger_poll(&ctx->psi.trigger, of->file, pt);
3768 }
3769
cgroup_pressure_release(struct kernfs_open_file * of)3770 static void cgroup_pressure_release(struct kernfs_open_file *of)
3771 {
3772 struct cgroup_file_ctx *ctx = of->priv;
3773
3774 psi_trigger_destroy(ctx->psi.trigger);
3775 }
3776
cgroup_psi_enabled(void)3777 bool cgroup_psi_enabled(void)
3778 {
3779 return (cgroup_feature_disable_mask & (1 << OPT_FEATURE_PRESSURE)) == 0;
3780 }
3781
3782 #else /* CONFIG_PSI */
cgroup_psi_enabled(void)3783 bool cgroup_psi_enabled(void)
3784 {
3785 return false;
3786 }
3787
3788 #endif /* CONFIG_PSI */
3789
cgroup_freeze_show(struct seq_file * seq,void * v)3790 static int cgroup_freeze_show(struct seq_file *seq, void *v)
3791 {
3792 struct cgroup *cgrp = seq_css(seq)->cgroup;
3793
3794 seq_printf(seq, "%d\n", cgrp->freezer.freeze);
3795
3796 return 0;
3797 }
3798
cgroup_freeze_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3799 static ssize_t cgroup_freeze_write(struct kernfs_open_file *of,
3800 char *buf, size_t nbytes, loff_t off)
3801 {
3802 struct cgroup *cgrp;
3803 ssize_t ret;
3804 int freeze;
3805
3806 ret = kstrtoint(strstrip(buf), 0, &freeze);
3807 if (ret)
3808 return ret;
3809
3810 if (freeze < 0 || freeze > 1)
3811 return -ERANGE;
3812
3813 cgrp = cgroup_kn_lock_live(of->kn, false);
3814 if (!cgrp)
3815 return -ENOENT;
3816
3817 cgroup_freeze(cgrp, freeze);
3818
3819 cgroup_kn_unlock(of->kn);
3820
3821 return nbytes;
3822 }
3823
__cgroup_kill(struct cgroup * cgrp)3824 static void __cgroup_kill(struct cgroup *cgrp)
3825 {
3826 struct css_task_iter it;
3827 struct task_struct *task;
3828
3829 lockdep_assert_held(&cgroup_mutex);
3830
3831 spin_lock_irq(&css_set_lock);
3832 set_bit(CGRP_KILL, &cgrp->flags);
3833 spin_unlock_irq(&css_set_lock);
3834
3835 css_task_iter_start(&cgrp->self, CSS_TASK_ITER_PROCS | CSS_TASK_ITER_THREADED, &it);
3836 while ((task = css_task_iter_next(&it))) {
3837 /* Ignore kernel threads here. */
3838 if (task->flags & PF_KTHREAD)
3839 continue;
3840
3841 /* Skip tasks that are already dying. */
3842 if (__fatal_signal_pending(task))
3843 continue;
3844
3845 send_sig(SIGKILL, task, 0);
3846 }
3847 css_task_iter_end(&it);
3848
3849 spin_lock_irq(&css_set_lock);
3850 clear_bit(CGRP_KILL, &cgrp->flags);
3851 spin_unlock_irq(&css_set_lock);
3852 }
3853
cgroup_kill(struct cgroup * cgrp)3854 static void cgroup_kill(struct cgroup *cgrp)
3855 {
3856 struct cgroup_subsys_state *css;
3857 struct cgroup *dsct;
3858
3859 lockdep_assert_held(&cgroup_mutex);
3860
3861 cgroup_for_each_live_descendant_pre(dsct, css, cgrp)
3862 __cgroup_kill(dsct);
3863 }
3864
cgroup_kill_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3865 static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf,
3866 size_t nbytes, loff_t off)
3867 {
3868 ssize_t ret = 0;
3869 int kill;
3870 struct cgroup *cgrp;
3871
3872 ret = kstrtoint(strstrip(buf), 0, &kill);
3873 if (ret)
3874 return ret;
3875
3876 if (kill != 1)
3877 return -ERANGE;
3878
3879 cgrp = cgroup_kn_lock_live(of->kn, false);
3880 if (!cgrp)
3881 return -ENOENT;
3882
3883 /*
3884 * Killing is a process directed operation, i.e. the whole thread-group
3885 * is taken down so act like we do for cgroup.procs and only make this
3886 * writable in non-threaded cgroups.
3887 */
3888 if (cgroup_is_threaded(cgrp))
3889 ret = -EOPNOTSUPP;
3890 else
3891 cgroup_kill(cgrp);
3892
3893 cgroup_kn_unlock(of->kn);
3894
3895 return ret ?: nbytes;
3896 }
3897
cgroup_file_open(struct kernfs_open_file * of)3898 static int cgroup_file_open(struct kernfs_open_file *of)
3899 {
3900 struct cftype *cft = of_cft(of);
3901 struct cgroup_file_ctx *ctx;
3902 int ret;
3903
3904 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3905 if (!ctx)
3906 return -ENOMEM;
3907
3908 ctx->ns = current->nsproxy->cgroup_ns;
3909 get_cgroup_ns(ctx->ns);
3910 of->priv = ctx;
3911
3912 if (!cft->open)
3913 return 0;
3914
3915 ret = cft->open(of);
3916 if (ret) {
3917 put_cgroup_ns(ctx->ns);
3918 kfree(ctx);
3919 }
3920 return ret;
3921 }
3922
cgroup_file_release(struct kernfs_open_file * of)3923 static void cgroup_file_release(struct kernfs_open_file *of)
3924 {
3925 struct cftype *cft = of_cft(of);
3926 struct cgroup_file_ctx *ctx = of->priv;
3927
3928 if (cft->release)
3929 cft->release(of);
3930 put_cgroup_ns(ctx->ns);
3931 kfree(ctx);
3932 }
3933
cgroup_file_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3934 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3935 size_t nbytes, loff_t off)
3936 {
3937 struct cgroup_file_ctx *ctx = of->priv;
3938 struct cgroup *cgrp = of->kn->parent->priv;
3939 struct cftype *cft = of_cft(of);
3940 struct cgroup_subsys_state *css;
3941 int ret;
3942
3943 if (!nbytes)
3944 return 0;
3945
3946 /*
3947 * If namespaces are delegation boundaries, disallow writes to
3948 * files in an non-init namespace root from inside the namespace
3949 * except for the files explicitly marked delegatable -
3950 * cgroup.procs and cgroup.subtree_control.
3951 */
3952 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3953 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3954 ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
3955 return -EPERM;
3956
3957 if (cft->write)
3958 return cft->write(of, buf, nbytes, off);
3959
3960 /*
3961 * kernfs guarantees that a file isn't deleted with operations in
3962 * flight, which means that the matching css is and stays alive and
3963 * doesn't need to be pinned. The RCU locking is not necessary
3964 * either. It's just for the convenience of using cgroup_css().
3965 */
3966 rcu_read_lock();
3967 css = cgroup_css(cgrp, cft->ss);
3968 rcu_read_unlock();
3969
3970 if (cft->write_u64) {
3971 unsigned long long v;
3972 ret = kstrtoull(buf, 0, &v);
3973 if (!ret)
3974 ret = cft->write_u64(css, cft, v);
3975 } else if (cft->write_s64) {
3976 long long v;
3977 ret = kstrtoll(buf, 0, &v);
3978 if (!ret)
3979 ret = cft->write_s64(css, cft, v);
3980 } else {
3981 ret = -EINVAL;
3982 }
3983
3984 return ret ?: nbytes;
3985 }
3986
cgroup_file_poll(struct kernfs_open_file * of,poll_table * pt)3987 static __poll_t cgroup_file_poll(struct kernfs_open_file *of, poll_table *pt)
3988 {
3989 struct cftype *cft = of_cft(of);
3990
3991 if (cft->poll)
3992 return cft->poll(of, pt);
3993
3994 return kernfs_generic_poll(of, pt);
3995 }
3996
cgroup_seqfile_start(struct seq_file * seq,loff_t * ppos)3997 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3998 {
3999 return seq_cft(seq)->seq_start(seq, ppos);
4000 }
4001
cgroup_seqfile_next(struct seq_file * seq,void * v,loff_t * ppos)4002 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
4003 {
4004 return seq_cft(seq)->seq_next(seq, v, ppos);
4005 }
4006
cgroup_seqfile_stop(struct seq_file * seq,void * v)4007 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
4008 {
4009 if (seq_cft(seq)->seq_stop)
4010 seq_cft(seq)->seq_stop(seq, v);
4011 }
4012
cgroup_seqfile_show(struct seq_file * m,void * arg)4013 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
4014 {
4015 struct cftype *cft = seq_cft(m);
4016 struct cgroup_subsys_state *css = seq_css(m);
4017
4018 if (cft->seq_show)
4019 return cft->seq_show(m, arg);
4020
4021 if (cft->read_u64)
4022 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
4023 else if (cft->read_s64)
4024 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
4025 else
4026 return -EINVAL;
4027 return 0;
4028 }
4029
4030 static struct kernfs_ops cgroup_kf_single_ops = {
4031 .atomic_write_len = PAGE_SIZE,
4032 .open = cgroup_file_open,
4033 .release = cgroup_file_release,
4034 .write = cgroup_file_write,
4035 .poll = cgroup_file_poll,
4036 .seq_show = cgroup_seqfile_show,
4037 };
4038
4039 static struct kernfs_ops cgroup_kf_ops = {
4040 .atomic_write_len = PAGE_SIZE,
4041 .open = cgroup_file_open,
4042 .release = cgroup_file_release,
4043 .write = cgroup_file_write,
4044 .poll = cgroup_file_poll,
4045 .seq_start = cgroup_seqfile_start,
4046 .seq_next = cgroup_seqfile_next,
4047 .seq_stop = cgroup_seqfile_stop,
4048 .seq_show = cgroup_seqfile_show,
4049 };
4050
4051 /* set uid and gid of cgroup dirs and files to that of the creator */
cgroup_kn_set_ugid(struct kernfs_node * kn)4052 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
4053 {
4054 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
4055 .ia_uid = current_fsuid(),
4056 .ia_gid = current_fsgid(), };
4057
4058 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
4059 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
4060 return 0;
4061
4062 return kernfs_setattr(kn, &iattr);
4063 }
4064
cgroup_file_notify_timer(struct timer_list * timer)4065 static void cgroup_file_notify_timer(struct timer_list *timer)
4066 {
4067 cgroup_file_notify(container_of(timer, struct cgroup_file,
4068 notify_timer));
4069 }
4070
cgroup_add_file(struct cgroup_subsys_state * css,struct cgroup * cgrp,struct cftype * cft)4071 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
4072 struct cftype *cft)
4073 {
4074 char name[CGROUP_FILE_NAME_MAX];
4075 struct kernfs_node *kn;
4076 struct lock_class_key *key = NULL;
4077 int ret;
4078
4079 #ifdef CONFIG_DEBUG_LOCK_ALLOC
4080 key = &cft->lockdep_key;
4081 #endif
4082 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
4083 cgroup_file_mode(cft),
4084 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
4085 0, cft->kf_ops, cft,
4086 NULL, key);
4087 if (IS_ERR(kn))
4088 return PTR_ERR(kn);
4089
4090 ret = cgroup_kn_set_ugid(kn);
4091 if (ret) {
4092 kernfs_remove(kn);
4093 return ret;
4094 }
4095
4096 if (cft->file_offset) {
4097 struct cgroup_file *cfile = (void *)css + cft->file_offset;
4098
4099 timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
4100
4101 spin_lock_irq(&cgroup_file_kn_lock);
4102 cfile->kn = kn;
4103 spin_unlock_irq(&cgroup_file_kn_lock);
4104 }
4105
4106 return 0;
4107 }
4108
4109 /**
4110 * cgroup_addrm_files - add or remove files to a cgroup directory
4111 * @css: the target css
4112 * @cgrp: the target cgroup (usually css->cgroup)
4113 * @cfts: array of cftypes to be added
4114 * @is_add: whether to add or remove
4115 *
4116 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
4117 * For removals, this function never fails.
4118 */
cgroup_addrm_files(struct cgroup_subsys_state * css,struct cgroup * cgrp,struct cftype cfts[],bool is_add)4119 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
4120 struct cgroup *cgrp, struct cftype cfts[],
4121 bool is_add)
4122 {
4123 struct cftype *cft, *cft_end = NULL;
4124 int ret = 0;
4125
4126 lockdep_assert_held(&cgroup_mutex);
4127
4128 restart:
4129 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
4130 /* does cft->flags tell us to skip this file on @cgrp? */
4131 if ((cft->flags & CFTYPE_PRESSURE) && !cgroup_psi_enabled())
4132 continue;
4133 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
4134 continue;
4135 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
4136 continue;
4137 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
4138 continue;
4139 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
4140 continue;
4141 if ((cft->flags & CFTYPE_DEBUG) && !cgroup_debug)
4142 continue;
4143 if (is_add) {
4144 ret = cgroup_add_file(css, cgrp, cft);
4145 if (ret) {
4146 pr_warn("%s: failed to add %s, err=%d\n",
4147 __func__, cft->name, ret);
4148 cft_end = cft;
4149 is_add = false;
4150 goto restart;
4151 }
4152 } else {
4153 cgroup_rm_file(cgrp, cft);
4154 }
4155 }
4156 return ret;
4157 }
4158
cgroup_apply_cftypes(struct cftype * cfts,bool is_add)4159 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
4160 {
4161 struct cgroup_subsys *ss = cfts[0].ss;
4162 struct cgroup *root = &ss->root->cgrp;
4163 struct cgroup_subsys_state *css;
4164 int ret = 0;
4165
4166 lockdep_assert_held(&cgroup_mutex);
4167
4168 /* add/rm files for all cgroups created before */
4169 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
4170 struct cgroup *cgrp = css->cgroup;
4171
4172 if (!(css->flags & CSS_VISIBLE))
4173 continue;
4174
4175 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
4176 if (ret)
4177 break;
4178 }
4179
4180 if (is_add && !ret)
4181 kernfs_activate(root->kn);
4182 return ret;
4183 }
4184
cgroup_exit_cftypes(struct cftype * cfts)4185 static void cgroup_exit_cftypes(struct cftype *cfts)
4186 {
4187 struct cftype *cft;
4188
4189 for (cft = cfts; cft->name[0] != '\0'; cft++) {
4190 /* free copy for custom atomic_write_len, see init_cftypes() */
4191 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
4192 kfree(cft->kf_ops);
4193 cft->kf_ops = NULL;
4194 cft->ss = NULL;
4195
4196 /* revert flags set by cgroup core while adding @cfts */
4197 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
4198 }
4199 }
4200
cgroup_init_cftypes(struct cgroup_subsys * ss,struct cftype * cfts)4201 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4202 {
4203 struct cftype *cft;
4204
4205 for (cft = cfts; cft->name[0] != '\0'; cft++) {
4206 struct kernfs_ops *kf_ops;
4207
4208 WARN_ON(cft->ss || cft->kf_ops);
4209
4210 if ((cft->flags & CFTYPE_PRESSURE) && !cgroup_psi_enabled())
4211 continue;
4212
4213 if (cft->seq_start)
4214 kf_ops = &cgroup_kf_ops;
4215 else
4216 kf_ops = &cgroup_kf_single_ops;
4217
4218 /*
4219 * Ugh... if @cft wants a custom max_write_len, we need to
4220 * make a copy of kf_ops to set its atomic_write_len.
4221 */
4222 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
4223 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
4224 if (!kf_ops) {
4225 cgroup_exit_cftypes(cfts);
4226 return -ENOMEM;
4227 }
4228 kf_ops->atomic_write_len = cft->max_write_len;
4229 }
4230
4231 cft->kf_ops = kf_ops;
4232 cft->ss = ss;
4233 }
4234
4235 return 0;
4236 }
4237
cgroup_rm_cftypes_locked(struct cftype * cfts)4238 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
4239 {
4240 lockdep_assert_held(&cgroup_mutex);
4241
4242 if (!cfts || !cfts[0].ss)
4243 return -ENOENT;
4244
4245 list_del(&cfts->node);
4246 cgroup_apply_cftypes(cfts, false);
4247 cgroup_exit_cftypes(cfts);
4248 return 0;
4249 }
4250
4251 /**
4252 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
4253 * @cfts: zero-length name terminated array of cftypes
4254 *
4255 * Unregister @cfts. Files described by @cfts are removed from all
4256 * existing cgroups and all future cgroups won't have them either. This
4257 * function can be called anytime whether @cfts' subsys is attached or not.
4258 *
4259 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
4260 * registered.
4261 */
cgroup_rm_cftypes(struct cftype * cfts)4262 int cgroup_rm_cftypes(struct cftype *cfts)
4263 {
4264 int ret;
4265
4266 mutex_lock(&cgroup_mutex);
4267 ret = cgroup_rm_cftypes_locked(cfts);
4268 mutex_unlock(&cgroup_mutex);
4269 return ret;
4270 }
4271
4272 /**
4273 * cgroup_add_cftypes - add an array of cftypes to a subsystem
4274 * @ss: target cgroup subsystem
4275 * @cfts: zero-length name terminated array of cftypes
4276 *
4277 * Register @cfts to @ss. Files described by @cfts are created for all
4278 * existing cgroups to which @ss is attached and all future cgroups will
4279 * have them too. This function can be called anytime whether @ss is
4280 * attached or not.
4281 *
4282 * Returns 0 on successful registration, -errno on failure. Note that this
4283 * function currently returns 0 as long as @cfts registration is successful
4284 * even if some file creation attempts on existing cgroups fail.
4285 */
cgroup_add_cftypes(struct cgroup_subsys * ss,struct cftype * cfts)4286 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4287 {
4288 int ret;
4289
4290 if (!cgroup_ssid_enabled(ss->id))
4291 return 0;
4292
4293 if (!cfts || cfts[0].name[0] == '\0')
4294 return 0;
4295
4296 ret = cgroup_init_cftypes(ss, cfts);
4297 if (ret)
4298 return ret;
4299
4300 mutex_lock(&cgroup_mutex);
4301
4302 list_add_tail(&cfts->node, &ss->cfts);
4303 ret = cgroup_apply_cftypes(cfts, true);
4304 if (ret)
4305 cgroup_rm_cftypes_locked(cfts);
4306
4307 mutex_unlock(&cgroup_mutex);
4308 return ret;
4309 }
4310
4311 /**
4312 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
4313 * @ss: target cgroup subsystem
4314 * @cfts: zero-length name terminated array of cftypes
4315 *
4316 * Similar to cgroup_add_cftypes() but the added files are only used for
4317 * the default hierarchy.
4318 */
cgroup_add_dfl_cftypes(struct cgroup_subsys * ss,struct cftype * cfts)4319 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4320 {
4321 struct cftype *cft;
4322
4323 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4324 cft->flags |= __CFTYPE_ONLY_ON_DFL;
4325 return cgroup_add_cftypes(ss, cfts);
4326 }
4327 EXPORT_SYMBOL_GPL(cgroup_add_dfl_cftypes);
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
4806 /**
4807 * css_task_iter_next - return the next task for the iterator
4808 * @it: the task iterator being iterated
4809 *
4810 * The "next" function for task iteration. @it should have been
4811 * initialized via css_task_iter_start(). Returns NULL when the iteration
4812 * reaches the end.
4813 */
css_task_iter_next(struct css_task_iter * it)4814 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4815 {
4816 if (it->cur_task) {
4817 put_task_struct(it->cur_task);
4818 it->cur_task = NULL;
4819 }
4820
4821 spin_lock_irq(&css_set_lock);
4822
4823 /* @it may be half-advanced by skips, finish advancing */
4824 if (it->flags & CSS_TASK_ITER_SKIPPED)
4825 css_task_iter_advance(it);
4826
4827 if (it->task_pos) {
4828 it->cur_task = list_entry(it->task_pos, struct task_struct,
4829 cg_list);
4830 get_task_struct(it->cur_task);
4831 css_task_iter_advance(it);
4832 }
4833
4834 spin_unlock_irq(&css_set_lock);
4835
4836 return it->cur_task;
4837 }
4838
4839 /**
4840 * css_task_iter_end - finish task iteration
4841 * @it: the task iterator to finish
4842 *
4843 * Finish task iteration started by css_task_iter_start().
4844 */
css_task_iter_end(struct css_task_iter * it)4845 void css_task_iter_end(struct css_task_iter *it)
4846 {
4847 if (it->cur_cset) {
4848 spin_lock_irq(&css_set_lock);
4849 list_del(&it->iters_node);
4850 put_css_set_locked(it->cur_cset);
4851 spin_unlock_irq(&css_set_lock);
4852 }
4853
4854 if (it->cur_dcset)
4855 put_css_set(it->cur_dcset);
4856
4857 if (it->cur_task)
4858 put_task_struct(it->cur_task);
4859 }
4860
cgroup_procs_release(struct kernfs_open_file * of)4861 static void cgroup_procs_release(struct kernfs_open_file *of)
4862 {
4863 struct cgroup_file_ctx *ctx = of->priv;
4864
4865 if (ctx->procs.started)
4866 css_task_iter_end(&ctx->procs.iter);
4867 }
4868
cgroup_procs_next(struct seq_file * s,void * v,loff_t * pos)4869 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
4870 {
4871 struct kernfs_open_file *of = s->private;
4872 struct cgroup_file_ctx *ctx = of->priv;
4873
4874 if (pos)
4875 (*pos)++;
4876
4877 return css_task_iter_next(&ctx->procs.iter);
4878 }
4879
__cgroup_procs_start(struct seq_file * s,loff_t * pos,unsigned int iter_flags)4880 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
4881 unsigned int iter_flags)
4882 {
4883 struct kernfs_open_file *of = s->private;
4884 struct cgroup *cgrp = seq_css(s)->cgroup;
4885 struct cgroup_file_ctx *ctx = of->priv;
4886 struct css_task_iter *it = &ctx->procs.iter;
4887
4888 /*
4889 * When a seq_file is seeked, it's always traversed sequentially
4890 * from position 0, so we can simply keep iterating on !0 *pos.
4891 */
4892 if (!ctx->procs.started) {
4893 if (WARN_ON_ONCE((*pos)))
4894 return ERR_PTR(-EINVAL);
4895 css_task_iter_start(&cgrp->self, iter_flags, it);
4896 ctx->procs.started = true;
4897 } else if (!(*pos)) {
4898 css_task_iter_end(it);
4899 css_task_iter_start(&cgrp->self, iter_flags, it);
4900 } else
4901 return it->cur_task;
4902
4903 return cgroup_procs_next(s, NULL, NULL);
4904 }
4905
cgroup_procs_start(struct seq_file * s,loff_t * pos)4906 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
4907 {
4908 struct cgroup *cgrp = seq_css(s)->cgroup;
4909
4910 /*
4911 * All processes of a threaded subtree belong to the domain cgroup
4912 * of the subtree. Only threads can be distributed across the
4913 * subtree. Reject reads on cgroup.procs in the subtree proper.
4914 * They're always empty anyway.
4915 */
4916 if (cgroup_is_threaded(cgrp))
4917 return ERR_PTR(-EOPNOTSUPP);
4918
4919 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
4920 CSS_TASK_ITER_THREADED);
4921 }
4922
cgroup_procs_show(struct seq_file * s,void * v)4923 static int cgroup_procs_show(struct seq_file *s, void *v)
4924 {
4925 seq_printf(s, "%d\n", task_pid_vnr(v));
4926 return 0;
4927 }
4928
cgroup_may_write(const struct cgroup * cgrp,struct super_block * sb)4929 static int cgroup_may_write(const struct cgroup *cgrp, struct super_block *sb)
4930 {
4931 int ret;
4932 struct inode *inode;
4933
4934 lockdep_assert_held(&cgroup_mutex);
4935
4936 inode = kernfs_get_inode(sb, cgrp->procs_file.kn);
4937 if (!inode)
4938 return -ENOMEM;
4939
4940 ret = inode_permission(&init_user_ns, inode, MAY_WRITE);
4941 iput(inode);
4942 return ret;
4943 }
4944
cgroup_procs_write_permission(struct cgroup * src_cgrp,struct cgroup * dst_cgrp,struct super_block * sb,struct cgroup_namespace * ns)4945 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
4946 struct cgroup *dst_cgrp,
4947 struct super_block *sb,
4948 struct cgroup_namespace *ns)
4949 {
4950 struct cgroup *com_cgrp = src_cgrp;
4951 int ret;
4952
4953 lockdep_assert_held(&cgroup_mutex);
4954
4955 /* find the common ancestor */
4956 while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
4957 com_cgrp = cgroup_parent(com_cgrp);
4958
4959 /* %current should be authorized to migrate to the common ancestor */
4960 ret = cgroup_may_write(com_cgrp, sb);
4961 if (ret)
4962 return ret;
4963
4964 /*
4965 * If namespaces are delegation boundaries, %current must be able
4966 * to see both source and destination cgroups from its namespace.
4967 */
4968 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
4969 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
4970 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
4971 return -ENOENT;
4972
4973 return 0;
4974 }
4975
cgroup_attach_permissions(struct cgroup * src_cgrp,struct cgroup * dst_cgrp,struct super_block * sb,bool threadgroup,struct cgroup_namespace * ns)4976 static int cgroup_attach_permissions(struct cgroup *src_cgrp,
4977 struct cgroup *dst_cgrp,
4978 struct super_block *sb, bool threadgroup,
4979 struct cgroup_namespace *ns)
4980 {
4981 int ret = 0;
4982
4983 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp, sb, ns);
4984 if (ret)
4985 return ret;
4986
4987 ret = cgroup_migrate_vet_dst(dst_cgrp);
4988 if (ret)
4989 return ret;
4990
4991 if (!threadgroup && (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp))
4992 ret = -EOPNOTSUPP;
4993
4994 return ret;
4995 }
4996
__cgroup_procs_write(struct kernfs_open_file * of,char * buf,bool threadgroup)4997 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
4998 bool threadgroup)
4999 {
5000 struct cgroup_file_ctx *ctx = of->priv;
5001 struct cgroup *src_cgrp, *dst_cgrp;
5002 struct task_struct *task;
5003 const struct cred *saved_cred;
5004 ssize_t ret;
5005 bool threadgroup_locked;
5006
5007 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
5008 if (!dst_cgrp)
5009 return -ENODEV;
5010
5011 task = cgroup_procs_write_start(buf, threadgroup, &threadgroup_locked, dst_cgrp);
5012 ret = PTR_ERR_OR_ZERO(task);
5013 if (ret)
5014 goto out_unlock;
5015
5016 /* find the source cgroup */
5017 spin_lock_irq(&css_set_lock);
5018 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
5019 spin_unlock_irq(&css_set_lock);
5020
5021 /*
5022 * Process and thread migrations follow same delegation rule. Check
5023 * permissions using the credentials from file open to protect against
5024 * inherited fd attacks.
5025 */
5026 saved_cred = override_creds(of->file->f_cred);
5027 ret = cgroup_attach_permissions(src_cgrp, dst_cgrp,
5028 of->file->f_path.dentry->d_sb,
5029 threadgroup, ctx->ns);
5030 revert_creds(saved_cred);
5031 if (ret)
5032 goto out_finish;
5033
5034 ret = cgroup_attach_task(dst_cgrp, task, threadgroup);
5035
5036 out_finish:
5037 cgroup_procs_write_finish(task, threadgroup_locked);
5038 out_unlock:
5039 cgroup_kn_unlock(of->kn);
5040
5041 return ret;
5042 }
5043
cgroup_procs_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)5044 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
5045 char *buf, size_t nbytes, loff_t off)
5046 {
5047 return __cgroup_procs_write(of, buf, true) ?: nbytes;
5048 }
5049
cgroup_threads_start(struct seq_file * s,loff_t * pos)5050 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
5051 {
5052 return __cgroup_procs_start(s, pos, 0);
5053 }
5054
cgroup_threads_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)5055 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
5056 char *buf, size_t nbytes, loff_t off)
5057 {
5058 return __cgroup_procs_write(of, buf, false) ?: nbytes;
5059 }
5060
5061 /* cgroup core interface files for the default hierarchy */
5062 static struct cftype cgroup_base_files[] = {
5063 {
5064 .name = "cgroup.type",
5065 .flags = CFTYPE_NOT_ON_ROOT,
5066 .seq_show = cgroup_type_show,
5067 .write = cgroup_type_write,
5068 },
5069 {
5070 .name = "cgroup.procs",
5071 .flags = CFTYPE_NS_DELEGATABLE,
5072 .file_offset = offsetof(struct cgroup, procs_file),
5073 .release = cgroup_procs_release,
5074 .seq_start = cgroup_procs_start,
5075 .seq_next = cgroup_procs_next,
5076 .seq_show = cgroup_procs_show,
5077 .write = cgroup_procs_write,
5078 },
5079 {
5080 .name = "cgroup.threads",
5081 .flags = CFTYPE_NS_DELEGATABLE,
5082 .release = cgroup_procs_release,
5083 .seq_start = cgroup_threads_start,
5084 .seq_next = cgroup_procs_next,
5085 .seq_show = cgroup_procs_show,
5086 .write = cgroup_threads_write,
5087 },
5088 {
5089 .name = "cgroup.controllers",
5090 .seq_show = cgroup_controllers_show,
5091 },
5092 {
5093 .name = "cgroup.subtree_control",
5094 .flags = CFTYPE_NS_DELEGATABLE,
5095 .seq_show = cgroup_subtree_control_show,
5096 .write = cgroup_subtree_control_write,
5097 },
5098 {
5099 .name = "cgroup.events",
5100 .flags = CFTYPE_NOT_ON_ROOT,
5101 .file_offset = offsetof(struct cgroup, events_file),
5102 .seq_show = cgroup_events_show,
5103 },
5104 {
5105 .name = "cgroup.max.descendants",
5106 .seq_show = cgroup_max_descendants_show,
5107 .write = cgroup_max_descendants_write,
5108 },
5109 {
5110 .name = "cgroup.max.depth",
5111 .seq_show = cgroup_max_depth_show,
5112 .write = cgroup_max_depth_write,
5113 },
5114 {
5115 .name = "cgroup.stat",
5116 .seq_show = cgroup_stat_show,
5117 },
5118 {
5119 .name = "cgroup.freeze",
5120 .flags = CFTYPE_NOT_ON_ROOT,
5121 .seq_show = cgroup_freeze_show,
5122 .write = cgroup_freeze_write,
5123 },
5124 {
5125 .name = "cgroup.kill",
5126 .flags = CFTYPE_NOT_ON_ROOT,
5127 .write = cgroup_kill_write,
5128 },
5129 {
5130 .name = "cpu.stat",
5131 .seq_show = cpu_stat_show,
5132 },
5133 #ifdef CONFIG_PSI
5134 {
5135 .name = "io.pressure",
5136 .flags = CFTYPE_PRESSURE,
5137 .seq_show = cgroup_io_pressure_show,
5138 .write = cgroup_io_pressure_write,
5139 .poll = cgroup_pressure_poll,
5140 .release = cgroup_pressure_release,
5141 },
5142 {
5143 .name = "memory.pressure",
5144 .flags = CFTYPE_PRESSURE,
5145 .seq_show = cgroup_memory_pressure_show,
5146 .write = cgroup_memory_pressure_write,
5147 .poll = cgroup_pressure_poll,
5148 .release = cgroup_pressure_release,
5149 },
5150 {
5151 .name = "cpu.pressure",
5152 .flags = CFTYPE_PRESSURE,
5153 .seq_show = cgroup_cpu_pressure_show,
5154 .write = cgroup_cpu_pressure_write,
5155 .poll = cgroup_pressure_poll,
5156 .release = cgroup_pressure_release,
5157 },
5158 #endif /* CONFIG_PSI */
5159 { } /* terminate */
5160 };
5161
5162 /*
5163 * css destruction is four-stage process.
5164 *
5165 * 1. Destruction starts. Killing of the percpu_ref is initiated.
5166 * Implemented in kill_css().
5167 *
5168 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
5169 * and thus css_tryget_online() is guaranteed to fail, the css can be
5170 * offlined by invoking offline_css(). After offlining, the base ref is
5171 * put. Implemented in css_killed_work_fn().
5172 *
5173 * 3. When the percpu_ref reaches zero, the only possible remaining
5174 * accessors are inside RCU read sections. css_release() schedules the
5175 * RCU callback.
5176 *
5177 * 4. After the grace period, the css can be freed. Implemented in
5178 * css_free_work_fn().
5179 *
5180 * It is actually hairier because both step 2 and 4 require process context
5181 * and thus involve punting to css->destroy_work adding two additional
5182 * steps to the already complex sequence.
5183 */
css_free_rwork_fn(struct work_struct * work)5184 static void css_free_rwork_fn(struct work_struct *work)
5185 {
5186 struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
5187 struct cgroup_subsys_state, destroy_rwork);
5188 struct cgroup_subsys *ss = css->ss;
5189 struct cgroup *cgrp = css->cgroup;
5190
5191 percpu_ref_exit(&css->refcnt);
5192
5193 if (ss) {
5194 /* css free path */
5195 struct cgroup_subsys_state *parent = css->parent;
5196 int id = css->id;
5197
5198 ss->css_free(css);
5199 cgroup_idr_remove(&ss->css_idr, id);
5200 cgroup_put(cgrp);
5201
5202 if (parent)
5203 css_put(parent);
5204 } else {
5205 /* cgroup free path */
5206 atomic_dec(&cgrp->root->nr_cgrps);
5207 cgroup1_pidlist_destroy_all(cgrp);
5208 cancel_work_sync(&cgrp->release_agent_work);
5209
5210 if (cgroup_parent(cgrp)) {
5211 /*
5212 * We get a ref to the parent, and put the ref when
5213 * this cgroup is being freed, so it's guaranteed
5214 * that the parent won't be destroyed before its
5215 * children.
5216 */
5217 cgroup_put(cgroup_parent(cgrp));
5218 kernfs_put(cgrp->kn);
5219 psi_cgroup_free(cgrp);
5220 cgroup_rstat_exit(cgrp);
5221 kfree(cgrp);
5222 } else {
5223 /*
5224 * This is root cgroup's refcnt reaching zero,
5225 * which indicates that the root should be
5226 * released.
5227 */
5228 cgroup_destroy_root(cgrp->root);
5229 }
5230 }
5231 }
5232
css_release_work_fn(struct work_struct * work)5233 static void css_release_work_fn(struct work_struct *work)
5234 {
5235 struct cgroup_subsys_state *css =
5236 container_of(work, struct cgroup_subsys_state, destroy_work);
5237 struct cgroup_subsys *ss = css->ss;
5238 struct cgroup *cgrp = css->cgroup;
5239
5240 mutex_lock(&cgroup_mutex);
5241
5242 css->flags |= CSS_RELEASED;
5243 list_del_rcu(&css->sibling);
5244
5245 if (ss) {
5246 /* css release path */
5247 if (!list_empty(&css->rstat_css_node)) {
5248 cgroup_rstat_flush(cgrp);
5249 list_del_rcu(&css->rstat_css_node);
5250 }
5251
5252 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
5253 if (ss->css_released)
5254 ss->css_released(css);
5255 } else {
5256 struct cgroup *tcgrp;
5257
5258 /* cgroup release path */
5259 TRACE_CGROUP_PATH(release, cgrp);
5260
5261 cgroup_rstat_flush(cgrp);
5262
5263 spin_lock_irq(&css_set_lock);
5264 for (tcgrp = cgroup_parent(cgrp); tcgrp;
5265 tcgrp = cgroup_parent(tcgrp))
5266 tcgrp->nr_dying_descendants--;
5267 spin_unlock_irq(&css_set_lock);
5268
5269 /*
5270 * There are two control paths which try to determine
5271 * cgroup from dentry without going through kernfs -
5272 * cgroupstats_build() and css_tryget_online_from_dir().
5273 * Those are supported by RCU protecting clearing of
5274 * cgrp->kn->priv backpointer.
5275 */
5276 if (cgrp->kn)
5277 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
5278 NULL);
5279 }
5280
5281 mutex_unlock(&cgroup_mutex);
5282
5283 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5284 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
5285 }
5286
css_release(struct percpu_ref * ref)5287 static void css_release(struct percpu_ref *ref)
5288 {
5289 struct cgroup_subsys_state *css =
5290 container_of(ref, struct cgroup_subsys_state, refcnt);
5291
5292 INIT_WORK(&css->destroy_work, css_release_work_fn);
5293 queue_work(cgroup_destroy_wq, &css->destroy_work);
5294 }
5295
init_and_link_css(struct cgroup_subsys_state * css,struct cgroup_subsys * ss,struct cgroup * cgrp)5296 static void init_and_link_css(struct cgroup_subsys_state *css,
5297 struct cgroup_subsys *ss, struct cgroup *cgrp)
5298 {
5299 lockdep_assert_held(&cgroup_mutex);
5300
5301 cgroup_get_live(cgrp);
5302
5303 memset(css, 0, sizeof(*css));
5304 css->cgroup = cgrp;
5305 css->ss = ss;
5306 css->id = -1;
5307 INIT_LIST_HEAD(&css->sibling);
5308 INIT_LIST_HEAD(&css->children);
5309 INIT_LIST_HEAD(&css->rstat_css_node);
5310 css->serial_nr = css_serial_nr_next++;
5311 atomic_set(&css->online_cnt, 0);
5312
5313 if (cgroup_parent(cgrp)) {
5314 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
5315 css_get(css->parent);
5316 }
5317
5318 if (ss->css_rstat_flush)
5319 list_add_rcu(&css->rstat_css_node, &cgrp->rstat_css_list);
5320
5321 BUG_ON(cgroup_css(cgrp, ss));
5322 }
5323
5324 /* invoke ->css_online() on a new CSS and mark it online if successful */
online_css(struct cgroup_subsys_state * css)5325 static int online_css(struct cgroup_subsys_state *css)
5326 {
5327 struct cgroup_subsys *ss = css->ss;
5328 int ret = 0;
5329
5330 lockdep_assert_held(&cgroup_mutex);
5331
5332 if (ss->css_online)
5333 ret = ss->css_online(css);
5334 if (!ret) {
5335 css->flags |= CSS_ONLINE;
5336 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
5337
5338 atomic_inc(&css->online_cnt);
5339 if (css->parent)
5340 atomic_inc(&css->parent->online_cnt);
5341 }
5342 return ret;
5343 }
5344
5345 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
offline_css(struct cgroup_subsys_state * css)5346 static void offline_css(struct cgroup_subsys_state *css)
5347 {
5348 struct cgroup_subsys *ss = css->ss;
5349
5350 lockdep_assert_held(&cgroup_mutex);
5351
5352 if (!(css->flags & CSS_ONLINE))
5353 return;
5354
5355 if (ss->css_offline)
5356 ss->css_offline(css);
5357
5358 css->flags &= ~CSS_ONLINE;
5359 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
5360
5361 wake_up_all(&css->cgroup->offline_waitq);
5362 }
5363
5364 /**
5365 * css_create - create a cgroup_subsys_state
5366 * @cgrp: the cgroup new css will be associated with
5367 * @ss: the subsys of new css
5368 *
5369 * Create a new css associated with @cgrp - @ss pair. On success, the new
5370 * css is online and installed in @cgrp. This function doesn't create the
5371 * interface files. Returns 0 on success, -errno on failure.
5372 */
css_create(struct cgroup * cgrp,struct cgroup_subsys * ss)5373 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
5374 struct cgroup_subsys *ss)
5375 {
5376 struct cgroup *parent = cgroup_parent(cgrp);
5377 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
5378 struct cgroup_subsys_state *css;
5379 int err;
5380
5381 lockdep_assert_held(&cgroup_mutex);
5382
5383 css = ss->css_alloc(parent_css);
5384 if (!css)
5385 css = ERR_PTR(-ENOMEM);
5386 if (IS_ERR(css))
5387 return css;
5388
5389 init_and_link_css(css, ss, cgrp);
5390
5391 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
5392 if (err)
5393 goto err_free_css;
5394
5395 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
5396 if (err < 0)
5397 goto err_free_css;
5398 css->id = err;
5399
5400 /* @css is ready to be brought online now, make it visible */
5401 list_add_tail_rcu(&css->sibling, &parent_css->children);
5402 cgroup_idr_replace(&ss->css_idr, css, css->id);
5403
5404 err = online_css(css);
5405 if (err)
5406 goto err_list_del;
5407
5408 return css;
5409
5410 err_list_del:
5411 list_del_rcu(&css->sibling);
5412 err_free_css:
5413 list_del_rcu(&css->rstat_css_node);
5414 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5415 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
5416 return ERR_PTR(err);
5417 }
5418
5419 /*
5420 * The returned cgroup is fully initialized including its control mask, but
5421 * it isn't associated with its kernfs_node and doesn't have the control
5422 * mask applied.
5423 */
cgroup_create(struct cgroup * parent,const char * name,umode_t mode)5424 static struct cgroup *cgroup_create(struct cgroup *parent, const char *name,
5425 umode_t mode)
5426 {
5427 struct cgroup_root *root = parent->root;
5428 struct cgroup *cgrp, *tcgrp;
5429 struct kernfs_node *kn;
5430 int level = parent->level + 1;
5431 int ret;
5432
5433 /* allocate the cgroup and its ID, 0 is reserved for the root */
5434 cgrp = kzalloc(struct_size(cgrp, ancestor_ids, (level + 1)),
5435 GFP_KERNEL);
5436 if (!cgrp)
5437 return ERR_PTR(-ENOMEM);
5438
5439 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
5440 if (ret)
5441 goto out_free_cgrp;
5442
5443 ret = cgroup_rstat_init(cgrp);
5444 if (ret)
5445 goto out_cancel_ref;
5446
5447 /* create the directory */
5448 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
5449 if (IS_ERR(kn)) {
5450 ret = PTR_ERR(kn);
5451 goto out_stat_exit;
5452 }
5453 cgrp->kn = kn;
5454
5455 init_cgroup_housekeeping(cgrp);
5456
5457 cgrp->self.parent = &parent->self;
5458 cgrp->root = root;
5459 cgrp->level = level;
5460
5461 ret = psi_cgroup_alloc(cgrp);
5462 if (ret)
5463 goto out_kernfs_remove;
5464
5465 ret = cgroup_bpf_inherit(cgrp);
5466 if (ret)
5467 goto out_psi_free;
5468
5469 /*
5470 * New cgroup inherits effective freeze counter, and
5471 * if the parent has to be frozen, the child has too.
5472 */
5473 cgrp->freezer.e_freeze = parent->freezer.e_freeze;
5474 if (cgrp->freezer.e_freeze) {
5475 /*
5476 * Set the CGRP_FREEZE flag, so when a process will be
5477 * attached to the child cgroup, it will become frozen.
5478 * At this point the new cgroup is unpopulated, so we can
5479 * consider it frozen immediately.
5480 */
5481 set_bit(CGRP_FREEZE, &cgrp->flags);
5482 set_bit(CGRP_FROZEN, &cgrp->flags);
5483 }
5484
5485 spin_lock_irq(&css_set_lock);
5486 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5487 cgrp->ancestor_ids[tcgrp->level] = cgroup_id(tcgrp);
5488
5489 if (tcgrp != cgrp) {
5490 tcgrp->nr_descendants++;
5491
5492 /*
5493 * If the new cgroup is frozen, all ancestor cgroups
5494 * get a new frozen descendant, but their state can't
5495 * change because of this.
5496 */
5497 if (cgrp->freezer.e_freeze)
5498 tcgrp->freezer.nr_frozen_descendants++;
5499 }
5500 }
5501 spin_unlock_irq(&css_set_lock);
5502
5503 if (notify_on_release(parent))
5504 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
5505
5506 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
5507 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
5508
5509 cgrp->self.serial_nr = css_serial_nr_next++;
5510
5511 /* allocation complete, commit to creation */
5512 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
5513 atomic_inc(&root->nr_cgrps);
5514 cgroup_get_live(parent);
5515
5516 /*
5517 * On the default hierarchy, a child doesn't automatically inherit
5518 * subtree_control from the parent. Each is configured manually.
5519 */
5520 if (!cgroup_on_dfl(cgrp))
5521 cgrp->subtree_control = cgroup_control(cgrp);
5522
5523 cgroup_propagate_control(cgrp);
5524
5525 return cgrp;
5526
5527 out_psi_free:
5528 psi_cgroup_free(cgrp);
5529 out_kernfs_remove:
5530 kernfs_remove(cgrp->kn);
5531 out_stat_exit:
5532 cgroup_rstat_exit(cgrp);
5533 out_cancel_ref:
5534 percpu_ref_exit(&cgrp->self.refcnt);
5535 out_free_cgrp:
5536 kfree(cgrp);
5537 return ERR_PTR(ret);
5538 }
5539
cgroup_check_hierarchy_limits(struct cgroup * parent)5540 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
5541 {
5542 struct cgroup *cgroup;
5543 int ret = false;
5544 int level = 1;
5545
5546 lockdep_assert_held(&cgroup_mutex);
5547
5548 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
5549 if (cgroup->nr_descendants >= cgroup->max_descendants)
5550 goto fail;
5551
5552 if (level > cgroup->max_depth)
5553 goto fail;
5554
5555 level++;
5556 }
5557
5558 ret = true;
5559 fail:
5560 return ret;
5561 }
5562
cgroup_mkdir(struct kernfs_node * parent_kn,const char * name,umode_t mode)5563 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
5564 {
5565 struct cgroup *parent, *cgrp;
5566 int ret;
5567
5568 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
5569 if (strchr(name, '\n'))
5570 return -EINVAL;
5571
5572 parent = cgroup_kn_lock_live(parent_kn, false);
5573 if (!parent)
5574 return -ENODEV;
5575
5576 if (!cgroup_check_hierarchy_limits(parent)) {
5577 ret = -EAGAIN;
5578 goto out_unlock;
5579 }
5580
5581 cgrp = cgroup_create(parent, name, mode);
5582 if (IS_ERR(cgrp)) {
5583 ret = PTR_ERR(cgrp);
5584 goto out_unlock;
5585 }
5586
5587 /*
5588 * This extra ref will be put in cgroup_free_fn() and guarantees
5589 * that @cgrp->kn is always accessible.
5590 */
5591 kernfs_get(cgrp->kn);
5592
5593 ret = cgroup_kn_set_ugid(cgrp->kn);
5594 if (ret)
5595 goto out_destroy;
5596
5597 ret = css_populate_dir(&cgrp->self);
5598 if (ret)
5599 goto out_destroy;
5600
5601 ret = cgroup_apply_control_enable(cgrp);
5602 if (ret)
5603 goto out_destroy;
5604
5605 TRACE_CGROUP_PATH(mkdir, cgrp);
5606
5607 /* let's create and online css's */
5608 kernfs_activate(cgrp->kn);
5609
5610 ret = 0;
5611 goto out_unlock;
5612
5613 out_destroy:
5614 cgroup_destroy_locked(cgrp);
5615 out_unlock:
5616 cgroup_kn_unlock(parent_kn);
5617 return ret;
5618 }
5619
5620 /*
5621 * This is called when the refcnt of a css is confirmed to be killed.
5622 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
5623 * initiate destruction and put the css ref from kill_css().
5624 */
css_killed_work_fn(struct work_struct * work)5625 static void css_killed_work_fn(struct work_struct *work)
5626 {
5627 struct cgroup_subsys_state *css =
5628 container_of(work, struct cgroup_subsys_state, destroy_work);
5629
5630 mutex_lock(&cgroup_mutex);
5631
5632 do {
5633 offline_css(css);
5634 css_put(css);
5635 /* @css can't go away while we're holding cgroup_mutex */
5636 css = css->parent;
5637 } while (css && atomic_dec_and_test(&css->online_cnt));
5638
5639 mutex_unlock(&cgroup_mutex);
5640 }
5641
5642 /* css kill confirmation processing requires process context, bounce */
css_killed_ref_fn(struct percpu_ref * ref)5643 static void css_killed_ref_fn(struct percpu_ref *ref)
5644 {
5645 struct cgroup_subsys_state *css =
5646 container_of(ref, struct cgroup_subsys_state, refcnt);
5647
5648 if (atomic_dec_and_test(&css->online_cnt)) {
5649 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5650 queue_work(cgroup_destroy_wq, &css->destroy_work);
5651 }
5652 }
5653
5654 /**
5655 * kill_css - destroy a css
5656 * @css: css to destroy
5657 *
5658 * This function initiates destruction of @css by removing cgroup interface
5659 * files and putting its base reference. ->css_offline() will be invoked
5660 * asynchronously once css_tryget_online() is guaranteed to fail and when
5661 * the reference count reaches zero, @css will be released.
5662 */
kill_css(struct cgroup_subsys_state * css)5663 static void kill_css(struct cgroup_subsys_state *css)
5664 {
5665 lockdep_assert_held(&cgroup_mutex);
5666
5667 if (css->flags & CSS_DYING)
5668 return;
5669
5670 css->flags |= CSS_DYING;
5671
5672 /*
5673 * This must happen before css is disassociated with its cgroup.
5674 * See seq_css() for details.
5675 */
5676 css_clear_dir(css);
5677
5678 /*
5679 * Killing would put the base ref, but we need to keep it alive
5680 * until after ->css_offline().
5681 */
5682 css_get(css);
5683
5684 /*
5685 * cgroup core guarantees that, by the time ->css_offline() is
5686 * invoked, no new css reference will be given out via
5687 * css_tryget_online(). We can't simply call percpu_ref_kill() and
5688 * proceed to offlining css's because percpu_ref_kill() doesn't
5689 * guarantee that the ref is seen as killed on all CPUs on return.
5690 *
5691 * Use percpu_ref_kill_and_confirm() to get notifications as each
5692 * css is confirmed to be seen as killed on all CPUs.
5693 */
5694 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5695 }
5696
5697 /**
5698 * cgroup_destroy_locked - the first stage of cgroup destruction
5699 * @cgrp: cgroup to be destroyed
5700 *
5701 * css's make use of percpu refcnts whose killing latency shouldn't be
5702 * exposed to userland and are RCU protected. Also, cgroup core needs to
5703 * guarantee that css_tryget_online() won't succeed by the time
5704 * ->css_offline() is invoked. To satisfy all the requirements,
5705 * destruction is implemented in the following two steps.
5706 *
5707 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
5708 * userland visible parts and start killing the percpu refcnts of
5709 * css's. Set up so that the next stage will be kicked off once all
5710 * the percpu refcnts are confirmed to be killed.
5711 *
5712 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5713 * rest of destruction. Once all cgroup references are gone, the
5714 * cgroup is RCU-freed.
5715 *
5716 * This function implements s1. After this step, @cgrp is gone as far as
5717 * the userland is concerned and a new cgroup with the same name may be
5718 * created. As cgroup doesn't care about the names internally, this
5719 * doesn't cause any problem.
5720 */
cgroup_destroy_locked(struct cgroup * cgrp)5721 static int cgroup_destroy_locked(struct cgroup *cgrp)
5722 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5723 {
5724 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5725 struct cgroup_subsys_state *css;
5726 struct cgrp_cset_link *link;
5727 int ssid;
5728
5729 lockdep_assert_held(&cgroup_mutex);
5730
5731 /*
5732 * Only migration can raise populated from zero and we're already
5733 * holding cgroup_mutex.
5734 */
5735 if (cgroup_is_populated(cgrp))
5736 return -EBUSY;
5737
5738 /*
5739 * Make sure there's no live children. We can't test emptiness of
5740 * ->self.children as dead children linger on it while being
5741 * drained; otherwise, "rmdir parent/child parent" may fail.
5742 */
5743 if (css_has_online_children(&cgrp->self))
5744 return -EBUSY;
5745
5746 /*
5747 * Mark @cgrp and the associated csets dead. The former prevents
5748 * further task migration and child creation by disabling
5749 * cgroup_lock_live_group(). The latter makes the csets ignored by
5750 * the migration path.
5751 */
5752 cgrp->self.flags &= ~CSS_ONLINE;
5753
5754 spin_lock_irq(&css_set_lock);
5755 list_for_each_entry(link, &cgrp->cset_links, cset_link)
5756 link->cset->dead = true;
5757 spin_unlock_irq(&css_set_lock);
5758
5759 /* initiate massacre of all css's */
5760 for_each_css(css, ssid, cgrp)
5761 kill_css(css);
5762
5763 /* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
5764 css_clear_dir(&cgrp->self);
5765 kernfs_remove(cgrp->kn);
5766
5767 if (parent && cgroup_is_threaded(cgrp))
5768 parent->nr_threaded_children--;
5769
5770 spin_lock_irq(&css_set_lock);
5771 for (tcgrp = cgroup_parent(cgrp); tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5772 tcgrp->nr_descendants--;
5773 tcgrp->nr_dying_descendants++;
5774 /*
5775 * If the dying cgroup is frozen, decrease frozen descendants
5776 * counters of ancestor cgroups.
5777 */
5778 if (test_bit(CGRP_FROZEN, &cgrp->flags))
5779 tcgrp->freezer.nr_frozen_descendants--;
5780 }
5781 spin_unlock_irq(&css_set_lock);
5782
5783 cgroup1_check_for_release(parent);
5784
5785 cgroup_bpf_offline(cgrp);
5786
5787 /* put the base reference */
5788 percpu_ref_kill(&cgrp->self.refcnt);
5789
5790 return 0;
5791 };
5792
cgroup_rmdir(struct kernfs_node * kn)5793 int cgroup_rmdir(struct kernfs_node *kn)
5794 {
5795 struct cgroup *cgrp;
5796 int ret = 0;
5797
5798 cgrp = cgroup_kn_lock_live(kn, false);
5799 if (!cgrp)
5800 return 0;
5801
5802 ret = cgroup_destroy_locked(cgrp);
5803 if (!ret)
5804 TRACE_CGROUP_PATH(rmdir, cgrp);
5805
5806 cgroup_kn_unlock(kn);
5807 return ret;
5808 }
5809
5810 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5811 .show_options = cgroup_show_options,
5812 .mkdir = cgroup_mkdir,
5813 .rmdir = cgroup_rmdir,
5814 .show_path = cgroup_show_path,
5815 };
5816
cgroup_init_subsys(struct cgroup_subsys * ss,bool early)5817 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5818 {
5819 struct cgroup_subsys_state *css;
5820
5821 pr_debug("Initializing cgroup subsys %s\n", ss->name);
5822
5823 mutex_lock(&cgroup_mutex);
5824
5825 idr_init(&ss->css_idr);
5826 INIT_LIST_HEAD(&ss->cfts);
5827
5828 /* Create the root cgroup state for this subsystem */
5829 ss->root = &cgrp_dfl_root;
5830 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5831 /* We don't handle early failures gracefully */
5832 BUG_ON(IS_ERR(css));
5833 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5834
5835 /*
5836 * Root csses are never destroyed and we can't initialize
5837 * percpu_ref during early init. Disable refcnting.
5838 */
5839 css->flags |= CSS_NO_REF;
5840
5841 if (early) {
5842 /* allocation can't be done safely during early init */
5843 css->id = 1;
5844 } else {
5845 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5846 BUG_ON(css->id < 0);
5847 }
5848
5849 /* Update the init_css_set to contain a subsys
5850 * pointer to this state - since the subsystem is
5851 * newly registered, all tasks and hence the
5852 * init_css_set is in the subsystem's root cgroup. */
5853 init_css_set.subsys[ss->id] = css;
5854
5855 have_fork_callback |= (bool)ss->fork << ss->id;
5856 have_exit_callback |= (bool)ss->exit << ss->id;
5857 have_release_callback |= (bool)ss->release << ss->id;
5858 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5859
5860 /* At system boot, before all subsystems have been
5861 * registered, no tasks have been forked, so we don't
5862 * need to invoke fork callbacks here. */
5863 BUG_ON(!list_empty(&init_task.tasks));
5864
5865 BUG_ON(online_css(css));
5866
5867 mutex_unlock(&cgroup_mutex);
5868 }
5869
5870 /**
5871 * cgroup_init_early - cgroup initialization at system boot
5872 *
5873 * Initialize cgroups at system boot, and initialize any
5874 * subsystems that request early init.
5875 */
cgroup_init_early(void)5876 int __init cgroup_init_early(void)
5877 {
5878 static struct cgroup_fs_context __initdata ctx;
5879 struct cgroup_subsys *ss;
5880 int i;
5881
5882 ctx.root = &cgrp_dfl_root;
5883 init_cgroup_root(&ctx);
5884 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5885
5886 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5887
5888 for_each_subsys(ss, i) {
5889 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5890 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
5891 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5892 ss->id, ss->name);
5893 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5894 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5895
5896 ss->id = i;
5897 ss->name = cgroup_subsys_name[i];
5898 if (!ss->legacy_name)
5899 ss->legacy_name = cgroup_subsys_name[i];
5900
5901 if (ss->early_init)
5902 cgroup_init_subsys(ss, true);
5903 }
5904 return 0;
5905 }
5906
5907 /**
5908 * cgroup_init - cgroup initialization
5909 *
5910 * Register cgroup filesystem and /proc file, and initialize
5911 * any subsystems that didn't request early init.
5912 */
cgroup_init(void)5913 int __init cgroup_init(void)
5914 {
5915 struct cgroup_subsys *ss;
5916 int ssid;
5917
5918 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
5919 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
5920 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
5921
5922 cgroup_rstat_boot();
5923
5924 /*
5925 * The latency of the synchronize_rcu() is too high for cgroups,
5926 * avoid it at the cost of forcing all readers into the slow path.
5927 */
5928 rcu_sync_enter_start(&cgroup_threadgroup_rwsem.rss);
5929
5930 get_user_ns(init_cgroup_ns.user_ns);
5931
5932 mutex_lock(&cgroup_mutex);
5933
5934 /*
5935 * Add init_css_set to the hash table so that dfl_root can link to
5936 * it during init.
5937 */
5938 hash_add(css_set_table, &init_css_set.hlist,
5939 css_set_hash(init_css_set.subsys));
5940
5941 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
5942
5943 mutex_unlock(&cgroup_mutex);
5944
5945 for_each_subsys(ss, ssid) {
5946 if (ss->early_init) {
5947 struct cgroup_subsys_state *css =
5948 init_css_set.subsys[ss->id];
5949
5950 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5951 GFP_KERNEL);
5952 BUG_ON(css->id < 0);
5953 } else {
5954 cgroup_init_subsys(ss, false);
5955 }
5956
5957 list_add_tail(&init_css_set.e_cset_node[ssid],
5958 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5959
5960 /*
5961 * Setting dfl_root subsys_mask needs to consider the
5962 * disabled flag and cftype registration needs kmalloc,
5963 * both of which aren't available during early_init.
5964 */
5965 if (!cgroup_ssid_enabled(ssid))
5966 continue;
5967
5968 if (cgroup1_ssid_disabled(ssid))
5969 printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
5970 ss->name);
5971
5972 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5973
5974 /* implicit controllers must be threaded too */
5975 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
5976
5977 if (ss->implicit_on_dfl)
5978 cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
5979 else if (!ss->dfl_cftypes)
5980 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
5981
5982 if (ss->threaded)
5983 cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
5984
5985 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5986 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5987 } else {
5988 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5989 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5990 }
5991
5992 if (ss->bind)
5993 ss->bind(init_css_set.subsys[ssid]);
5994
5995 mutex_lock(&cgroup_mutex);
5996 css_populate_dir(init_css_set.subsys[ssid]);
5997 mutex_unlock(&cgroup_mutex);
5998 }
5999
6000 /* init_css_set.subsys[] has been updated, re-hash */
6001 hash_del(&init_css_set.hlist);
6002 hash_add(css_set_table, &init_css_set.hlist,
6003 css_set_hash(init_css_set.subsys));
6004
6005 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
6006 WARN_ON(register_filesystem(&cgroup_fs_type));
6007 WARN_ON(register_filesystem(&cgroup2_fs_type));
6008 WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show));
6009 #ifdef CONFIG_CPUSETS
6010 WARN_ON(register_filesystem(&cpuset_fs_type));
6011 #endif
6012
6013 return 0;
6014 }
6015
cgroup_wq_init(void)6016 static int __init cgroup_wq_init(void)
6017 {
6018 /*
6019 * There isn't much point in executing destruction path in
6020 * parallel. Good chunk is serialized with cgroup_mutex anyway.
6021 * Use 1 for @max_active.
6022 *
6023 * We would prefer to do this in cgroup_init() above, but that
6024 * is called before init_workqueues(): so leave this until after.
6025 */
6026 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
6027 BUG_ON(!cgroup_destroy_wq);
6028 return 0;
6029 }
6030 core_initcall(cgroup_wq_init);
6031
cgroup_path_from_kernfs_id(u64 id,char * buf,size_t buflen)6032 void cgroup_path_from_kernfs_id(u64 id, char *buf, size_t buflen)
6033 {
6034 struct kernfs_node *kn;
6035
6036 kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6037 if (!kn)
6038 return;
6039 kernfs_path(kn, buf, buflen);
6040 kernfs_put(kn);
6041 }
6042
6043 /*
6044 * cgroup_get_from_id : get the cgroup associated with cgroup id
6045 * @id: cgroup id
6046 * On success return the cgrp, on failure return NULL
6047 */
cgroup_get_from_id(u64 id)6048 struct cgroup *cgroup_get_from_id(u64 id)
6049 {
6050 struct kernfs_node *kn;
6051 struct cgroup *cgrp = NULL;
6052
6053 kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6054 if (!kn)
6055 goto out;
6056
6057 if (kernfs_type(kn) != KERNFS_DIR)
6058 goto put;
6059
6060 rcu_read_lock();
6061
6062 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6063 if (cgrp && !cgroup_tryget(cgrp))
6064 cgrp = NULL;
6065
6066 rcu_read_unlock();
6067 put:
6068 kernfs_put(kn);
6069 out:
6070 return cgrp;
6071 }
6072 EXPORT_SYMBOL_GPL(cgroup_get_from_id);
6073
6074 /*
6075 * proc_cgroup_show()
6076 * - Print task's cgroup paths into seq_file, one line for each hierarchy
6077 * - Used for /proc/<pid>/cgroup.
6078 */
proc_cgroup_show(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * tsk)6079 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
6080 struct pid *pid, struct task_struct *tsk)
6081 {
6082 char *buf;
6083 int retval;
6084 struct cgroup_root *root;
6085
6086 retval = -ENOMEM;
6087 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6088 if (!buf)
6089 goto out;
6090
6091 mutex_lock(&cgroup_mutex);
6092 spin_lock_irq(&css_set_lock);
6093
6094 for_each_root(root) {
6095 struct cgroup_subsys *ss;
6096 struct cgroup *cgrp;
6097 int ssid, count = 0;
6098
6099 if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
6100 continue;
6101
6102 seq_printf(m, "%d:", root->hierarchy_id);
6103 if (root != &cgrp_dfl_root)
6104 for_each_subsys(ss, ssid)
6105 if (root->subsys_mask & (1 << ssid))
6106 seq_printf(m, "%s%s", count++ ? "," : "",
6107 ss->legacy_name);
6108 if (strlen(root->name))
6109 seq_printf(m, "%sname=%s", count ? "," : "",
6110 root->name);
6111 seq_putc(m, ':');
6112
6113 cgrp = task_cgroup_from_root(tsk, root);
6114
6115 /*
6116 * On traditional hierarchies, all zombie tasks show up as
6117 * belonging to the root cgroup. On the default hierarchy,
6118 * while a zombie doesn't show up in "cgroup.procs" and
6119 * thus can't be migrated, its /proc/PID/cgroup keeps
6120 * reporting the cgroup it belonged to before exiting. If
6121 * the cgroup is removed before the zombie is reaped,
6122 * " (deleted)" is appended to the cgroup path.
6123 */
6124 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
6125 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
6126 current->nsproxy->cgroup_ns);
6127 if (retval >= PATH_MAX)
6128 retval = -ENAMETOOLONG;
6129 if (retval < 0)
6130 goto out_unlock;
6131
6132 seq_puts(m, buf);
6133 } else {
6134 seq_puts(m, "/");
6135 }
6136
6137 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
6138 seq_puts(m, " (deleted)\n");
6139 else
6140 seq_putc(m, '\n');
6141 }
6142
6143 retval = 0;
6144 out_unlock:
6145 spin_unlock_irq(&css_set_lock);
6146 mutex_unlock(&cgroup_mutex);
6147 kfree(buf);
6148 out:
6149 return retval;
6150 }
6151
6152 /**
6153 * cgroup_fork - initialize cgroup related fields during copy_process()
6154 * @child: pointer to task_struct of forking parent process.
6155 *
6156 * A task is associated with the init_css_set until cgroup_post_fork()
6157 * attaches it to the target css_set.
6158 */
cgroup_fork(struct task_struct * child)6159 void cgroup_fork(struct task_struct *child)
6160 {
6161 RCU_INIT_POINTER(child->cgroups, &init_css_set);
6162 INIT_LIST_HEAD(&child->cg_list);
6163 }
6164
cgroup_get_from_file(struct file * f)6165 static struct cgroup *cgroup_get_from_file(struct file *f)
6166 {
6167 struct cgroup_subsys_state *css;
6168 struct cgroup *cgrp;
6169
6170 css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
6171 if (IS_ERR(css))
6172 return ERR_CAST(css);
6173
6174 cgrp = css->cgroup;
6175 if (!cgroup_on_dfl(cgrp)) {
6176 cgroup_put(cgrp);
6177 return ERR_PTR(-EBADF);
6178 }
6179
6180 return cgrp;
6181 }
6182
6183 /**
6184 * cgroup_css_set_fork - find or create a css_set for a child process
6185 * @kargs: the arguments passed to create the child process
6186 *
6187 * This functions finds or creates a new css_set which the child
6188 * process will be attached to in cgroup_post_fork(). By default,
6189 * the child process will be given the same css_set as its parent.
6190 *
6191 * If CLONE_INTO_CGROUP is specified this function will try to find an
6192 * existing css_set which includes the requested cgroup and if not create
6193 * a new css_set that the child will be attached to later. If this function
6194 * succeeds it will hold cgroup_threadgroup_rwsem on return. If
6195 * CLONE_INTO_CGROUP is requested this function will grab cgroup mutex
6196 * before grabbing cgroup_threadgroup_rwsem and will hold a reference
6197 * to the target cgroup.
6198 */
cgroup_css_set_fork(struct kernel_clone_args * kargs)6199 static int cgroup_css_set_fork(struct kernel_clone_args *kargs)
6200 __acquires(&cgroup_mutex) __acquires(&cgroup_threadgroup_rwsem)
6201 {
6202 int ret;
6203 struct cgroup *dst_cgrp = NULL;
6204 struct css_set *cset;
6205 struct super_block *sb;
6206 struct file *f;
6207
6208 if (kargs->flags & CLONE_INTO_CGROUP)
6209 mutex_lock(&cgroup_mutex);
6210
6211 cgroup_threadgroup_change_begin(current);
6212
6213 spin_lock_irq(&css_set_lock);
6214 cset = task_css_set(current);
6215 get_css_set(cset);
6216 spin_unlock_irq(&css_set_lock);
6217
6218 if (!(kargs->flags & CLONE_INTO_CGROUP)) {
6219 kargs->cset = cset;
6220 return 0;
6221 }
6222
6223 f = fget_raw(kargs->cgroup);
6224 if (!f) {
6225 ret = -EBADF;
6226 goto err;
6227 }
6228 sb = f->f_path.dentry->d_sb;
6229
6230 dst_cgrp = cgroup_get_from_file(f);
6231 if (IS_ERR(dst_cgrp)) {
6232 ret = PTR_ERR(dst_cgrp);
6233 dst_cgrp = NULL;
6234 goto err;
6235 }
6236
6237 if (cgroup_is_dead(dst_cgrp)) {
6238 ret = -ENODEV;
6239 goto err;
6240 }
6241
6242 /*
6243 * Verify that we the target cgroup is writable for us. This is
6244 * usually done by the vfs layer but since we're not going through
6245 * the vfs layer here we need to do it "manually".
6246 */
6247 ret = cgroup_may_write(dst_cgrp, sb);
6248 if (ret)
6249 goto err;
6250
6251 ret = cgroup_attach_permissions(cset->dfl_cgrp, dst_cgrp, sb,
6252 !(kargs->flags & CLONE_THREAD),
6253 current->nsproxy->cgroup_ns);
6254 if (ret)
6255 goto err;
6256
6257 kargs->cset = find_css_set(cset, dst_cgrp);
6258 if (!kargs->cset) {
6259 ret = -ENOMEM;
6260 goto err;
6261 }
6262
6263 put_css_set(cset);
6264 fput(f);
6265 kargs->cgrp = dst_cgrp;
6266 return ret;
6267
6268 err:
6269 cgroup_threadgroup_change_end(current);
6270 mutex_unlock(&cgroup_mutex);
6271 if (f)
6272 fput(f);
6273 if (dst_cgrp)
6274 cgroup_put(dst_cgrp);
6275 put_css_set(cset);
6276 if (kargs->cset)
6277 put_css_set(kargs->cset);
6278 return ret;
6279 }
6280
6281 /**
6282 * cgroup_css_set_put_fork - drop references we took during fork
6283 * @kargs: the arguments passed to create the child process
6284 *
6285 * Drop references to the prepared css_set and target cgroup if
6286 * CLONE_INTO_CGROUP was requested.
6287 */
cgroup_css_set_put_fork(struct kernel_clone_args * kargs)6288 static void cgroup_css_set_put_fork(struct kernel_clone_args *kargs)
6289 __releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6290 {
6291 struct cgroup *cgrp = kargs->cgrp;
6292 struct css_set *cset = kargs->cset;
6293
6294 cgroup_threadgroup_change_end(current);
6295
6296 if (cset) {
6297 put_css_set(cset);
6298 kargs->cset = NULL;
6299 }
6300
6301 if (kargs->flags & CLONE_INTO_CGROUP) {
6302 mutex_unlock(&cgroup_mutex);
6303 if (cgrp) {
6304 cgroup_put(cgrp);
6305 kargs->cgrp = NULL;
6306 }
6307 }
6308 }
6309
6310 /**
6311 * cgroup_can_fork - called on a new task before the process is exposed
6312 * @child: the child process
6313 *
6314 * This prepares a new css_set for the child process which the child will
6315 * be attached to in cgroup_post_fork().
6316 * This calls the subsystem can_fork() callbacks. If the cgroup_can_fork()
6317 * callback returns an error, the fork aborts with that error code. This
6318 * allows for a cgroup subsystem to conditionally allow or deny new forks.
6319 */
cgroup_can_fork(struct task_struct * child,struct kernel_clone_args * kargs)6320 int cgroup_can_fork(struct task_struct *child, struct kernel_clone_args *kargs)
6321 {
6322 struct cgroup_subsys *ss;
6323 int i, j, ret;
6324
6325 ret = cgroup_css_set_fork(kargs);
6326 if (ret)
6327 return ret;
6328
6329 do_each_subsys_mask(ss, i, have_canfork_callback) {
6330 ret = ss->can_fork(child, kargs->cset);
6331 if (ret)
6332 goto out_revert;
6333 } while_each_subsys_mask();
6334
6335 return 0;
6336
6337 out_revert:
6338 for_each_subsys(ss, j) {
6339 if (j >= i)
6340 break;
6341 if (ss->cancel_fork)
6342 ss->cancel_fork(child, kargs->cset);
6343 }
6344
6345 cgroup_css_set_put_fork(kargs);
6346
6347 return ret;
6348 }
6349
6350 /**
6351 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
6352 * @child: the child process
6353 * @kargs: the arguments passed to create the child process
6354 *
6355 * This calls the cancel_fork() callbacks if a fork failed *after*
6356 * cgroup_can_fork() succeeded and cleans up references we took to
6357 * prepare a new css_set for the child process in cgroup_can_fork().
6358 */
cgroup_cancel_fork(struct task_struct * child,struct kernel_clone_args * kargs)6359 void cgroup_cancel_fork(struct task_struct *child,
6360 struct kernel_clone_args *kargs)
6361 {
6362 struct cgroup_subsys *ss;
6363 int i;
6364
6365 for_each_subsys(ss, i)
6366 if (ss->cancel_fork)
6367 ss->cancel_fork(child, kargs->cset);
6368
6369 cgroup_css_set_put_fork(kargs);
6370 }
6371
6372 /**
6373 * cgroup_post_fork - finalize cgroup setup for the child process
6374 * @child: the child process
6375 *
6376 * Attach the child process to its css_set calling the subsystem fork()
6377 * callbacks.
6378 */
cgroup_post_fork(struct task_struct * child,struct kernel_clone_args * kargs)6379 void cgroup_post_fork(struct task_struct *child,
6380 struct kernel_clone_args *kargs)
6381 __releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6382 {
6383 unsigned long cgrp_flags = 0;
6384 bool kill = false;
6385 struct cgroup_subsys *ss;
6386 struct css_set *cset;
6387 int i;
6388
6389 cset = kargs->cset;
6390 kargs->cset = NULL;
6391
6392 spin_lock_irq(&css_set_lock);
6393
6394 /* init tasks are special, only link regular threads */
6395 if (likely(child->pid)) {
6396 if (kargs->cgrp)
6397 cgrp_flags = kargs->cgrp->flags;
6398 else
6399 cgrp_flags = cset->dfl_cgrp->flags;
6400
6401 WARN_ON_ONCE(!list_empty(&child->cg_list));
6402 cset->nr_tasks++;
6403 css_set_move_task(child, NULL, cset, false);
6404 } else {
6405 put_css_set(cset);
6406 cset = NULL;
6407 }
6408
6409 if (!(child->flags & PF_KTHREAD)) {
6410 if (unlikely(test_bit(CGRP_FREEZE, &cgrp_flags))) {
6411 /*
6412 * If the cgroup has to be frozen, the new task has
6413 * too. Let's set the JOBCTL_TRAP_FREEZE jobctl bit to
6414 * get the task into the frozen state.
6415 */
6416 spin_lock(&child->sighand->siglock);
6417 WARN_ON_ONCE(child->frozen);
6418 child->jobctl |= JOBCTL_TRAP_FREEZE;
6419 spin_unlock(&child->sighand->siglock);
6420
6421 /*
6422 * Calling cgroup_update_frozen() isn't required here,
6423 * because it will be called anyway a bit later from
6424 * do_freezer_trap(). So we avoid cgroup's transient
6425 * switch from the frozen state and back.
6426 */
6427 }
6428
6429 /*
6430 * If the cgroup is to be killed notice it now and take the
6431 * child down right after we finished preparing it for
6432 * userspace.
6433 */
6434 kill = test_bit(CGRP_KILL, &cgrp_flags);
6435 }
6436
6437 spin_unlock_irq(&css_set_lock);
6438
6439 /*
6440 * Call ss->fork(). This must happen after @child is linked on
6441 * css_set; otherwise, @child might change state between ->fork()
6442 * and addition to css_set.
6443 */
6444 do_each_subsys_mask(ss, i, have_fork_callback) {
6445 ss->fork(child);
6446 } while_each_subsys_mask();
6447
6448 /* Make the new cset the root_cset of the new cgroup namespace. */
6449 if (kargs->flags & CLONE_NEWCGROUP) {
6450 struct css_set *rcset = child->nsproxy->cgroup_ns->root_cset;
6451
6452 get_css_set(cset);
6453 child->nsproxy->cgroup_ns->root_cset = cset;
6454 put_css_set(rcset);
6455 }
6456
6457 /* Cgroup has to be killed so take down child immediately. */
6458 if (unlikely(kill))
6459 do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, child, PIDTYPE_TGID);
6460
6461 cgroup_css_set_put_fork(kargs);
6462 }
6463
6464 /**
6465 * cgroup_exit - detach cgroup from exiting task
6466 * @tsk: pointer to task_struct of exiting process
6467 *
6468 * Description: Detach cgroup from @tsk.
6469 *
6470 */
cgroup_exit(struct task_struct * tsk)6471 void cgroup_exit(struct task_struct *tsk)
6472 {
6473 struct cgroup_subsys *ss;
6474 struct css_set *cset;
6475 int i;
6476
6477 spin_lock_irq(&css_set_lock);
6478
6479 WARN_ON_ONCE(list_empty(&tsk->cg_list));
6480 cset = task_css_set(tsk);
6481 css_set_move_task(tsk, cset, NULL, false);
6482 list_add_tail(&tsk->cg_list, &cset->dying_tasks);
6483 cset->nr_tasks--;
6484
6485 if (dl_task(tsk))
6486 dec_dl_tasks_cs(tsk);
6487
6488 WARN_ON_ONCE(cgroup_task_frozen(tsk));
6489 if (unlikely(!(tsk->flags & PF_KTHREAD) &&
6490 test_bit(CGRP_FREEZE, &task_dfl_cgroup(tsk)->flags)))
6491 cgroup_update_frozen(task_dfl_cgroup(tsk));
6492
6493 spin_unlock_irq(&css_set_lock);
6494
6495 /* see cgroup_post_fork() for details */
6496 do_each_subsys_mask(ss, i, have_exit_callback) {
6497 ss->exit(tsk);
6498 } while_each_subsys_mask();
6499 }
6500
cgroup_release(struct task_struct * task)6501 void cgroup_release(struct task_struct *task)
6502 {
6503 struct cgroup_subsys *ss;
6504 int ssid;
6505
6506 do_each_subsys_mask(ss, ssid, have_release_callback) {
6507 ss->release(task);
6508 } while_each_subsys_mask();
6509
6510 spin_lock_irq(&css_set_lock);
6511 css_set_skip_task_iters(task_css_set(task), task);
6512 list_del_init(&task->cg_list);
6513 spin_unlock_irq(&css_set_lock);
6514 }
6515
cgroup_free(struct task_struct * task)6516 void cgroup_free(struct task_struct *task)
6517 {
6518 struct css_set *cset = task_css_set(task);
6519 put_css_set(cset);
6520 }
6521
cgroup_disable(char * str)6522 static int __init cgroup_disable(char *str)
6523 {
6524 struct cgroup_subsys *ss;
6525 char *token;
6526 int i;
6527
6528 while ((token = strsep(&str, ",")) != NULL) {
6529 if (!*token)
6530 continue;
6531
6532 for_each_subsys(ss, i) {
6533 if (strcmp(token, ss->name) &&
6534 strcmp(token, ss->legacy_name))
6535 continue;
6536
6537 static_branch_disable(cgroup_subsys_enabled_key[i]);
6538 pr_info("Disabling %s control group subsystem\n",
6539 ss->name);
6540 }
6541
6542 for (i = 0; i < OPT_FEATURE_COUNT; i++) {
6543 if (strcmp(token, cgroup_opt_feature_names[i]))
6544 continue;
6545 cgroup_feature_disable_mask |= 1 << i;
6546 pr_info("Disabling %s control group feature\n",
6547 cgroup_opt_feature_names[i]);
6548 break;
6549 }
6550 }
6551 return 1;
6552 }
6553 __setup("cgroup_disable=", cgroup_disable);
6554
enable_debug_cgroup(void)6555 void __init __weak enable_debug_cgroup(void) { }
6556
enable_cgroup_debug(char * str)6557 static int __init enable_cgroup_debug(char *str)
6558 {
6559 cgroup_debug = true;
6560 enable_debug_cgroup();
6561 return 1;
6562 }
6563 __setup("cgroup_debug", enable_cgroup_debug);
6564
6565 /**
6566 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
6567 * @dentry: directory dentry of interest
6568 * @ss: subsystem of interest
6569 *
6570 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
6571 * to get the corresponding css and return it. If such css doesn't exist
6572 * or can't be pinned, an ERR_PTR value is returned.
6573 */
css_tryget_online_from_dir(struct dentry * dentry,struct cgroup_subsys * ss)6574 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
6575 struct cgroup_subsys *ss)
6576 {
6577 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
6578 struct file_system_type *s_type = dentry->d_sb->s_type;
6579 struct cgroup_subsys_state *css = NULL;
6580 struct cgroup *cgrp;
6581
6582 /* is @dentry a cgroup dir? */
6583 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
6584 !kn || kernfs_type(kn) != KERNFS_DIR)
6585 return ERR_PTR(-EBADF);
6586
6587 rcu_read_lock();
6588
6589 /*
6590 * This path doesn't originate from kernfs and @kn could already
6591 * have been or be removed at any point. @kn->priv is RCU
6592 * protected for this access. See css_release_work_fn() for details.
6593 */
6594 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6595 if (cgrp)
6596 css = cgroup_css(cgrp, ss);
6597
6598 if (!css || !css_tryget_online(css))
6599 css = ERR_PTR(-ENOENT);
6600
6601 rcu_read_unlock();
6602 return css;
6603 }
6604
6605 /**
6606 * css_from_id - lookup css by id
6607 * @id: the cgroup id
6608 * @ss: cgroup subsys to be looked into
6609 *
6610 * Returns the css if there's valid one with @id, otherwise returns NULL.
6611 * Should be called under rcu_read_lock().
6612 */
css_from_id(int id,struct cgroup_subsys * ss)6613 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
6614 {
6615 WARN_ON_ONCE(!rcu_read_lock_held());
6616 return idr_find(&ss->css_idr, id);
6617 }
6618
6619 /**
6620 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
6621 * @path: path on the default hierarchy
6622 *
6623 * Find the cgroup at @path on the default hierarchy, increment its
6624 * reference count and return it. Returns pointer to the found cgroup on
6625 * success, ERR_PTR(-ENOENT) if @path doesn't exist or if the cgroup has already
6626 * been released and ERR_PTR(-ENOTDIR) if @path points to a non-directory.
6627 */
cgroup_get_from_path(const char * path)6628 struct cgroup *cgroup_get_from_path(const char *path)
6629 {
6630 struct kernfs_node *kn;
6631 struct cgroup *cgrp = ERR_PTR(-ENOENT);
6632 struct cgroup *root_cgrp;
6633
6634 spin_lock_irq(&css_set_lock);
6635 root_cgrp = current_cgns_cgroup_from_root(&cgrp_dfl_root);
6636 kn = kernfs_walk_and_get(root_cgrp->kn, path);
6637 spin_unlock_irq(&css_set_lock);
6638 if (!kn)
6639 goto out;
6640
6641 if (kernfs_type(kn) != KERNFS_DIR) {
6642 cgrp = ERR_PTR(-ENOTDIR);
6643 goto out_kernfs;
6644 }
6645
6646 rcu_read_lock();
6647
6648 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6649 if (!cgrp || !cgroup_tryget(cgrp))
6650 cgrp = ERR_PTR(-ENOENT);
6651
6652 rcu_read_unlock();
6653
6654 out_kernfs:
6655 kernfs_put(kn);
6656 out:
6657 return cgrp;
6658 }
6659 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
6660
6661 /**
6662 * cgroup_get_from_fd - get a cgroup pointer from a fd
6663 * @fd: fd obtained by open(cgroup2_dir)
6664 *
6665 * Find the cgroup from a fd which should be obtained
6666 * by opening a cgroup directory. Returns a pointer to the
6667 * cgroup on success. ERR_PTR is returned if the cgroup
6668 * cannot be found.
6669 */
cgroup_get_from_fd(int fd)6670 struct cgroup *cgroup_get_from_fd(int fd)
6671 {
6672 struct cgroup *cgrp;
6673 struct file *f;
6674
6675 f = fget_raw(fd);
6676 if (!f)
6677 return ERR_PTR(-EBADF);
6678
6679 cgrp = cgroup_get_from_file(f);
6680 fput(f);
6681 return cgrp;
6682 }
6683 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
6684
power_of_ten(int power)6685 static u64 power_of_ten(int power)
6686 {
6687 u64 v = 1;
6688 while (power--)
6689 v *= 10;
6690 return v;
6691 }
6692
6693 /**
6694 * cgroup_parse_float - parse a floating number
6695 * @input: input string
6696 * @dec_shift: number of decimal digits to shift
6697 * @v: output
6698 *
6699 * Parse a decimal floating point number in @input and store the result in
6700 * @v with decimal point right shifted @dec_shift times. For example, if
6701 * @input is "12.3456" and @dec_shift is 3, *@v will be set to 12345.
6702 * Returns 0 on success, -errno otherwise.
6703 *
6704 * There's nothing cgroup specific about this function except that it's
6705 * currently the only user.
6706 */
cgroup_parse_float(const char * input,unsigned dec_shift,s64 * v)6707 int cgroup_parse_float(const char *input, unsigned dec_shift, s64 *v)
6708 {
6709 s64 whole, frac = 0;
6710 int fstart = 0, fend = 0, flen;
6711
6712 if (!sscanf(input, "%lld.%n%lld%n", &whole, &fstart, &frac, &fend))
6713 return -EINVAL;
6714 if (frac < 0)
6715 return -EINVAL;
6716
6717 flen = fend > fstart ? fend - fstart : 0;
6718 if (flen < dec_shift)
6719 frac *= power_of_ten(dec_shift - flen);
6720 else
6721 frac = DIV_ROUND_CLOSEST_ULL(frac, power_of_ten(flen - dec_shift));
6722
6723 *v = whole * power_of_ten(dec_shift) + frac;
6724 return 0;
6725 }
6726
6727 /*
6728 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
6729 * definition in cgroup-defs.h.
6730 */
6731 #ifdef CONFIG_SOCK_CGROUP_DATA
6732
cgroup_sk_alloc(struct sock_cgroup_data * skcd)6733 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
6734 {
6735 struct cgroup *cgroup;
6736
6737 rcu_read_lock();
6738 /* Don't associate the sock with unrelated interrupted task's cgroup. */
6739 if (in_interrupt()) {
6740 cgroup = &cgrp_dfl_root.cgrp;
6741 cgroup_get(cgroup);
6742 goto out;
6743 }
6744
6745 while (true) {
6746 struct css_set *cset;
6747
6748 cset = task_css_set(current);
6749 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
6750 cgroup = cset->dfl_cgrp;
6751 break;
6752 }
6753 cpu_relax();
6754 }
6755 out:
6756 skcd->cgroup = cgroup;
6757 cgroup_bpf_get(cgroup);
6758 rcu_read_unlock();
6759 }
6760
cgroup_sk_clone(struct sock_cgroup_data * skcd)6761 void cgroup_sk_clone(struct sock_cgroup_data *skcd)
6762 {
6763 struct cgroup *cgrp = sock_cgroup_ptr(skcd);
6764
6765 /*
6766 * We might be cloning a socket which is left in an empty
6767 * cgroup and the cgroup might have already been rmdir'd.
6768 * Don't use cgroup_get_live().
6769 */
6770 cgroup_get(cgrp);
6771 cgroup_bpf_get(cgrp);
6772 }
6773
cgroup_sk_free(struct sock_cgroup_data * skcd)6774 void cgroup_sk_free(struct sock_cgroup_data *skcd)
6775 {
6776 struct cgroup *cgrp = sock_cgroup_ptr(skcd);
6777
6778 cgroup_bpf_put(cgrp);
6779 cgroup_put(cgrp);
6780 }
6781
6782 #endif /* CONFIG_SOCK_CGROUP_DATA */
6783
6784 #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)6785 int cgroup_bpf_attach(struct cgroup *cgrp,
6786 struct bpf_prog *prog, struct bpf_prog *replace_prog,
6787 struct bpf_cgroup_link *link,
6788 enum bpf_attach_type type,
6789 u32 flags)
6790 {
6791 int ret;
6792
6793 mutex_lock(&cgroup_mutex);
6794 ret = __cgroup_bpf_attach(cgrp, prog, replace_prog, link, type, flags);
6795 mutex_unlock(&cgroup_mutex);
6796 return ret;
6797 }
6798
cgroup_bpf_detach(struct cgroup * cgrp,struct bpf_prog * prog,enum bpf_attach_type type)6799 int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
6800 enum bpf_attach_type type)
6801 {
6802 int ret;
6803
6804 mutex_lock(&cgroup_mutex);
6805 ret = __cgroup_bpf_detach(cgrp, prog, NULL, type);
6806 mutex_unlock(&cgroup_mutex);
6807 return ret;
6808 }
6809
cgroup_bpf_query(struct cgroup * cgrp,const union bpf_attr * attr,union bpf_attr __user * uattr)6810 int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
6811 union bpf_attr __user *uattr)
6812 {
6813 int ret;
6814
6815 mutex_lock(&cgroup_mutex);
6816 ret = __cgroup_bpf_query(cgrp, attr, uattr);
6817 mutex_unlock(&cgroup_mutex);
6818 return ret;
6819 }
6820 #endif /* CONFIG_CGROUP_BPF */
6821
6822 #ifdef CONFIG_SYSFS
show_delegatable_files(struct cftype * files,char * buf,ssize_t size,const char * prefix)6823 static ssize_t show_delegatable_files(struct cftype *files, char *buf,
6824 ssize_t size, const char *prefix)
6825 {
6826 struct cftype *cft;
6827 ssize_t ret = 0;
6828
6829 for (cft = files; cft && cft->name[0] != '\0'; cft++) {
6830 if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
6831 continue;
6832
6833 if ((cft->flags & CFTYPE_PRESSURE) && !cgroup_psi_enabled())
6834 continue;
6835
6836 if (prefix)
6837 ret += snprintf(buf + ret, size - ret, "%s.", prefix);
6838
6839 ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
6840
6841 if (WARN_ON(ret >= size))
6842 break;
6843 }
6844
6845 return ret;
6846 }
6847
delegate_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)6848 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
6849 char *buf)
6850 {
6851 struct cgroup_subsys *ss;
6852 int ssid;
6853 ssize_t ret = 0;
6854
6855 ret = show_delegatable_files(cgroup_base_files, buf, PAGE_SIZE - ret,
6856 NULL);
6857
6858 for_each_subsys(ss, ssid)
6859 ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
6860 PAGE_SIZE - ret,
6861 cgroup_subsys_name[ssid]);
6862
6863 return ret;
6864 }
6865 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
6866
features_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)6867 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
6868 char *buf)
6869 {
6870 return snprintf(buf, PAGE_SIZE,
6871 "nsdelegate\n"
6872 "memory_localevents\n"
6873 "memory_recursiveprot\n");
6874 }
6875 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
6876
6877 static struct attribute *cgroup_sysfs_attrs[] = {
6878 &cgroup_delegate_attr.attr,
6879 &cgroup_features_attr.attr,
6880 NULL,
6881 };
6882
6883 static const struct attribute_group cgroup_sysfs_attr_group = {
6884 .attrs = cgroup_sysfs_attrs,
6885 .name = "cgroup",
6886 };
6887
cgroup_sysfs_init(void)6888 static int __init cgroup_sysfs_init(void)
6889 {
6890 return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
6891 }
6892 subsys_initcall(cgroup_sysfs_init);
6893
6894 #endif /* CONFIG_SYSFS */
6895