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