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