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