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