Version:  2.0.40 2.2.26 2.4.37 3.13 3.14 3.15 3.16 3.17 3.18 3.19 4.0 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10

Linux/kernel/cgroup.c

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

This page was automatically generated by LXR 0.3.1 (source).  •  Linux is a registered trademark of Linus Torvalds  •  Contact us