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