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