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