1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Generic process-grouping system. 4 * 5 * Based originally on the cpuset system, extracted by Paul Menage 6 * Copyright (C) 2006 Google, Inc 7 * 8 * Notifications support 9 * Copyright (C) 2009 Nokia Corporation 10 * Author: Kirill A. Shutemov 11 * 12 * Copyright notices from the original cpuset code: 13 * -------------------------------------------------- 14 * Copyright (C) 2003 BULL SA. 15 * Copyright (C) 2004-2006 Silicon Graphics, Inc. 16 * 17 * Portions derived from Patrick Mochel's sysfs code. 18 * sysfs is Copyright (c) 2001-3 Patrick Mochel 19 * 20 * 2003-10-10 Written by Simon Derr. 21 * 2003-10-22 Updates by Stephen Hemminger. 22 * 2004 May-July Rework by Paul Jackson. 23 * --------------------------------------------------- 24 */ 25 26 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 27 28 #include "cgroup-internal.h" 29 30 #include <linux/bpf-cgroup.h> 31 #include <linux/cred.h> 32 #include <linux/errno.h> 33 #include <linux/init_task.h> 34 #include <linux/kernel.h> 35 #include <linux/magic.h> 36 #include <linux/mutex.h> 37 #include <linux/mount.h> 38 #include <linux/pagemap.h> 39 #include <linux/proc_fs.h> 40 #include <linux/rcupdate.h> 41 #include <linux/sched.h> 42 #include <linux/sched/task.h> 43 #include <linux/slab.h> 44 #include <linux/spinlock.h> 45 #include <linux/percpu-rwsem.h> 46 #include <linux/string.h> 47 #include <linux/hashtable.h> 48 #include <linux/idr.h> 49 #include <linux/kthread.h> 50 #include <linux/atomic.h> 51 #include <linux/cpuset.h> 52 #include <linux/proc_ns.h> 53 #include <linux/nsproxy.h> 54 #include <linux/file.h> 55 #include <linux/fs_parser.h> 56 #include <linux/sched/cputime.h> 57 #include <linux/sched/deadline.h> 58 #include <linux/psi.h> 59 #include <linux/nstree.h> 60 #include <linux/irq_work.h> 61 #include <net/sock.h> 62 63 #define CREATE_TRACE_POINTS 64 #include <trace/events/cgroup.h> 65 66 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \ 67 MAX_CFTYPE_NAME + 2) 68 /* let's not notify more than 100 times per second */ 69 #define CGROUP_FILE_NOTIFY_MIN_INTV DIV_ROUND_UP(HZ, 100) 70 71 /* 72 * cgroup_mutex is the master lock. Any modification to cgroup or its 73 * hierarchy must be performed while holding it. 74 * 75 * css_set_lock protects task->cgroups pointer, the list of css_set 76 * objects, and the chain of tasks off each css_set. 77 * 78 * These locks are exported if CONFIG_PROVE_RCU so that accessors in 79 * cgroup.h can use them for lockdep annotations. 80 */ 81 DEFINE_MUTEX(cgroup_mutex); 82 DEFINE_SPINLOCK(css_set_lock); 83 84 #if (defined CONFIG_PROVE_RCU || defined CONFIG_LOCKDEP) 85 EXPORT_SYMBOL_GPL(cgroup_mutex); 86 EXPORT_SYMBOL_GPL(css_set_lock); 87 #endif 88 89 struct blocking_notifier_head cgroup_lifetime_notifier = 90 BLOCKING_NOTIFIER_INIT(cgroup_lifetime_notifier); 91 struct blocking_notifier_head cgroup_task_notifier = 92 BLOCKING_NOTIFIER_INIT(cgroup_task_notifier); 93 94 DEFINE_SPINLOCK(trace_cgroup_path_lock); 95 char trace_cgroup_path[TRACE_CGROUP_PATH_LEN]; 96 static bool cgroup_debug __read_mostly; 97 98 /* 99 * Protects cgroup_idr and css_idr so that IDs can be released without 100 * grabbing cgroup_mutex. 101 */ 102 static DEFINE_SPINLOCK(cgroup_idr_lock); 103 104 DEFINE_PERCPU_RWSEM(cgroup_threadgroup_rwsem); 105 106 #define cgroup_assert_mutex_or_rcu_locked() \ 107 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \ 108 !lockdep_is_held(&cgroup_mutex), \ 109 "cgroup_mutex or RCU read lock required") 110 111 /* 112 * cgroup destruction makes heavy use of work items and there can be a lot 113 * of concurrent destructions. Use a separate workqueue so that cgroup 114 * destruction work items don't end up filling up max_active of system_percpu_wq 115 * which may lead to deadlock. 116 * 117 * A cgroup destruction should enqueue work sequentially to: 118 * cgroup_offline_wq: use for css offline work 119 * cgroup_release_wq: use for css release work 120 * cgroup_free_wq: use for free work 121 * 122 * Rationale for using separate workqueues: 123 * The cgroup root free work may depend on completion of other css offline 124 * operations. If all tasks were enqueued to a single workqueue, this could 125 * create a deadlock scenario where: 126 * - Free work waits for other css offline work to complete. 127 * - But other css offline work is queued after free work in the same queue. 128 * 129 * Example deadlock scenario with single workqueue (cgroup_destroy_wq): 130 * 1. umount net_prio 131 * 2. net_prio root destruction enqueues work to cgroup_destroy_wq (CPUx) 132 * 3. perf_event CSS A offline enqueues work to same cgroup_destroy_wq (CPUx) 133 * 4. net_prio cgroup_destroy_root->cgroup_lock_and_drain_offline. 134 * 5. net_prio root destruction blocks waiting for perf_event CSS A offline, 135 * which can never complete as it's behind in the same queue and 136 * workqueue's max_active is 1. 137 */ 138 static struct workqueue_struct *cgroup_offline_wq; 139 static struct workqueue_struct *cgroup_release_wq; 140 static struct workqueue_struct *cgroup_free_wq; 141 142 /* generate an array of cgroup subsystem pointers */ 143 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys, 144 struct cgroup_subsys *cgroup_subsys[] = { 145 #include <linux/cgroup_subsys.h> 146 }; 147 #undef SUBSYS 148 149 /* array of cgroup subsystem names */ 150 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x, 151 static const char *cgroup_subsys_name[] = { 152 #include <linux/cgroup_subsys.h> 153 }; 154 #undef SUBSYS 155 156 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */ 157 #define SUBSYS(_x) \ 158 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \ 159 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \ 160 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \ 161 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key); 162 #include <linux/cgroup_subsys.h> 163 #undef SUBSYS 164 165 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key, 166 static struct static_key_true *cgroup_subsys_enabled_key[] = { 167 #include <linux/cgroup_subsys.h> 168 }; 169 #undef SUBSYS 170 171 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key, 172 static struct static_key_true *cgroup_subsys_on_dfl_key[] = { 173 #include <linux/cgroup_subsys.h> 174 }; 175 #undef SUBSYS 176 177 static DEFINE_PER_CPU(struct css_rstat_cpu, root_rstat_cpu); 178 static DEFINE_PER_CPU(struct cgroup_rstat_base_cpu, root_rstat_base_cpu); 179 180 /* the default hierarchy */ 181 struct cgroup_root cgrp_dfl_root = { 182 .cgrp.self.rstat_cpu = &root_rstat_cpu, 183 .cgrp.rstat_base_cpu = &root_rstat_base_cpu, 184 }; 185 EXPORT_SYMBOL_GPL(cgrp_dfl_root); 186 187 /* 188 * The default hierarchy always exists but is hidden until mounted for the 189 * first time. This is for backward compatibility. 190 */ 191 bool cgrp_dfl_visible; 192 193 /* some controllers are not supported in the default hierarchy */ 194 static u32 cgrp_dfl_inhibit_ss_mask; 195 196 /* some controllers are implicitly enabled on the default hierarchy */ 197 static u32 cgrp_dfl_implicit_ss_mask; 198 199 /* some controllers can be threaded on the default hierarchy */ 200 static u32 cgrp_dfl_threaded_ss_mask; 201 202 /* 203 * Set across rebind_subsystems() to the controllers leaving a hierarchy. 204 * Guarded by cgroup_mutex. Makes find_existing_css_set() resolve them to the 205 * root css so the affected tasks are migrated there before 206 * cgroup_apply_control_disable() kills the per-cgroup csses. 207 */ 208 static u32 cgroup_rebind_ss_mask; 209 210 /* The list of hierarchy roots */ 211 LIST_HEAD(cgroup_roots); 212 static int cgroup_root_count; 213 214 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */ 215 static DEFINE_IDR(cgroup_hierarchy_idr); 216 217 /* 218 * Assign a monotonically increasing serial number to csses. It guarantees 219 * cgroups with bigger numbers are newer than those with smaller numbers. 220 * Also, as csses are always appended to the parent's ->children list, it 221 * guarantees that sibling csses are always sorted in the ascending serial 222 * number order on the list. Protected by cgroup_mutex. 223 */ 224 static u64 css_serial_nr_next = 1; 225 226 /* 227 * These bitmasks identify subsystems with specific features to avoid 228 * having to do iterative checks repeatedly. 229 */ 230 static u32 have_fork_callback __read_mostly; 231 static u32 have_exit_callback __read_mostly; 232 static u32 have_release_callback __read_mostly; 233 static u32 have_canfork_callback __read_mostly; 234 235 static bool have_favordynmods __ro_after_init = IS_ENABLED(CONFIG_CGROUP_FAVOR_DYNMODS); 236 237 /* 238 * Write protected by cgroup_mutex and write-lock of cgroup_threadgroup_rwsem, 239 * read protected by either. 240 * 241 * Can only be turned on, but not turned off. 242 */ 243 bool cgroup_enable_per_threadgroup_rwsem __read_mostly; 244 245 /* cgroup namespace for init task */ 246 struct cgroup_namespace init_cgroup_ns = { 247 .ns = NS_COMMON_INIT(init_cgroup_ns), 248 .user_ns = &init_user_ns, 249 .root_cset = &init_css_set, 250 }; 251 252 static struct file_system_type cgroup2_fs_type; 253 static struct cftype cgroup_base_files[]; 254 static struct cftype cgroup_psi_files[]; 255 256 /* cgroup optional features */ 257 enum cgroup_opt_features { 258 #ifdef CONFIG_PSI 259 OPT_FEATURE_PRESSURE, 260 #endif 261 OPT_FEATURE_COUNT 262 }; 263 264 static const char *cgroup_opt_feature_names[OPT_FEATURE_COUNT] = { 265 #ifdef CONFIG_PSI 266 "pressure", 267 #endif 268 }; 269 270 static u16 cgroup_feature_disable_mask __read_mostly; 271 272 static int cgroup_apply_control(struct cgroup *cgrp); 273 static void cgroup_finalize_control(struct cgroup *cgrp, int ret); 274 static void css_task_iter_skip(struct css_task_iter *it, 275 struct task_struct *task); 276 static int cgroup_destroy_locked(struct cgroup *cgrp); 277 static void kill_css_sync(struct cgroup_subsys_state *css); 278 static void kill_css_finish(struct cgroup_subsys_state *css); 279 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp, 280 struct cgroup_subsys *ss); 281 static void css_release(struct percpu_ref *ref); 282 static int cgroup_addrm_files(struct cgroup_subsys_state *css, 283 struct cgroup *cgrp, struct cftype cfts[], 284 bool is_add); 285 static void cgroup_rt_init(void); 286 287 #ifdef CONFIG_DEBUG_CGROUP_REF 288 #define CGROUP_REF_FN_ATTRS noinline 289 #define CGROUP_REF_EXPORT(fn) EXPORT_SYMBOL_GPL(fn); 290 #include <linux/cgroup_refcnt.h> 291 #endif 292 293 /** 294 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID 295 * @ssid: subsys ID of interest 296 * 297 * cgroup_subsys_enabled() can only be used with literal subsys names which 298 * is fine for individual subsystems but unsuitable for cgroup core. This 299 * is slower static_key_enabled() based test indexed by @ssid. 300 */ 301 bool cgroup_ssid_enabled(int ssid) 302 { 303 if (!CGROUP_HAS_SUBSYS_CONFIG) 304 return false; 305 306 return static_key_enabled(cgroup_subsys_enabled_key[ssid]); 307 } 308 309 /** 310 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy 311 * @cgrp: the cgroup of interest 312 * 313 * The default hierarchy is the v2 interface of cgroup and this function 314 * can be used to test whether a cgroup is on the default hierarchy for 315 * cases where a subsystem should behave differently depending on the 316 * interface version. 317 * 318 * List of changed behaviors: 319 * 320 * - Mount options "noprefix", "xattr", "clone_children", "release_agent" 321 * and "name" are disallowed. 322 * 323 * - When mounting an existing superblock, mount options should match. 324 * 325 * - rename(2) is disallowed. 326 * 327 * - "tasks" is removed. Everything should be at process granularity. Use 328 * "cgroup.procs" instead. 329 * 330 * - "cgroup.procs" is not sorted. pids will be unique unless they got 331 * recycled in-between reads. 332 * 333 * - "release_agent" and "notify_on_release" are removed. Replacement 334 * notification mechanism will be implemented. 335 * 336 * - "cgroup.clone_children" is removed. 337 * 338 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup 339 * and its descendants contain no task; otherwise, 1. The file also 340 * generates kernfs notification which can be monitored through poll and 341 * [di]notify when the value of the file changes. 342 * 343 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and 344 * take masks of ancestors with non-empty cpus/mems, instead of being 345 * moved to an ancestor. 346 * 347 * - cpuset: a task can be moved into an empty cpuset, and again it takes 348 * masks of ancestors. 349 * 350 * - blkcg: blk-throttle becomes properly hierarchical. 351 */ 352 bool cgroup_on_dfl(const struct cgroup *cgrp) 353 { 354 return cgrp->root == &cgrp_dfl_root; 355 } 356 357 /* IDR wrappers which synchronize using cgroup_idr_lock */ 358 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end, 359 gfp_t gfp_mask) 360 { 361 int ret; 362 363 idr_preload(gfp_mask); 364 spin_lock_bh(&cgroup_idr_lock); 365 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM); 366 spin_unlock_bh(&cgroup_idr_lock); 367 idr_preload_end(); 368 return ret; 369 } 370 371 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id) 372 { 373 void *ret; 374 375 spin_lock_bh(&cgroup_idr_lock); 376 ret = idr_replace(idr, ptr, id); 377 spin_unlock_bh(&cgroup_idr_lock); 378 return ret; 379 } 380 381 static void cgroup_idr_remove(struct idr *idr, int id) 382 { 383 spin_lock_bh(&cgroup_idr_lock); 384 idr_remove(idr, id); 385 spin_unlock_bh(&cgroup_idr_lock); 386 } 387 388 static bool cgroup_is_threaded(struct cgroup *cgrp) 389 { 390 return cgrp->dom_cgrp != cgrp; 391 } 392 393 /* can @cgrp host both domain and threaded children? */ 394 static bool cgroup_is_mixable(struct cgroup *cgrp) 395 { 396 /* 397 * Root isn't under domain level resource control exempting it from 398 * the no-internal-process constraint, so it can serve as a thread 399 * root and a parent of resource domains at the same time. 400 */ 401 return !cgroup_parent(cgrp); 402 } 403 404 /* can @cgrp become a thread root? Should always be true for a thread root */ 405 static bool cgroup_can_be_thread_root(struct cgroup *cgrp) 406 { 407 /* mixables don't care */ 408 if (cgroup_is_mixable(cgrp)) 409 return true; 410 411 /* domain roots can't be nested under threaded */ 412 if (cgroup_is_threaded(cgrp)) 413 return false; 414 415 /* can only have either domain or threaded children */ 416 if (READ_ONCE(cgrp->nr_populated_domain_children)) 417 return false; 418 419 /* and no domain controllers can be enabled */ 420 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask) 421 return false; 422 423 return true; 424 } 425 426 /* is @cgrp root of a threaded subtree? */ 427 static bool cgroup_is_thread_root(struct cgroup *cgrp) 428 { 429 /* thread root should be a domain */ 430 if (cgroup_is_threaded(cgrp)) 431 return false; 432 433 /* a domain w/ threaded children is a thread root */ 434 if (cgrp->nr_threaded_children) 435 return true; 436 437 /* 438 * A domain which has tasks and explicit threaded controllers 439 * enabled is a thread root. 440 */ 441 if (cgroup_has_tasks(cgrp) && 442 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask)) 443 return true; 444 445 return false; 446 } 447 448 /* a domain which isn't connected to the root w/o brekage can't be used */ 449 static bool cgroup_is_valid_domain(struct cgroup *cgrp) 450 { 451 /* the cgroup itself can be a thread root */ 452 if (cgroup_is_threaded(cgrp)) 453 return false; 454 455 /* but the ancestors can't be unless mixable */ 456 while ((cgrp = cgroup_parent(cgrp))) { 457 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp)) 458 return false; 459 if (cgroup_is_threaded(cgrp)) 460 return false; 461 } 462 463 return true; 464 } 465 466 /* subsystems visibly enabled on a cgroup */ 467 static u32 cgroup_control(struct cgroup *cgrp) 468 { 469 struct cgroup *parent = cgroup_parent(cgrp); 470 u32 root_ss_mask = cgrp->root->subsys_mask; 471 472 if (parent) { 473 u32 ss_mask = parent->subtree_control; 474 475 /* threaded cgroups can only have threaded controllers */ 476 if (cgroup_is_threaded(cgrp)) 477 ss_mask &= cgrp_dfl_threaded_ss_mask; 478 return ss_mask; 479 } 480 481 if (cgroup_on_dfl(cgrp)) 482 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask | 483 cgrp_dfl_implicit_ss_mask); 484 return root_ss_mask; 485 } 486 487 /* subsystems enabled on a cgroup */ 488 static u32 cgroup_ss_mask(struct cgroup *cgrp) 489 { 490 struct cgroup *parent = cgroup_parent(cgrp); 491 492 if (parent) { 493 u32 ss_mask = parent->subtree_ss_mask; 494 495 /* threaded cgroups can only have threaded controllers */ 496 if (cgroup_is_threaded(cgrp)) 497 ss_mask &= cgrp_dfl_threaded_ss_mask; 498 return ss_mask; 499 } 500 501 return cgrp->root->subsys_mask; 502 } 503 504 /** 505 * cgroup_e_css_by_mask - obtain a cgroup's effective css for the specified ss 506 * @cgrp: the cgroup of interest 507 * @ss: the subsystem of interest (%NULL returns @cgrp->self) 508 * 509 * Similar to cgroup_css() but returns the effective css, which is defined 510 * as the matching css of the nearest ancestor including self which has @ss 511 * enabled. If @ss is associated with the hierarchy @cgrp is on, this 512 * function is guaranteed to return non-NULL css. 513 */ 514 static struct cgroup_subsys_state *cgroup_e_css_by_mask(struct cgroup *cgrp, 515 struct cgroup_subsys *ss) 516 { 517 lockdep_assert_held(&cgroup_mutex); 518 519 if (!ss) 520 return &cgrp->self; 521 522 /* 523 * This function is used while updating css associations and thus 524 * can't test the csses directly. Test ss_mask. 525 */ 526 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) { 527 cgrp = cgroup_parent(cgrp); 528 if (!cgrp) 529 return NULL; 530 } 531 532 return cgroup_css(cgrp, ss); 533 } 534 535 /** 536 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem 537 * @cgrp: the cgroup of interest 538 * @ss: the subsystem of interest 539 * 540 * Find and get the effective css of @cgrp for @ss. The effective css is 541 * defined as the matching css of the nearest ancestor including self which 542 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on, 543 * the root css is returned, so this function always returns a valid css. 544 * 545 * The returned css is not guaranteed to be online, and therefore it is the 546 * callers responsibility to try get a reference for it. 547 */ 548 struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp, 549 struct cgroup_subsys *ss) 550 { 551 if (!CGROUP_HAS_SUBSYS_CONFIG) 552 return NULL; 553 554 return rcu_dereference_check(cgrp->e_css[ss->id], 555 lockdep_is_held(&cgroup_mutex)); 556 } 557 558 /** 559 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem 560 * @cgrp: the cgroup of interest 561 * @ss: the subsystem of interest 562 * 563 * Find and get the effective css of @cgrp for @ss. The effective css is 564 * defined as the matching css of the nearest ancestor including self which 565 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on, 566 * the root css is returned, so this function always returns a valid css. 567 * The returned css must be put using css_put(). 568 */ 569 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp, 570 struct cgroup_subsys *ss) 571 { 572 struct cgroup_subsys_state *css; 573 574 if (!CGROUP_HAS_SUBSYS_CONFIG) 575 return NULL; 576 577 rcu_read_lock(); 578 579 css = cgroup_e_css(cgrp, ss); 580 while (!css_tryget_online(css)) 581 css = cgroup_e_css(cgroup_parent(css->cgroup), ss); 582 583 rcu_read_unlock(); 584 return css; 585 } 586 EXPORT_SYMBOL_GPL(cgroup_get_e_css); 587 588 static void cgroup_get_live(struct cgroup *cgrp) 589 { 590 WARN_ON_ONCE(cgroup_is_dead(cgrp)); 591 cgroup_get(cgrp); 592 } 593 594 /** 595 * __cgroup_task_count - count the number of tasks in a cgroup. The caller 596 * is responsible for taking the css_set_lock. 597 * @cgrp: the cgroup in question 598 */ 599 int __cgroup_task_count(const struct cgroup *cgrp) 600 { 601 int count = 0; 602 struct cgrp_cset_link *link; 603 604 lockdep_assert_held(&css_set_lock); 605 606 list_for_each_entry(link, &cgrp->cset_links, cset_link) 607 count += link->cset->nr_tasks; 608 609 return count; 610 } 611 612 /** 613 * cgroup_task_count - count the number of tasks in a cgroup. 614 * @cgrp: the cgroup in question 615 */ 616 int cgroup_task_count(const struct cgroup *cgrp) 617 { 618 int count; 619 620 spin_lock_irq(&css_set_lock); 621 count = __cgroup_task_count(cgrp); 622 spin_unlock_irq(&css_set_lock); 623 624 return count; 625 } 626 627 static struct cgroup *kn_priv(struct kernfs_node *kn) 628 { 629 struct kernfs_node *parent; 630 /* 631 * The parent can not be replaced due to KERNFS_ROOT_INVARIANT_PARENT. 632 * Therefore it is always safe to dereference this pointer outside of a 633 * RCU section. 634 */ 635 parent = rcu_dereference_check(kn->__parent, 636 kernfs_root_flags(kn) & KERNFS_ROOT_INVARIANT_PARENT); 637 return parent->priv; 638 } 639 640 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of) 641 { 642 struct cgroup *cgrp = kn_priv(of->kn); 643 struct cftype *cft = of_cft(of); 644 645 /* 646 * This is open and unprotected implementation of cgroup_css(). 647 * seq_css() is only called from a kernfs file operation which has 648 * an active reference on the file. Because all the subsystem 649 * files are drained before a css is disassociated with a cgroup, 650 * the matching css from the cgroup's subsys table is guaranteed to 651 * be and stay valid until the enclosing operation is complete. 652 */ 653 if (CGROUP_HAS_SUBSYS_CONFIG && cft->ss) 654 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]); 655 else 656 return &cgrp->self; 657 } 658 EXPORT_SYMBOL_GPL(of_css); 659 660 /** 661 * for_each_css - iterate all css's of a cgroup 662 * @css: the iteration cursor 663 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end 664 * @cgrp: the target cgroup to iterate css's of 665 * 666 * Should be called under cgroup_mutex. 667 */ 668 #define for_each_css(css, ssid, cgrp) \ 669 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \ 670 if (!((css) = rcu_dereference_check( \ 671 (cgrp)->subsys[(ssid)], \ 672 lockdep_is_held(&cgroup_mutex)))) { } \ 673 else 674 675 /** 676 * do_each_subsys_mask - filter for_each_subsys with a bitmask 677 * @ss: the iteration cursor 678 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end 679 * @ss_mask: the bitmask 680 * 681 * The block will only run for cases where the ssid-th bit (1 << ssid) of 682 * @ss_mask is set. 683 */ 684 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \ 685 unsigned long __ss_mask = (ss_mask); \ 686 if (!CGROUP_HAS_SUBSYS_CONFIG) { \ 687 (ssid) = 0; \ 688 break; \ 689 } \ 690 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \ 691 (ss) = cgroup_subsys[ssid]; \ 692 { 693 694 #define while_each_subsys_mask() \ 695 } \ 696 } \ 697 } while (false) 698 699 /* 700 * The default css_set - used by init and its children prior to any 701 * hierarchies being mounted. It contains a pointer to the root state 702 * for each subsystem. Also used to anchor the list of css_sets. Not 703 * reference-counted, to improve performance when child cgroups 704 * haven't been created. 705 */ 706 struct css_set init_css_set = { 707 .refcount = REFCOUNT_INIT(1), 708 .dom_cset = &init_css_set, 709 .tasks = LIST_HEAD_INIT(init_css_set.tasks), 710 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks), 711 .dying_tasks = LIST_HEAD_INIT(init_css_set.dying_tasks), 712 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters), 713 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets), 714 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links), 715 .mg_src_preload_node = LIST_HEAD_INIT(init_css_set.mg_src_preload_node), 716 .mg_dst_preload_node = LIST_HEAD_INIT(init_css_set.mg_dst_preload_node), 717 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node), 718 719 /* 720 * The following field is re-initialized when this cset gets linked 721 * in cgroup_init(). However, let's initialize the field 722 * statically too so that the default cgroup can be accessed safely 723 * early during boot. 724 */ 725 .dfl_cgrp = &cgrp_dfl_root.cgrp, 726 }; 727 728 static int css_set_count = 1; /* 1 for init_css_set */ 729 730 static bool css_set_threaded(struct css_set *cset) 731 { 732 return cset->dom_cset != cset; 733 } 734 735 /** 736 * css_set_populated - does a css_set contain any tasks? 737 * @cset: target css_set 738 * 739 * css_set_populated() should be the same as !!cset->nr_tasks at steady 740 * state. However, css_set_populated() can be called while a task is being 741 * added to or removed from the linked list before the nr_tasks is 742 * properly updated. Hence, we can't just look at ->nr_tasks here. 743 */ 744 static bool css_set_populated(struct css_set *cset) 745 { 746 lockdep_assert_held(&css_set_lock); 747 748 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks); 749 } 750 751 /** 752 * css_update_populated - update the populated state of a css and ancestors 753 * @css: leaf css whose own populated count is changing 754 * @populated: inc or dec 755 * 756 * One of the css_sets pinned by @css is getting its first task or losing the 757 * last. Propagate the transition up the parent chain so that a css's 758 * nr_populated_children is zero iff none of its descendants contain any tasks. 759 * 760 * For a cgroup->self walk, also runs cgroup-side bookkeeping at each level: 761 * domain/threaded child split, deferred-destroy trigger, and notification via 762 * "cgroup.populated" (zero iff cgrp->self has neither populated csets nor 763 * populated children; userland is notified on transitions). 764 */ 765 static void css_update_populated(struct cgroup_subsys_state *css, bool populated) 766 { 767 struct cgroup_subsys_state *child = NULL; 768 int adj = populated ? 1 : -1; 769 770 lockdep_assert_held(&css_set_lock); 771 772 do { 773 /* non-NULL only on the cgroup->self walk */ 774 struct cgroup *cgrp = css_is_self(css) ? css->cgroup : NULL; 775 bool was_populated = css_is_populated(css); 776 777 if (!child) { 778 WRITE_ONCE(css->nr_populated_csets, 779 css->nr_populated_csets + adj); 780 } else { 781 WRITE_ONCE(css->nr_populated_children, 782 css->nr_populated_children + adj); 783 if (cgrp) { 784 if (cgroup_is_threaded(child->cgroup)) 785 WRITE_ONCE(cgrp->nr_populated_threaded_children, 786 cgrp->nr_populated_threaded_children + adj); 787 else 788 WRITE_ONCE(cgrp->nr_populated_domain_children, 789 cgrp->nr_populated_domain_children + adj); 790 } 791 } 792 793 if (was_populated == css_is_populated(css)) 794 break; 795 796 /* 797 * Pair with smp_mb() in kill_css_sync(). Either we observe 798 * CSS_DYING and queue, or the caller observes our decrement 799 * and fires synchronously. 800 */ 801 smp_mb(); 802 803 /* 804 * Subtree just emptied below a dying css. Fire deferred kill. 805 * The transition is one-shot for a dying css. 806 */ 807 if (was_populated && css_is_dying(css)) { 808 css_get(css); 809 WARN_ON_ONCE(!queue_work(cgroup_offline_wq, &css->kill_finish_work)); 810 } 811 812 if (cgrp) { 813 cgroup1_check_for_release(cgrp); 814 TRACE_CGROUP_PATH(notify_populated, cgrp, 815 cgroup_is_populated(cgrp)); 816 cgroup_file_notify(&cgrp->events_file); 817 } 818 819 child = css; 820 css = css->parent; 821 } while (css); 822 } 823 824 /** 825 * css_set_update_populated - update populated state of a css_set 826 * @cset: target css_set 827 * @populated: whether @cset is populated or depopulated 828 * 829 * @cset is either getting the first task or losing the last. Update the 830 * populated counters along each linked cgroup's self chain and each 831 * subsystem css that @cset pins. 832 */ 833 static void css_set_update_populated(struct css_set *cset, bool populated) 834 { 835 struct cgrp_cset_link *link; 836 struct cgroup_subsys *ss; 837 int ssid; 838 839 lockdep_assert_held(&css_set_lock); 840 841 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) 842 css_update_populated(&link->cgrp->self, populated); 843 844 for_each_subsys(ss, ssid) { 845 struct cgroup_subsys_state *css = cset->subsys[ssid]; 846 847 if (css) 848 css_update_populated(css, populated); 849 } 850 } 851 852 /* 853 * @task is leaving, advance task iterators which are pointing to it so 854 * that they can resume at the next position. Advancing an iterator might 855 * remove it from the list, use safe walk. See css_task_iter_skip() for 856 * details. 857 */ 858 static void css_set_skip_task_iters(struct css_set *cset, 859 struct task_struct *task) 860 { 861 struct css_task_iter *it, *pos; 862 863 list_for_each_entry_safe(it, pos, &cset->task_iters, iters_node) 864 css_task_iter_skip(it, task); 865 } 866 867 /** 868 * css_set_move_task - move a task from one css_set to another 869 * @task: task being moved 870 * @from_cset: css_set @task currently belongs to (may be NULL) 871 * @to_cset: new css_set @task is being moved to (may be NULL) 872 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks 873 * 874 * Move @task from @from_cset to @to_cset. If @task didn't belong to any 875 * css_set, @from_cset can be NULL. If @task is being disassociated 876 * instead of moved, @to_cset can be NULL. 877 * 878 * This function automatically handles populated counter updates and 879 * css_task_iter adjustments but the caller is responsible for managing 880 * @from_cset and @to_cset's reference counts. 881 */ 882 static void css_set_move_task(struct task_struct *task, 883 struct css_set *from_cset, struct css_set *to_cset, 884 bool use_mg_tasks) 885 { 886 lockdep_assert_held(&css_set_lock); 887 888 if (to_cset && !css_set_populated(to_cset)) 889 css_set_update_populated(to_cset, true); 890 891 if (from_cset) { 892 WARN_ON_ONCE(list_empty(&task->cg_list)); 893 894 css_set_skip_task_iters(from_cset, task); 895 list_del_init(&task->cg_list); 896 if (!css_set_populated(from_cset)) 897 css_set_update_populated(from_cset, false); 898 } else { 899 WARN_ON_ONCE(!list_empty(&task->cg_list)); 900 } 901 902 if (to_cset) { 903 /* 904 * We are synchronized through cgroup_threadgroup_rwsem 905 * against PF_EXITING setting such that we can't race 906 * against cgroup_task_dead()/cgroup_task_free() dropping 907 * the css_set. 908 */ 909 WARN_ON_ONCE(task->flags & PF_EXITING); 910 911 cgroup_move_task(task, to_cset); 912 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks : 913 &to_cset->tasks); 914 } 915 } 916 917 /* 918 * hash table for cgroup groups. This improves the performance to find 919 * an existing css_set. This hash doesn't (currently) take into 920 * account cgroups in empty hierarchies. 921 */ 922 #define CSS_SET_HASH_BITS 7 923 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS); 924 925 static unsigned long css_set_hash(struct cgroup_subsys_state **css) 926 { 927 unsigned long key = 0UL; 928 struct cgroup_subsys *ss; 929 int i; 930 931 for_each_subsys(ss, i) 932 key += (unsigned long)css[i]; 933 key = (key >> 16) ^ key; 934 935 return key; 936 } 937 938 void put_css_set_locked(struct css_set *cset) 939 { 940 struct cgrp_cset_link *link, *tmp_link; 941 struct cgroup_subsys *ss; 942 int ssid; 943 944 lockdep_assert_held(&css_set_lock); 945 946 if (!refcount_dec_and_test(&cset->refcount)) 947 return; 948 949 WARN_ON_ONCE(!list_empty(&cset->threaded_csets)); 950 951 /* This css_set is dead. Unlink it and release cgroup and css refs */ 952 for_each_subsys(ss, ssid) { 953 list_del(&cset->e_cset_node[ssid]); 954 css_put(cset->subsys[ssid]); 955 } 956 hash_del(&cset->hlist); 957 css_set_count--; 958 959 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) { 960 list_del(&link->cset_link); 961 list_del(&link->cgrp_link); 962 if (cgroup_parent(link->cgrp)) 963 cgroup_put(link->cgrp); 964 kfree(link); 965 } 966 967 if (css_set_threaded(cset)) { 968 list_del(&cset->threaded_csets_node); 969 put_css_set_locked(cset->dom_cset); 970 } 971 972 kfree_rcu(cset, rcu_head); 973 } 974 975 /** 976 * compare_css_sets - helper function for find_existing_css_set(). 977 * @cset: candidate css_set being tested 978 * @old_cset: existing css_set for a task 979 * @new_cgrp: cgroup that's being entered by the task 980 * @template: desired set of css pointers in css_set (pre-calculated) 981 * 982 * Returns true if "cset" matches "old_cset" except for the hierarchy 983 * which "new_cgrp" belongs to, for which it should match "new_cgrp". 984 */ 985 static bool compare_css_sets(struct css_set *cset, 986 struct css_set *old_cset, 987 struct cgroup *new_cgrp, 988 struct cgroup_subsys_state *template[]) 989 { 990 struct cgroup *new_dfl_cgrp; 991 struct list_head *l1, *l2; 992 993 /* 994 * On the default hierarchy, there can be csets which are 995 * associated with the same set of cgroups but different csses. 996 * Let's first ensure that csses match. 997 */ 998 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) 999 return false; 1000 1001 1002 /* @cset's domain should match the default cgroup's */ 1003 if (cgroup_on_dfl(new_cgrp)) 1004 new_dfl_cgrp = new_cgrp; 1005 else 1006 new_dfl_cgrp = old_cset->dfl_cgrp; 1007 1008 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp) 1009 return false; 1010 1011 /* 1012 * Compare cgroup pointers in order to distinguish between 1013 * different cgroups in hierarchies. As different cgroups may 1014 * share the same effective css, this comparison is always 1015 * necessary. 1016 */ 1017 l1 = &cset->cgrp_links; 1018 l2 = &old_cset->cgrp_links; 1019 while (1) { 1020 struct cgrp_cset_link *link1, *link2; 1021 struct cgroup *cgrp1, *cgrp2; 1022 1023 l1 = l1->next; 1024 l2 = l2->next; 1025 /* See if we reached the end - both lists are equal length. */ 1026 if (l1 == &cset->cgrp_links) { 1027 BUG_ON(l2 != &old_cset->cgrp_links); 1028 break; 1029 } else { 1030 BUG_ON(l2 == &old_cset->cgrp_links); 1031 } 1032 /* Locate the cgroups associated with these links. */ 1033 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link); 1034 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link); 1035 cgrp1 = link1->cgrp; 1036 cgrp2 = link2->cgrp; 1037 /* Hierarchies should be linked in the same order. */ 1038 BUG_ON(cgrp1->root != cgrp2->root); 1039 1040 /* 1041 * If this hierarchy is the hierarchy of the cgroup 1042 * that's changing, then we need to check that this 1043 * css_set points to the new cgroup; if it's any other 1044 * hierarchy, then this css_set should point to the 1045 * same cgroup as the old css_set. 1046 */ 1047 if (cgrp1->root == new_cgrp->root) { 1048 if (cgrp1 != new_cgrp) 1049 return false; 1050 } else { 1051 if (cgrp1 != cgrp2) 1052 return false; 1053 } 1054 } 1055 return true; 1056 } 1057 1058 /** 1059 * find_existing_css_set - init css array and find the matching css_set 1060 * @old_cset: the css_set that we're using before the cgroup transition 1061 * @cgrp: the cgroup that we're moving into 1062 * @template: out param for the new set of csses, should be clear on entry 1063 */ 1064 static struct css_set *find_existing_css_set(struct css_set *old_cset, 1065 struct cgroup *cgrp, 1066 struct cgroup_subsys_state **template) 1067 { 1068 struct cgroup_root *root = cgrp->root; 1069 struct cgroup_subsys *ss; 1070 struct css_set *cset; 1071 unsigned long key; 1072 int i; 1073 1074 /* 1075 * Build the set of subsystem state objects that we want to see in the 1076 * new css_set. While subsystems can change globally, the entries here 1077 * won't change, so no need for locking. 1078 */ 1079 for_each_subsys(ss, i) { 1080 if (unlikely(cgroup_rebind_ss_mask & (1UL << i))) { 1081 /* 1082 * @ss is leaving this hierarchy and its per-cgroup 1083 * csses are about to be killed. Resolve to the 1084 * surviving root css so the tasks are migrated there. 1085 */ 1086 template[i] = cgroup_css(&root->cgrp, ss); 1087 WARN_ON_ONCE(!template[i]); 1088 } else if (root->subsys_mask & (1UL << i)) { 1089 /* 1090 * @ss is in this hierarchy, so we want the 1091 * effective css from @cgrp. 1092 */ 1093 template[i] = cgroup_e_css_by_mask(cgrp, ss); 1094 } else { 1095 /* 1096 * @ss is not in this hierarchy, so we don't want 1097 * to change the css. 1098 */ 1099 template[i] = old_cset->subsys[i]; 1100 } 1101 } 1102 1103 key = css_set_hash(template); 1104 hash_for_each_possible(css_set_table, cset, hlist, key) { 1105 if (!compare_css_sets(cset, old_cset, cgrp, template)) 1106 continue; 1107 1108 /* This css_set matches what we need */ 1109 return cset; 1110 } 1111 1112 /* No existing cgroup group matched */ 1113 return NULL; 1114 } 1115 1116 static void free_cgrp_cset_links(struct list_head *links_to_free) 1117 { 1118 struct cgrp_cset_link *link, *tmp_link; 1119 1120 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) { 1121 list_del(&link->cset_link); 1122 kfree(link); 1123 } 1124 } 1125 1126 /** 1127 * allocate_cgrp_cset_links - allocate cgrp_cset_links 1128 * @count: the number of links to allocate 1129 * @tmp_links: list_head the allocated links are put on 1130 * 1131 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links 1132 * through ->cset_link. Returns 0 on success or -errno. 1133 */ 1134 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links) 1135 { 1136 struct cgrp_cset_link *link; 1137 int i; 1138 1139 INIT_LIST_HEAD(tmp_links); 1140 1141 for (i = 0; i < count; i++) { 1142 link = kzalloc_obj(*link); 1143 if (!link) { 1144 free_cgrp_cset_links(tmp_links); 1145 return -ENOMEM; 1146 } 1147 list_add(&link->cset_link, tmp_links); 1148 } 1149 return 0; 1150 } 1151 1152 /** 1153 * link_css_set - a helper function to link a css_set to a cgroup 1154 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links() 1155 * @cset: the css_set to be linked 1156 * @cgrp: the destination cgroup 1157 */ 1158 static void link_css_set(struct list_head *tmp_links, struct css_set *cset, 1159 struct cgroup *cgrp) 1160 { 1161 struct cgrp_cset_link *link; 1162 1163 BUG_ON(list_empty(tmp_links)); 1164 1165 if (cgroup_on_dfl(cgrp)) 1166 cset->dfl_cgrp = cgrp; 1167 1168 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link); 1169 link->cset = cset; 1170 link->cgrp = cgrp; 1171 1172 /* 1173 * Always add links to the tail of the lists so that the lists are 1174 * in chronological order. 1175 */ 1176 list_move_tail(&link->cset_link, &cgrp->cset_links); 1177 list_add_tail(&link->cgrp_link, &cset->cgrp_links); 1178 1179 if (cgroup_parent(cgrp)) 1180 cgroup_get_live(cgrp); 1181 } 1182 1183 /** 1184 * find_css_set - return a new css_set with one cgroup updated 1185 * @old_cset: the baseline css_set 1186 * @cgrp: the cgroup to be updated 1187 * 1188 * Return a new css_set that's equivalent to @old_cset, but with @cgrp 1189 * substituted into the appropriate hierarchy. 1190 */ 1191 static struct css_set *find_css_set(struct css_set *old_cset, 1192 struct cgroup *cgrp) 1193 { 1194 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { }; 1195 struct css_set *cset; 1196 struct list_head tmp_links; 1197 struct cgrp_cset_link *link; 1198 struct cgroup_subsys *ss; 1199 unsigned long key; 1200 int ssid; 1201 1202 lockdep_assert_held(&cgroup_mutex); 1203 1204 /* First see if we already have a cgroup group that matches 1205 * the desired set */ 1206 spin_lock_irq(&css_set_lock); 1207 cset = find_existing_css_set(old_cset, cgrp, template); 1208 if (cset) 1209 get_css_set(cset); 1210 spin_unlock_irq(&css_set_lock); 1211 1212 if (cset) 1213 return cset; 1214 1215 cset = kzalloc_obj(*cset); 1216 if (!cset) 1217 return NULL; 1218 1219 /* Allocate all the cgrp_cset_link objects that we'll need */ 1220 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) { 1221 kfree(cset); 1222 return NULL; 1223 } 1224 1225 refcount_set(&cset->refcount, 1); 1226 cset->dom_cset = cset; 1227 INIT_LIST_HEAD(&cset->tasks); 1228 INIT_LIST_HEAD(&cset->mg_tasks); 1229 INIT_LIST_HEAD(&cset->dying_tasks); 1230 INIT_LIST_HEAD(&cset->task_iters); 1231 INIT_LIST_HEAD(&cset->threaded_csets); 1232 INIT_HLIST_NODE(&cset->hlist); 1233 INIT_LIST_HEAD(&cset->cgrp_links); 1234 INIT_LIST_HEAD(&cset->mg_src_preload_node); 1235 INIT_LIST_HEAD(&cset->mg_dst_preload_node); 1236 INIT_LIST_HEAD(&cset->mg_node); 1237 1238 /* Copy the set of subsystem state objects generated in 1239 * find_existing_css_set() */ 1240 memcpy(cset->subsys, template, sizeof(cset->subsys)); 1241 1242 spin_lock_irq(&css_set_lock); 1243 /* Add reference counts and links from the new css_set. */ 1244 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) { 1245 struct cgroup *c = link->cgrp; 1246 1247 if (c->root == cgrp->root) 1248 c = cgrp; 1249 link_css_set(&tmp_links, cset, c); 1250 } 1251 1252 BUG_ON(!list_empty(&tmp_links)); 1253 1254 css_set_count++; 1255 1256 /* Add @cset to the hash table */ 1257 key = css_set_hash(cset->subsys); 1258 hash_add(css_set_table, &cset->hlist, key); 1259 1260 for_each_subsys(ss, ssid) { 1261 struct cgroup_subsys_state *css = cset->subsys[ssid]; 1262 1263 list_add_tail(&cset->e_cset_node[ssid], 1264 &css->cgroup->e_csets[ssid]); 1265 css_get(css); 1266 } 1267 1268 spin_unlock_irq(&css_set_lock); 1269 1270 /* 1271 * If @cset should be threaded, look up the matching dom_cset and 1272 * link them up. We first fully initialize @cset then look for the 1273 * dom_cset. It's simpler this way and safe as @cset is guaranteed 1274 * to stay empty until we return. 1275 */ 1276 if (cgroup_is_threaded(cset->dfl_cgrp)) { 1277 struct css_set *dcset; 1278 1279 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp); 1280 if (!dcset) { 1281 put_css_set(cset); 1282 return NULL; 1283 } 1284 1285 spin_lock_irq(&css_set_lock); 1286 cset->dom_cset = dcset; 1287 list_add_tail(&cset->threaded_csets_node, 1288 &dcset->threaded_csets); 1289 spin_unlock_irq(&css_set_lock); 1290 } 1291 1292 return cset; 1293 } 1294 1295 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root) 1296 { 1297 struct cgroup *root_cgrp = kernfs_root_to_node(kf_root)->priv; 1298 1299 return root_cgrp->root; 1300 } 1301 1302 void cgroup_favor_dynmods(struct cgroup_root *root, bool favor) 1303 { 1304 bool favoring = root->flags & CGRP_ROOT_FAVOR_DYNMODS; 1305 1306 /* 1307 * see the comment above CGRP_ROOT_FAVOR_DYNMODS definition. 1308 * favordynmods can flip while task is between 1309 * cgroup_threadgroup_change_begin() and end(), so down_write global 1310 * cgroup_threadgroup_rwsem to synchronize them. 1311 * 1312 * Once cgroup_enable_per_threadgroup_rwsem is enabled, holding 1313 * cgroup_threadgroup_rwsem doesn't exlude tasks between 1314 * cgroup_thread_group_change_begin() and end() and thus it's unsafe to 1315 * turn off. As the scenario is unlikely, simply disallow disabling once 1316 * enabled and print out a warning. 1317 */ 1318 percpu_down_write(&cgroup_threadgroup_rwsem); 1319 if (favor && !favoring) { 1320 cgroup_enable_per_threadgroup_rwsem = true; 1321 rcu_sync_enter(&cgroup_threadgroup_rwsem.rss); 1322 root->flags |= CGRP_ROOT_FAVOR_DYNMODS; 1323 } else if (!favor && favoring) { 1324 if (cgroup_enable_per_threadgroup_rwsem) 1325 pr_warn_once("cgroup favordynmods: per threadgroup rwsem mechanism can't be disabled\n"); 1326 rcu_sync_exit(&cgroup_threadgroup_rwsem.rss); 1327 root->flags &= ~CGRP_ROOT_FAVOR_DYNMODS; 1328 } 1329 percpu_up_write(&cgroup_threadgroup_rwsem); 1330 } 1331 1332 static int cgroup_init_root_id(struct cgroup_root *root) 1333 { 1334 int id; 1335 1336 lockdep_assert_held(&cgroup_mutex); 1337 1338 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL); 1339 if (id < 0) 1340 return id; 1341 1342 root->hierarchy_id = id; 1343 return 0; 1344 } 1345 1346 static void cgroup_exit_root_id(struct cgroup_root *root) 1347 { 1348 lockdep_assert_held(&cgroup_mutex); 1349 1350 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id); 1351 } 1352 1353 void cgroup_free_root(struct cgroup_root *root) 1354 { 1355 kfree_rcu(root, rcu); 1356 } 1357 1358 static void cgroup_destroy_root(struct cgroup_root *root) 1359 { 1360 struct cgroup *cgrp = &root->cgrp; 1361 struct cgrp_cset_link *link, *tmp_link; 1362 int ret; 1363 1364 trace_cgroup_destroy_root(root); 1365 1366 /* runs off a workqueue, no signal can interrupt the drain */ 1367 ret = cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp); 1368 if (WARN_ON_ONCE(ret)) 1369 cgroup_lock(); 1370 1371 BUG_ON(atomic_read(&root->nr_cgrps)); 1372 BUG_ON(!list_empty(&cgrp->self.children)); 1373 1374 ret = blocking_notifier_call_chain(&cgroup_lifetime_notifier, 1375 CGROUP_LIFETIME_OFFLINE, cgrp); 1376 WARN_ON_ONCE(notifier_to_errno(ret)); 1377 1378 /* Rebind all subsystems back to the default hierarchy */ 1379 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask)); 1380 1381 /* 1382 * Release all the links from cset_links to this hierarchy's 1383 * root cgroup 1384 */ 1385 spin_lock_irq(&css_set_lock); 1386 1387 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) { 1388 list_del(&link->cset_link); 1389 list_del(&link->cgrp_link); 1390 kfree(link); 1391 } 1392 1393 spin_unlock_irq(&css_set_lock); 1394 1395 WARN_ON_ONCE(list_empty(&root->root_list)); 1396 list_del_rcu(&root->root_list); 1397 cgroup_root_count--; 1398 1399 if (!have_favordynmods) 1400 cgroup_favor_dynmods(root, false); 1401 1402 cgroup_exit_root_id(root); 1403 1404 cgroup_unlock(); 1405 1406 kernfs_destroy_root(root->kf_root); 1407 cgroup_free_root(root); 1408 } 1409 1410 /* 1411 * Returned cgroup is without refcount but it's valid as long as cset pins it. 1412 */ 1413 static inline struct cgroup *__cset_cgroup_from_root(struct css_set *cset, 1414 struct cgroup_root *root) 1415 { 1416 struct cgroup *res_cgroup = NULL; 1417 1418 if (cset == &init_css_set) { 1419 res_cgroup = &root->cgrp; 1420 } else if (root == &cgrp_dfl_root) { 1421 res_cgroup = cset->dfl_cgrp; 1422 } else { 1423 struct cgrp_cset_link *link; 1424 lockdep_assert_held(&css_set_lock); 1425 1426 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) { 1427 struct cgroup *c = link->cgrp; 1428 1429 if (c->root == root) { 1430 res_cgroup = c; 1431 break; 1432 } 1433 } 1434 } 1435 1436 /* 1437 * If cgroup_mutex is not held, the cgrp_cset_link will be freed 1438 * before we remove the cgroup root from the root_list. Consequently, 1439 * when accessing a cgroup root, the cset_link may have already been 1440 * freed, resulting in a NULL res_cgroup. However, by holding the 1441 * cgroup_mutex, we ensure that res_cgroup can't be NULL. 1442 * If we don't hold cgroup_mutex in the caller, we must do the NULL 1443 * check. 1444 */ 1445 return res_cgroup; 1446 } 1447 1448 /* 1449 * look up cgroup associated with current task's cgroup namespace on the 1450 * specified hierarchy 1451 */ 1452 static struct cgroup * 1453 current_cgns_cgroup_from_root(struct cgroup_root *root) 1454 { 1455 struct cgroup *res = NULL; 1456 struct css_set *cset; 1457 1458 lockdep_assert_held(&css_set_lock); 1459 1460 rcu_read_lock(); 1461 1462 cset = current->nsproxy->cgroup_ns->root_cset; 1463 res = __cset_cgroup_from_root(cset, root); 1464 1465 rcu_read_unlock(); 1466 1467 /* 1468 * The namespace_sem is held by current, so the root cgroup can't 1469 * be umounted. Therefore, we can ensure that the res is non-NULL. 1470 */ 1471 WARN_ON_ONCE(!res); 1472 return res; 1473 } 1474 1475 /* 1476 * Look up cgroup associated with current task's cgroup namespace on the default 1477 * hierarchy. 1478 * 1479 * Unlike current_cgns_cgroup_from_root(), this doesn't need locks: 1480 * - Internal rcu_read_lock is unnecessary because we don't dereference any rcu 1481 * pointers. 1482 * - css_set_lock is not needed because we just read cset->dfl_cgrp. 1483 * - As a bonus returned cgrp is pinned with the current because it cannot 1484 * switch cgroup_ns asynchronously. 1485 */ 1486 static struct cgroup *current_cgns_cgroup_dfl(void) 1487 { 1488 struct css_set *cset; 1489 1490 if (current->nsproxy) { 1491 cset = current->nsproxy->cgroup_ns->root_cset; 1492 return __cset_cgroup_from_root(cset, &cgrp_dfl_root); 1493 } else { 1494 /* 1495 * NOTE: This function may be called from bpf_cgroup_from_id() 1496 * on a task which has already passed exit_nsproxy_namespaces() 1497 * and nsproxy == NULL. Fall back to cgrp_dfl_root which will 1498 * make all cgroups visible for lookups. 1499 */ 1500 return &cgrp_dfl_root.cgrp; 1501 } 1502 } 1503 1504 /* look up cgroup associated with given css_set on the specified hierarchy */ 1505 static struct cgroup *cset_cgroup_from_root(struct css_set *cset, 1506 struct cgroup_root *root) 1507 { 1508 lockdep_assert_held(&css_set_lock); 1509 1510 return __cset_cgroup_from_root(cset, root); 1511 } 1512 1513 /* 1514 * Return the cgroup for "task" from the given hierarchy. Must be 1515 * called with css_set_lock held to prevent task's groups from being modified. 1516 * Must be called with either cgroup_mutex or rcu read lock to prevent the 1517 * cgroup root from being destroyed. 1518 */ 1519 struct cgroup *task_cgroup_from_root(struct task_struct *task, 1520 struct cgroup_root *root) 1521 { 1522 /* 1523 * No need to lock the task - since we hold css_set_lock the 1524 * task can't change groups. 1525 */ 1526 return cset_cgroup_from_root(task_css_set(task), root); 1527 } 1528 1529 /* 1530 * A task must hold cgroup_mutex to modify cgroups. 1531 * 1532 * Any task can increment and decrement the count field without lock. 1533 * So in general, code holding cgroup_mutex can't rely on the count 1534 * field not changing. However, if the count goes to zero, then only 1535 * cgroup_attach_task() can increment it again. Because a count of zero 1536 * means that no tasks are currently attached, therefore there is no 1537 * way a task attached to that cgroup can fork (the other way to 1538 * increment the count). So code holding cgroup_mutex can safely 1539 * assume that if the count is zero, it will stay zero. Similarly, if 1540 * a task holds cgroup_mutex on a cgroup with zero count, it 1541 * knows that the cgroup won't be removed, as cgroup_rmdir() 1542 * needs that mutex. 1543 * 1544 * A cgroup can only be deleted if both its 'count' of using tasks 1545 * is zero, and its list of 'children' cgroups is empty. Since all 1546 * tasks in the system use _some_ cgroup, and since there is always at 1547 * least one task in the system (init, pid == 1), therefore, root cgroup 1548 * always has either children cgroups and/or using tasks. So we don't 1549 * need a special hack to ensure that root cgroup cannot be deleted. 1550 * 1551 * P.S. One more locking exception. RCU is used to guard the 1552 * update of a tasks cgroup pointer by cgroup_attach_task() 1553 */ 1554 1555 static struct kernfs_syscall_ops cgroup_kf_syscall_ops; 1556 1557 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft, 1558 char *buf) 1559 { 1560 struct cgroup_subsys *ss = cft->ss; 1561 1562 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) && 1563 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) { 1564 const char *dbg = (cft->flags & CFTYPE_DEBUG) ? ".__DEBUG__." : ""; 1565 1566 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s%s.%s", 1567 dbg, cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name, 1568 cft->name); 1569 } else { 1570 strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX); 1571 } 1572 return buf; 1573 } 1574 1575 /** 1576 * cgroup_file_mode - deduce file mode of a control file 1577 * @cft: the control file in question 1578 * 1579 * S_IRUGO for read, S_IWUSR for write. 1580 */ 1581 static umode_t cgroup_file_mode(const struct cftype *cft) 1582 { 1583 umode_t mode = 0; 1584 1585 if (cft->read_u64 || cft->read_s64 || cft->seq_show) 1586 mode |= S_IRUGO; 1587 1588 if (cft->write_u64 || cft->write_s64 || cft->write) { 1589 if (cft->flags & CFTYPE_WORLD_WRITABLE) 1590 mode |= S_IWUGO; 1591 else 1592 mode |= S_IWUSR; 1593 } 1594 1595 return mode; 1596 } 1597 1598 /** 1599 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask 1600 * @subtree_control: the new subtree_control mask to consider 1601 * @this_ss_mask: available subsystems 1602 * 1603 * On the default hierarchy, a subsystem may request other subsystems to be 1604 * enabled together through its ->depends_on mask. In such cases, more 1605 * subsystems than specified in "cgroup.subtree_control" may be enabled. 1606 * 1607 * This function calculates which subsystems need to be enabled if 1608 * @subtree_control is to be applied while restricted to @this_ss_mask. 1609 */ 1610 static u32 cgroup_calc_subtree_ss_mask(u32 subtree_control, u32 this_ss_mask) 1611 { 1612 u32 cur_ss_mask = subtree_control; 1613 struct cgroup_subsys *ss; 1614 int ssid; 1615 1616 lockdep_assert_held(&cgroup_mutex); 1617 1618 cur_ss_mask |= cgrp_dfl_implicit_ss_mask; 1619 1620 while (true) { 1621 u32 new_ss_mask = cur_ss_mask; 1622 1623 do_each_subsys_mask(ss, ssid, cur_ss_mask) { 1624 new_ss_mask |= ss->depends_on; 1625 } while_each_subsys_mask(); 1626 1627 /* 1628 * Mask out subsystems which aren't available. This can 1629 * happen only if some depended-upon subsystems were bound 1630 * to non-default hierarchies. 1631 */ 1632 new_ss_mask &= this_ss_mask; 1633 1634 if (new_ss_mask == cur_ss_mask) 1635 break; 1636 cur_ss_mask = new_ss_mask; 1637 } 1638 1639 return cur_ss_mask; 1640 } 1641 1642 /** 1643 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods 1644 * @kn: the kernfs_node being serviced 1645 * 1646 * This helper undoes cgroup_kn_lock_live() and should be invoked before 1647 * the method finishes if locking succeeded. Note that once this function 1648 * returns the cgroup returned by cgroup_kn_lock_live() may become 1649 * inaccessible any time. If the caller intends to continue to access the 1650 * cgroup, it should pin it before invoking this function. 1651 */ 1652 void cgroup_kn_unlock(struct kernfs_node *kn) 1653 { 1654 struct cgroup *cgrp; 1655 1656 if (kernfs_type(kn) == KERNFS_DIR) 1657 cgrp = kn->priv; 1658 else 1659 cgrp = kn_priv(kn); 1660 1661 cgroup_unlock(); 1662 1663 kernfs_unbreak_active_protection(kn); 1664 cgroup_put(cgrp); 1665 } 1666 1667 /** 1668 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods 1669 * @kn: the kernfs_node being serviced 1670 * @drain_offline: perform offline draining on the cgroup 1671 * 1672 * This helper is to be used by a cgroup kernfs method currently servicing 1673 * @kn. It breaks the active protection, performs cgroup locking and 1674 * verifies that the associated cgroup is alive. Returns the cgroup if 1675 * alive; otherwise, an ERR_PTR value. A successful return should be undone by 1676 * a matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the 1677 * cgroup is drained of offlining csses before return, and an interrupted drain 1678 * fails with -ERESTARTSYS. 1679 * 1680 * Any cgroup kernfs method implementation which requires locking the 1681 * associated cgroup should use this helper. It avoids nesting cgroup 1682 * locking under kernfs active protection and allows all kernfs operations 1683 * including self-removal. 1684 */ 1685 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline) 1686 { 1687 struct cgroup *cgrp; 1688 int ret; 1689 1690 if (kernfs_type(kn) == KERNFS_DIR) 1691 cgrp = kn->priv; 1692 else 1693 cgrp = kn_priv(kn); 1694 1695 /* 1696 * We're gonna grab cgroup_mutex which nests outside kernfs 1697 * active_ref. cgroup liveliness check alone provides enough 1698 * protection against removal. Ensure @cgrp stays accessible and 1699 * break the active_ref protection. 1700 */ 1701 if (!cgroup_tryget(cgrp)) 1702 return ERR_PTR(-ENODEV); 1703 kernfs_break_active_protection(kn); 1704 1705 if (drain_offline) { 1706 ret = cgroup_lock_and_drain_offline(cgrp); 1707 if (unlikely(ret)) { 1708 kernfs_unbreak_active_protection(kn); 1709 cgroup_put(cgrp); 1710 return ERR_PTR(ret); 1711 } 1712 } else { 1713 cgroup_lock(); 1714 } 1715 1716 if (!cgroup_is_dead(cgrp)) 1717 return cgrp; 1718 1719 cgroup_kn_unlock(kn); 1720 return ERR_PTR(-ENODEV); 1721 } 1722 1723 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft) 1724 { 1725 char name[CGROUP_FILE_NAME_MAX]; 1726 1727 lockdep_assert_held(&cgroup_mutex); 1728 1729 if (cft->file_offset) { 1730 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss); 1731 struct cgroup_file *cfile = (void *)css + cft->file_offset; 1732 1733 spin_lock_irq(&cfile->lock); 1734 WRITE_ONCE(cfile->kn, NULL); 1735 spin_unlock_irq(&cfile->lock); 1736 1737 timer_delete_sync(&cfile->notify_timer); 1738 } 1739 1740 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name)); 1741 } 1742 1743 /** 1744 * css_clear_dir - remove subsys files in a cgroup directory 1745 * @css: target css 1746 */ 1747 static void css_clear_dir(struct cgroup_subsys_state *css) 1748 { 1749 struct cgroup *cgrp = css->cgroup; 1750 struct cftype *cfts; 1751 1752 if (!(css->flags & CSS_VISIBLE)) 1753 return; 1754 1755 css->flags &= ~CSS_VISIBLE; 1756 1757 if (css_is_self(css)) { 1758 if (cgroup_on_dfl(cgrp)) { 1759 cgroup_addrm_files(css, cgrp, 1760 cgroup_base_files, false); 1761 if (cgroup_psi_enabled()) 1762 cgroup_addrm_files(css, cgrp, 1763 cgroup_psi_files, false); 1764 } else { 1765 cgroup_addrm_files(css, cgrp, 1766 cgroup1_base_files, false); 1767 } 1768 } else { 1769 list_for_each_entry(cfts, &css->ss->cfts, node) 1770 cgroup_addrm_files(css, cgrp, cfts, false); 1771 } 1772 } 1773 1774 /** 1775 * css_populate_dir - create subsys files in a cgroup directory 1776 * @css: target css 1777 * 1778 * On failure, no file is added. 1779 */ 1780 static int css_populate_dir(struct cgroup_subsys_state *css) 1781 { 1782 struct cgroup *cgrp = css->cgroup; 1783 struct cftype *cfts, *failed_cfts; 1784 int ret; 1785 1786 if (css->flags & CSS_VISIBLE) 1787 return 0; 1788 1789 if (css_is_self(css)) { 1790 if (cgroup_on_dfl(cgrp)) { 1791 ret = cgroup_addrm_files(css, cgrp, 1792 cgroup_base_files, true); 1793 if (ret < 0) 1794 return ret; 1795 1796 if (cgroup_psi_enabled()) { 1797 ret = cgroup_addrm_files(css, cgrp, 1798 cgroup_psi_files, true); 1799 if (ret < 0) { 1800 cgroup_addrm_files(css, cgrp, 1801 cgroup_base_files, false); 1802 return ret; 1803 } 1804 } 1805 } else { 1806 ret = cgroup_addrm_files(css, cgrp, 1807 cgroup1_base_files, true); 1808 if (ret < 0) 1809 return ret; 1810 } 1811 } else { 1812 list_for_each_entry(cfts, &css->ss->cfts, node) { 1813 ret = cgroup_addrm_files(css, cgrp, cfts, true); 1814 if (ret < 0) { 1815 failed_cfts = cfts; 1816 goto err; 1817 } 1818 } 1819 } 1820 1821 css->flags |= CSS_VISIBLE; 1822 1823 return 0; 1824 err: 1825 list_for_each_entry(cfts, &css->ss->cfts, node) { 1826 if (cfts == failed_cfts) 1827 break; 1828 cgroup_addrm_files(css, cgrp, cfts, false); 1829 } 1830 return ret; 1831 } 1832 1833 int rebind_subsystems(struct cgroup_root *dst_root, u32 ss_mask) 1834 { 1835 struct cgroup *dcgrp = &dst_root->cgrp; 1836 struct cgroup_subsys *ss; 1837 int ssid, ret; 1838 u32 dfl_disable_ss_mask = 0; 1839 1840 lockdep_assert_held(&cgroup_mutex); 1841 1842 do_each_subsys_mask(ss, ssid, ss_mask) { 1843 /* 1844 * If @ss has non-root csses attached to it, can't move. 1845 * If @ss is an implicit controller, it is exempt from this 1846 * rule and can be stolen. 1847 */ 1848 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) && 1849 !ss->implicit_on_dfl) 1850 return -EBUSY; 1851 1852 /* can't move between two non-dummy roots either */ 1853 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root) 1854 return -EBUSY; 1855 1856 /* 1857 * Collect ssid's that need to be disabled from default 1858 * hierarchy. 1859 */ 1860 if (ss->root == &cgrp_dfl_root) 1861 dfl_disable_ss_mask |= 1 << ssid; 1862 1863 } while_each_subsys_mask(); 1864 1865 if (dfl_disable_ss_mask) { 1866 struct cgroup *scgrp = &cgrp_dfl_root.cgrp; 1867 1868 /* 1869 * Controllers leaving the default hierarchy are disabled 1870 * together. cgroup_rebind_ss_mask makes cgroup_apply_control() 1871 * migrate their tasks to the root css, so the per-cgroup csses 1872 * are unpopulated when cgroup_finalize_control() kills them. 1873 * Clear it before cgroup_finalize_control(), which does no 1874 * css_set lookup. 1875 */ 1876 cgrp_dfl_root.subsys_mask &= ~dfl_disable_ss_mask; 1877 cgroup_rebind_ss_mask = dfl_disable_ss_mask; 1878 WARN_ON(cgroup_apply_control(scgrp)); 1879 cgroup_rebind_ss_mask = 0; 1880 cgroup_finalize_control(scgrp, 0); 1881 } 1882 1883 do_each_subsys_mask(ss, ssid, ss_mask) { 1884 struct cgroup_root *src_root = ss->root; 1885 struct cgroup *scgrp = &src_root->cgrp; 1886 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss); 1887 struct css_set *cset, *cset_pos; 1888 struct css_task_iter *it; 1889 1890 WARN_ON(!css || cgroup_css(dcgrp, ss)); 1891 1892 if (src_root != &cgrp_dfl_root) { 1893 /* 1894 * Disable from the source, migrating its tasks to the 1895 * root css first (see cgroup_rebind_ss_mask). 1896 */ 1897 src_root->subsys_mask &= ~(1 << ssid); 1898 cgroup_rebind_ss_mask = 1 << ssid; 1899 WARN_ON(cgroup_apply_control(scgrp)); 1900 cgroup_rebind_ss_mask = 0; 1901 cgroup_finalize_control(scgrp, 0); 1902 } 1903 1904 /* rebind */ 1905 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL); 1906 rcu_assign_pointer(dcgrp->subsys[ssid], css); 1907 ss->root = dst_root; 1908 1909 spin_lock_irq(&css_set_lock); 1910 css->cgroup = dcgrp; 1911 WARN_ON(!list_empty(&dcgrp->e_csets[ss->id])); 1912 list_for_each_entry_safe(cset, cset_pos, &scgrp->e_csets[ss->id], 1913 e_cset_node[ss->id]) { 1914 list_move_tail(&cset->e_cset_node[ss->id], 1915 &dcgrp->e_csets[ss->id]); 1916 /* 1917 * all css_sets of scgrp together in same order to dcgrp, 1918 * patch in-flight iterators to preserve correct iteration. 1919 * since the iterator is always advanced right away and 1920 * finished when it->cset_pos meets it->cset_head, so only 1921 * update it->cset_head is enough here. 1922 */ 1923 list_for_each_entry(it, &cset->task_iters, iters_node) 1924 if (it->cset_head == &scgrp->e_csets[ss->id]) 1925 it->cset_head = &dcgrp->e_csets[ss->id]; 1926 } 1927 spin_unlock_irq(&css_set_lock); 1928 1929 /* default hierarchy doesn't enable controllers by default */ 1930 dst_root->subsys_mask |= 1 << ssid; 1931 if (dst_root == &cgrp_dfl_root) { 1932 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]); 1933 } else { 1934 dcgrp->subtree_control |= 1 << ssid; 1935 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]); 1936 } 1937 1938 ret = cgroup_apply_control(dcgrp); 1939 if (ret) 1940 pr_warn("partial failure to rebind %s controller (err=%d)\n", 1941 ss->name, ret); 1942 1943 if (ss->bind) 1944 ss->bind(css); 1945 } while_each_subsys_mask(); 1946 1947 kernfs_activate(dcgrp->kn); 1948 return 0; 1949 } 1950 1951 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node, 1952 struct kernfs_root *kf_root) 1953 { 1954 int len = 0; 1955 char *buf = NULL; 1956 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root); 1957 struct cgroup *ns_cgroup; 1958 1959 buf = kmalloc(PATH_MAX, GFP_KERNEL); 1960 if (!buf) 1961 return -ENOMEM; 1962 1963 spin_lock_irq(&css_set_lock); 1964 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot); 1965 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX); 1966 spin_unlock_irq(&css_set_lock); 1967 1968 if (len == -E2BIG) 1969 len = -ERANGE; 1970 else if (len > 0) { 1971 seq_escape(sf, buf, " \t\n\\"); 1972 len = 0; 1973 } 1974 kfree(buf); 1975 return len; 1976 } 1977 1978 enum cgroup2_param { 1979 Opt_nsdelegate, 1980 Opt_favordynmods, 1981 Opt_memory_localevents, 1982 Opt_memory_recursiveprot, 1983 Opt_memory_hugetlb_accounting, 1984 Opt_pids_localevents, 1985 nr__cgroup2_params 1986 }; 1987 1988 static const struct fs_parameter_spec cgroup2_fs_parameters[] = { 1989 fsparam_flag("nsdelegate", Opt_nsdelegate), 1990 fsparam_flag("favordynmods", Opt_favordynmods), 1991 fsparam_flag("memory_localevents", Opt_memory_localevents), 1992 fsparam_flag("memory_recursiveprot", Opt_memory_recursiveprot), 1993 fsparam_flag("memory_hugetlb_accounting", Opt_memory_hugetlb_accounting), 1994 fsparam_flag("pids_localevents", Opt_pids_localevents), 1995 {} 1996 }; 1997 1998 static int cgroup2_parse_param(struct fs_context *fc, struct fs_parameter *param) 1999 { 2000 struct cgroup_fs_context *ctx = cgroup_fc2context(fc); 2001 struct fs_parse_result result; 2002 int opt; 2003 2004 opt = fs_parse(fc, cgroup2_fs_parameters, param, &result); 2005 if (opt < 0) 2006 return opt; 2007 2008 switch (opt) { 2009 case Opt_nsdelegate: 2010 ctx->flags |= CGRP_ROOT_NS_DELEGATE; 2011 return 0; 2012 case Opt_favordynmods: 2013 ctx->flags |= CGRP_ROOT_FAVOR_DYNMODS; 2014 return 0; 2015 case Opt_memory_localevents: 2016 ctx->flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS; 2017 return 0; 2018 case Opt_memory_recursiveprot: 2019 ctx->flags |= CGRP_ROOT_MEMORY_RECURSIVE_PROT; 2020 return 0; 2021 case Opt_memory_hugetlb_accounting: 2022 ctx->flags |= CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING; 2023 return 0; 2024 case Opt_pids_localevents: 2025 ctx->flags |= CGRP_ROOT_PIDS_LOCAL_EVENTS; 2026 return 0; 2027 } 2028 return -EINVAL; 2029 } 2030 2031 struct cgroup_of_peak *of_peak(struct kernfs_open_file *of) 2032 { 2033 struct cgroup_file_ctx *ctx = of->priv; 2034 2035 return &ctx->peak; 2036 } 2037 2038 static void apply_cgroup_root_flags(unsigned int root_flags) 2039 { 2040 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) { 2041 if (root_flags & CGRP_ROOT_NS_DELEGATE) 2042 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE; 2043 else 2044 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE; 2045 2046 cgroup_favor_dynmods(&cgrp_dfl_root, 2047 root_flags & CGRP_ROOT_FAVOR_DYNMODS); 2048 2049 if (root_flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS) 2050 cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS; 2051 else 2052 cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_LOCAL_EVENTS; 2053 2054 if (root_flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT) 2055 cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_RECURSIVE_PROT; 2056 else 2057 cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_RECURSIVE_PROT; 2058 2059 if (root_flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING) 2060 cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING; 2061 else 2062 cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING; 2063 2064 if (root_flags & CGRP_ROOT_PIDS_LOCAL_EVENTS) 2065 cgrp_dfl_root.flags |= CGRP_ROOT_PIDS_LOCAL_EVENTS; 2066 else 2067 cgrp_dfl_root.flags &= ~CGRP_ROOT_PIDS_LOCAL_EVENTS; 2068 } 2069 } 2070 2071 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root) 2072 { 2073 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) 2074 seq_puts(seq, ",nsdelegate"); 2075 if (cgrp_dfl_root.flags & CGRP_ROOT_FAVOR_DYNMODS) 2076 seq_puts(seq, ",favordynmods"); 2077 if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS) 2078 seq_puts(seq, ",memory_localevents"); 2079 if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT) 2080 seq_puts(seq, ",memory_recursiveprot"); 2081 if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING) 2082 seq_puts(seq, ",memory_hugetlb_accounting"); 2083 if (cgrp_dfl_root.flags & CGRP_ROOT_PIDS_LOCAL_EVENTS) 2084 seq_puts(seq, ",pids_localevents"); 2085 return 0; 2086 } 2087 2088 static int cgroup_reconfigure(struct fs_context *fc) 2089 { 2090 struct cgroup_fs_context *ctx = cgroup_fc2context(fc); 2091 2092 apply_cgroup_root_flags(ctx->flags); 2093 return 0; 2094 } 2095 2096 static void init_cgroup_housekeeping(struct cgroup *cgrp) 2097 { 2098 struct cgroup_subsys *ss; 2099 int ssid; 2100 2101 INIT_LIST_HEAD(&cgrp->self.sibling); 2102 INIT_LIST_HEAD(&cgrp->self.children); 2103 INIT_LIST_HEAD(&cgrp->cset_links); 2104 INIT_LIST_HEAD(&cgrp->pidlists); 2105 mutex_init(&cgrp->pidlist_mutex); 2106 cgrp->self.cgroup = cgrp; 2107 cgrp->self.flags |= CSS_ONLINE; 2108 cgrp->dom_cgrp = cgrp; 2109 cgrp->max_descendants = INT_MAX; 2110 cgrp->max_depth = INT_MAX; 2111 prev_cputime_init(&cgrp->prev_cputime); 2112 2113 for_each_subsys(ss, ssid) 2114 INIT_LIST_HEAD(&cgrp->e_csets[ssid]); 2115 2116 #ifdef CONFIG_CGROUP_BPF 2117 for (int i = 0; i < ARRAY_SIZE(cgrp->bpf.revisions); i++) 2118 cgrp->bpf.revisions[i] = 1; 2119 #endif 2120 2121 init_waitqueue_head(&cgrp->offline_waitq); 2122 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent); 2123 } 2124 2125 void init_cgroup_root(struct cgroup_fs_context *ctx) 2126 { 2127 struct cgroup_root *root = ctx->root; 2128 struct cgroup *cgrp = &root->cgrp; 2129 struct cgroup_subsys *ss; 2130 int ssid; 2131 2132 INIT_LIST_HEAD_RCU(&root->root_list); 2133 atomic_set(&root->nr_cgrps, 1); 2134 cgrp->root = root; 2135 init_cgroup_housekeeping(cgrp); 2136 2137 /* 2138 * A root cgroup's effective css is always the root css in 2139 * init_css_set.subsys[], whichever hierarchy the subsystem is bound 2140 * to, so rebind_subsystems() doesn't need to update e_css[]. For 2141 * cgrp_dfl_root this runs before the root csses exist, and 2142 * online_css() sets the entries when they come online. 2143 */ 2144 for_each_subsys(ss, ssid) 2145 RCU_INIT_POINTER(cgrp->e_css[ssid], init_css_set.subsys[ssid]); 2146 2147 /* DYNMODS must be modified through cgroup_favor_dynmods() */ 2148 root->flags = ctx->flags & ~CGRP_ROOT_FAVOR_DYNMODS; 2149 if (ctx->release_agent) 2150 strscpy(root->release_agent_path, ctx->release_agent, PATH_MAX); 2151 if (ctx->name) 2152 strscpy(root->name, ctx->name, MAX_CGROUP_ROOT_NAMELEN); 2153 if (ctx->cpuset_clone_children) 2154 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags); 2155 } 2156 2157 int cgroup_setup_root(struct cgroup_root *root, u32 ss_mask) 2158 { 2159 LIST_HEAD(tmp_links); 2160 struct cgroup *root_cgrp = &root->cgrp; 2161 struct kernfs_syscall_ops *kf_sops; 2162 struct css_set *cset; 2163 int i, ret; 2164 2165 lockdep_assert_held(&cgroup_mutex); 2166 2167 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release, 2168 0, GFP_KERNEL); 2169 if (ret) 2170 goto out; 2171 2172 /* 2173 * We're accessing css_set_count without locking css_set_lock here, 2174 * but that's OK - it can only be increased by someone holding 2175 * cgroup_lock, and that's us. Later rebinding may disable 2176 * controllers on the default hierarchy and thus create new csets, 2177 * which can't be more than the existing ones. Allocate 2x. 2178 */ 2179 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links); 2180 if (ret) 2181 goto cancel_ref; 2182 2183 ret = cgroup_init_root_id(root); 2184 if (ret) 2185 goto cancel_ref; 2186 2187 kf_sops = root == &cgrp_dfl_root ? 2188 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops; 2189 2190 root->kf_root = kernfs_create_root(kf_sops, 2191 KERNFS_ROOT_CREATE_DEACTIVATED | 2192 KERNFS_ROOT_SUPPORT_EXPORTOP | 2193 KERNFS_ROOT_SUPPORT_USER_XATTR | 2194 KERNFS_ROOT_INVARIANT_PARENT, 2195 root_cgrp); 2196 if (IS_ERR(root->kf_root)) { 2197 ret = PTR_ERR(root->kf_root); 2198 goto exit_root_id; 2199 } 2200 root_cgrp->kn = kernfs_root_to_node(root->kf_root); 2201 WARN_ON_ONCE(cgroup_ino(root_cgrp) != 1); 2202 root_cgrp->ancestors[0] = root_cgrp; 2203 2204 ret = css_populate_dir(&root_cgrp->self); 2205 if (ret) 2206 goto destroy_root; 2207 2208 ret = css_rstat_init(&root_cgrp->self); 2209 if (ret) 2210 goto destroy_root; 2211 2212 ret = rebind_subsystems(root, ss_mask); 2213 if (ret) 2214 goto exit_stats; 2215 2216 ret = blocking_notifier_call_chain(&cgroup_lifetime_notifier, 2217 CGROUP_LIFETIME_ONLINE, root_cgrp); 2218 WARN_ON_ONCE(notifier_to_errno(ret)); 2219 2220 trace_cgroup_setup_root(root); 2221 2222 /* 2223 * There must be no failure case after here, since rebinding takes 2224 * care of subsystems' refcounts, which are explicitly dropped in 2225 * the failure exit path. 2226 */ 2227 list_add_rcu(&root->root_list, &cgroup_roots); 2228 cgroup_root_count++; 2229 2230 /* 2231 * Link the root cgroup in this hierarchy into all the css_set 2232 * objects. 2233 */ 2234 spin_lock_irq(&css_set_lock); 2235 hash_for_each(css_set_table, i, cset, hlist) { 2236 link_css_set(&tmp_links, cset, root_cgrp); 2237 if (css_set_populated(cset)) 2238 css_update_populated(&root_cgrp->self, true); 2239 } 2240 spin_unlock_irq(&css_set_lock); 2241 2242 BUG_ON(!list_empty(&root_cgrp->self.children)); 2243 BUG_ON(atomic_read(&root->nr_cgrps) != 1); 2244 2245 ret = 0; 2246 goto out; 2247 2248 exit_stats: 2249 css_rstat_exit(&root_cgrp->self); 2250 destroy_root: 2251 kernfs_destroy_root(root->kf_root); 2252 root->kf_root = NULL; 2253 exit_root_id: 2254 cgroup_exit_root_id(root); 2255 cancel_ref: 2256 percpu_ref_exit(&root_cgrp->self.refcnt); 2257 out: 2258 free_cgrp_cset_links(&tmp_links); 2259 return ret; 2260 } 2261 2262 int cgroup_do_get_tree(struct fs_context *fc) 2263 { 2264 struct cgroup_fs_context *ctx = cgroup_fc2context(fc); 2265 int ret; 2266 2267 ctx->kfc.root = ctx->root->kf_root; 2268 if (fc->fs_type == &cgroup2_fs_type) 2269 ctx->kfc.magic = CGROUP2_SUPER_MAGIC; 2270 else 2271 ctx->kfc.magic = CGROUP_SUPER_MAGIC; 2272 ret = kernfs_get_tree(fc); 2273 2274 /* 2275 * In non-init cgroup namespace, instead of root cgroup's dentry, 2276 * we return the dentry corresponding to the cgroupns->root_cgrp. 2277 */ 2278 if (!ret && ctx->ns != &init_cgroup_ns) { 2279 struct dentry *nsdentry; 2280 struct super_block *sb = fc->root->d_sb; 2281 struct cgroup *cgrp; 2282 2283 cgroup_lock(); 2284 spin_lock_irq(&css_set_lock); 2285 2286 cgrp = cset_cgroup_from_root(ctx->ns->root_cset, ctx->root); 2287 2288 spin_unlock_irq(&css_set_lock); 2289 cgroup_unlock(); 2290 2291 nsdentry = kernfs_node_dentry(cgrp->kn, sb); 2292 dput(fc->root); 2293 if (IS_ERR(nsdentry)) { 2294 deactivate_locked_super(sb); 2295 ret = PTR_ERR(nsdentry); 2296 nsdentry = NULL; 2297 } 2298 fc->root = nsdentry; 2299 } 2300 2301 if (!ctx->kfc.new_sb_created) 2302 cgroup_put(&ctx->root->cgrp); 2303 2304 return ret; 2305 } 2306 2307 /* 2308 * Destroy a cgroup filesystem context. 2309 */ 2310 static void cgroup_fs_context_free(struct fs_context *fc) 2311 { 2312 struct cgroup_fs_context *ctx = cgroup_fc2context(fc); 2313 2314 kfree(ctx->name); 2315 kfree(ctx->release_agent); 2316 put_cgroup_ns(ctx->ns); 2317 kernfs_free_fs_context(fc); 2318 kfree(ctx); 2319 } 2320 2321 static int cgroup_get_tree(struct fs_context *fc) 2322 { 2323 struct cgroup_fs_context *ctx = cgroup_fc2context(fc); 2324 int ret; 2325 2326 WRITE_ONCE(cgrp_dfl_visible, true); 2327 cgroup_get_live(&cgrp_dfl_root.cgrp); 2328 ctx->root = &cgrp_dfl_root; 2329 2330 ret = cgroup_do_get_tree(fc); 2331 if (!ret) 2332 apply_cgroup_root_flags(ctx->flags); 2333 return ret; 2334 } 2335 2336 static const struct fs_context_operations cgroup_fs_context_ops = { 2337 .free = cgroup_fs_context_free, 2338 .parse_param = cgroup2_parse_param, 2339 .get_tree = cgroup_get_tree, 2340 .reconfigure = cgroup_reconfigure, 2341 }; 2342 2343 static const struct fs_context_operations cgroup1_fs_context_ops = { 2344 .free = cgroup_fs_context_free, 2345 .parse_param = cgroup1_parse_param, 2346 .get_tree = cgroup1_get_tree, 2347 .reconfigure = cgroup1_reconfigure, 2348 }; 2349 2350 /* 2351 * Initialise the cgroup filesystem creation/reconfiguration context. Notably, 2352 * we select the namespace we're going to use. 2353 */ 2354 static int cgroup_init_fs_context(struct fs_context *fc) 2355 { 2356 struct cgroup_fs_context *ctx; 2357 2358 ctx = kzalloc_obj(struct cgroup_fs_context); 2359 if (!ctx) 2360 return -ENOMEM; 2361 2362 ctx->ns = current->nsproxy->cgroup_ns; 2363 get_cgroup_ns(ctx->ns); 2364 fc->fs_private = &ctx->kfc; 2365 if (fc->fs_type == &cgroup2_fs_type) 2366 fc->ops = &cgroup_fs_context_ops; 2367 else 2368 fc->ops = &cgroup1_fs_context_ops; 2369 put_user_ns(fc->user_ns); 2370 fc->user_ns = get_user_ns(ctx->ns->user_ns); 2371 fc->global = true; 2372 2373 if (have_favordynmods) 2374 ctx->flags |= CGRP_ROOT_FAVOR_DYNMODS; 2375 2376 return 0; 2377 } 2378 2379 static void cgroup_kill_sb(struct super_block *sb) 2380 { 2381 struct kernfs_root *kf_root = kernfs_root_from_sb(sb); 2382 struct cgroup_root *root = cgroup_root_from_kf(kf_root); 2383 2384 /* 2385 * If @root doesn't have any children, start killing it. 2386 * This prevents new mounts by disabling percpu_ref_tryget_live(). 2387 * 2388 * And don't kill the default root. 2389 */ 2390 if (list_empty(&root->cgrp.self.children) && root != &cgrp_dfl_root && 2391 !percpu_ref_is_dying(&root->cgrp.self.refcnt)) 2392 percpu_ref_kill(&root->cgrp.self.refcnt); 2393 cgroup_put(&root->cgrp); 2394 kernfs_kill_sb(sb); 2395 } 2396 2397 struct file_system_type cgroup_fs_type = { 2398 .name = "cgroup", 2399 .init_fs_context = cgroup_init_fs_context, 2400 .parameters = cgroup1_fs_parameters, 2401 .kill_sb = cgroup_kill_sb, 2402 .fs_flags = FS_USERNS_MOUNT, 2403 }; 2404 2405 static struct file_system_type cgroup2_fs_type = { 2406 .name = "cgroup2", 2407 .init_fs_context = cgroup_init_fs_context, 2408 .parameters = cgroup2_fs_parameters, 2409 .kill_sb = cgroup_kill_sb, 2410 .fs_flags = FS_USERNS_MOUNT, 2411 }; 2412 2413 #ifdef CONFIG_CPUSETS_V1 2414 enum cpuset_param { 2415 Opt_cpuset_v2_mode, 2416 }; 2417 2418 static const struct fs_parameter_spec cpuset_fs_parameters[] = { 2419 fsparam_flag ("cpuset_v2_mode", Opt_cpuset_v2_mode), 2420 {} 2421 }; 2422 2423 static int cpuset_parse_param(struct fs_context *fc, struct fs_parameter *param) 2424 { 2425 struct cgroup_fs_context *ctx = cgroup_fc2context(fc); 2426 struct fs_parse_result result; 2427 int opt; 2428 2429 opt = fs_parse(fc, cpuset_fs_parameters, param, &result); 2430 if (opt < 0) 2431 return opt; 2432 2433 switch (opt) { 2434 case Opt_cpuset_v2_mode: 2435 ctx->flags |= CGRP_ROOT_CPUSET_V2_MODE; 2436 return 0; 2437 } 2438 return -EINVAL; 2439 } 2440 2441 static const struct fs_context_operations cpuset_fs_context_ops = { 2442 .get_tree = cgroup1_get_tree, 2443 .free = cgroup_fs_context_free, 2444 .parse_param = cpuset_parse_param, 2445 }; 2446 2447 /* 2448 * This is ugly, but preserves the userspace API for existing cpuset 2449 * users. If someone tries to mount the "cpuset" filesystem, we 2450 * silently switch it to mount "cgroup" instead 2451 */ 2452 static int cpuset_init_fs_context(struct fs_context *fc) 2453 { 2454 char *agent = kstrdup("/sbin/cpuset_release_agent", GFP_USER); 2455 struct cgroup_fs_context *ctx; 2456 int err; 2457 2458 err = cgroup_init_fs_context(fc); 2459 if (err) { 2460 kfree(agent); 2461 return err; 2462 } 2463 2464 fc->ops = &cpuset_fs_context_ops; 2465 2466 ctx = cgroup_fc2context(fc); 2467 ctx->subsys_mask = 1 << cpuset_cgrp_id; 2468 ctx->flags |= CGRP_ROOT_NOPREFIX; 2469 ctx->release_agent = agent; 2470 2471 get_filesystem(&cgroup_fs_type); 2472 put_filesystem(fc->fs_type); 2473 fc->fs_type = &cgroup_fs_type; 2474 2475 return 0; 2476 } 2477 2478 static struct file_system_type cpuset_fs_type = { 2479 .name = "cpuset", 2480 .init_fs_context = cpuset_init_fs_context, 2481 .parameters = cpuset_fs_parameters, 2482 .fs_flags = FS_USERNS_MOUNT, 2483 }; 2484 #endif 2485 2486 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen, 2487 struct cgroup_namespace *ns) 2488 { 2489 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root); 2490 2491 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen); 2492 } 2493 2494 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen, 2495 struct cgroup_namespace *ns) 2496 { 2497 int ret; 2498 2499 cgroup_lock(); 2500 spin_lock_irq(&css_set_lock); 2501 2502 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns); 2503 2504 spin_unlock_irq(&css_set_lock); 2505 cgroup_unlock(); 2506 2507 return ret; 2508 } 2509 EXPORT_SYMBOL_GPL(cgroup_path_ns); 2510 2511 /** 2512 * cgroup_attach_lock - Lock for ->attach() 2513 * @lock_mode: whether acquire and acquire which rwsem 2514 * @tsk: thread group to lock 2515 * 2516 * cgroup migration sometimes needs to stabilize threadgroups against forks and 2517 * exits by write-locking cgroup_threadgroup_rwsem. However, some ->attach() 2518 * implementations (e.g. cpuset), also need to disable CPU hotplug. 2519 * Unfortunately, letting ->attach() operations acquire cpus_read_lock() can 2520 * lead to deadlocks. 2521 * 2522 * Bringing up a CPU may involve creating and destroying tasks which requires 2523 * read-locking threadgroup_rwsem, so threadgroup_rwsem nests inside 2524 * cpus_read_lock(). If we call an ->attach() which acquires the cpus lock while 2525 * write-locking threadgroup_rwsem, the locking order is reversed and we end up 2526 * waiting for an on-going CPU hotplug operation which in turn is waiting for 2527 * the threadgroup_rwsem to be released to create new tasks. For more details: 2528 * 2529 * http://lkml.kernel.org/r/20220711174629.uehfmqegcwn2lqzu@wubuntu 2530 * 2531 * Resolve the situation by always acquiring cpus_read_lock() before optionally 2532 * write-locking cgroup_threadgroup_rwsem. This allows ->attach() to assume that 2533 * CPU hotplug is disabled on entry. 2534 * 2535 * When favordynmods is enabled, take per threadgroup rwsem to reduce overhead 2536 * on dynamic cgroup modifications. see the comment above 2537 * CGRP_ROOT_FAVOR_DYNMODS definition. 2538 * 2539 * tsk is not NULL only when writing to cgroup.procs. 2540 */ 2541 void cgroup_attach_lock(enum cgroup_attach_lock_mode lock_mode, 2542 struct task_struct *tsk) 2543 { 2544 cpus_read_lock(); 2545 2546 switch (lock_mode) { 2547 case CGRP_ATTACH_LOCK_NONE: 2548 break; 2549 case CGRP_ATTACH_LOCK_GLOBAL: 2550 percpu_down_write(&cgroup_threadgroup_rwsem); 2551 break; 2552 case CGRP_ATTACH_LOCK_PER_THREADGROUP: 2553 down_write(&tsk->signal->cgroup_threadgroup_rwsem); 2554 break; 2555 default: 2556 pr_warn("cgroup: Unexpected attach lock mode."); 2557 break; 2558 } 2559 } 2560 2561 /** 2562 * cgroup_attach_unlock - Undo cgroup_attach_lock() 2563 * @lock_mode: whether release and release which rwsem 2564 * @tsk: thread group to lock 2565 */ 2566 void cgroup_attach_unlock(enum cgroup_attach_lock_mode lock_mode, 2567 struct task_struct *tsk) 2568 { 2569 switch (lock_mode) { 2570 case CGRP_ATTACH_LOCK_NONE: 2571 break; 2572 case CGRP_ATTACH_LOCK_GLOBAL: 2573 percpu_up_write(&cgroup_threadgroup_rwsem); 2574 break; 2575 case CGRP_ATTACH_LOCK_PER_THREADGROUP: 2576 up_write(&tsk->signal->cgroup_threadgroup_rwsem); 2577 break; 2578 default: 2579 pr_warn("cgroup: Unexpected attach lock mode."); 2580 break; 2581 } 2582 2583 cpus_read_unlock(); 2584 } 2585 2586 /** 2587 * cgroup_migrate_add_task - add a migration target task to a migration context 2588 * @task: target task 2589 * @mgctx: target migration context 2590 * 2591 * Add @task, which is a migration target, to @mgctx->tset. This function 2592 * becomes noop if @task doesn't need to be migrated. @task's css_set 2593 * should have been added as a migration source and @task->cg_list will be 2594 * moved from the css_set's tasks list to mg_tasks one. 2595 */ 2596 static void cgroup_migrate_add_task(struct task_struct *task, 2597 struct cgroup_mgctx *mgctx) 2598 { 2599 struct css_set *cset; 2600 2601 lockdep_assert_held(&css_set_lock); 2602 2603 /* @task either already exited or can't exit until the end */ 2604 if (task->flags & PF_EXITING) 2605 return; 2606 2607 /* cgroup_threadgroup_rwsem protects racing against forks */ 2608 WARN_ON_ONCE(list_empty(&task->cg_list)); 2609 2610 cset = task_css_set(task); 2611 if (!cset->mg_src_cgrp) 2612 return; 2613 2614 mgctx->tset.nr_tasks++; 2615 2616 css_set_skip_task_iters(cset, task); 2617 list_move_tail(&task->cg_list, &cset->mg_tasks); 2618 if (list_empty(&cset->mg_node)) 2619 list_add_tail(&cset->mg_node, 2620 &mgctx->tset.src_csets); 2621 if (list_empty(&cset->mg_dst_cset->mg_node)) 2622 list_add_tail(&cset->mg_dst_cset->mg_node, 2623 &mgctx->tset.dst_csets); 2624 } 2625 2626 /** 2627 * cgroup_taskset_first - reset taskset and return the first task 2628 * @tset: taskset of interest 2629 * @dst_cssp: output variable for the destination css 2630 * 2631 * @tset iteration is initialized and the first task is returned. 2632 */ 2633 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset, 2634 struct cgroup_subsys_state **dst_cssp) 2635 { 2636 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node); 2637 tset->cur_task = NULL; 2638 2639 return cgroup_taskset_next(tset, dst_cssp); 2640 } 2641 2642 /** 2643 * cgroup_taskset_next - iterate to the next task in taskset 2644 * @tset: taskset of interest 2645 * @dst_cssp: output variable for the destination css 2646 * 2647 * Return the next task in @tset. Iteration must have been initialized 2648 * with cgroup_taskset_first(). 2649 */ 2650 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset, 2651 struct cgroup_subsys_state **dst_cssp) 2652 { 2653 struct css_set *cset = tset->cur_cset; 2654 struct task_struct *task = tset->cur_task; 2655 2656 while (CGROUP_HAS_SUBSYS_CONFIG && &cset->mg_node != tset->csets) { 2657 if (!task) 2658 task = list_first_entry(&cset->mg_tasks, 2659 struct task_struct, cg_list); 2660 else 2661 task = list_next_entry(task, cg_list); 2662 2663 if (&task->cg_list != &cset->mg_tasks) { 2664 tset->cur_cset = cset; 2665 tset->cur_task = task; 2666 2667 /* 2668 * This function may be called both before and 2669 * after cgroup_migrate_execute(). The two cases 2670 * can be distinguished by looking at whether @cset 2671 * has its ->mg_dst_cset set. 2672 */ 2673 if (cset->mg_dst_cset) 2674 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid]; 2675 else 2676 *dst_cssp = cset->subsys[tset->ssid]; 2677 2678 return task; 2679 } 2680 2681 cset = list_next_entry(cset, mg_node); 2682 task = NULL; 2683 } 2684 2685 return NULL; 2686 } 2687 2688 static void cgroup_migrate_notify_canceled(struct css_set *src_cset, 2689 struct task_struct *task) 2690 { 2691 struct cgroup_task_migrate_ctx ctx = { 2692 .task = task, 2693 .src_dcgrp = src_cset->dfl_cgrp, 2694 .dst_dcgrp = src_cset->mg_dst_cset->dfl_cgrp, 2695 }; 2696 2697 blocking_notifier_call_chain(&cgroup_task_notifier, 2698 CGROUP_TASK_MIGRATE_CANCELED, &ctx); 2699 } 2700 2701 /** 2702 * cgroup_migrate_execute - migrate a taskset 2703 * @mgctx: migration context 2704 * 2705 * Migrate tasks in @mgctx as setup by migration preparation functions. This 2706 * function fails iff one of the ->can_attach callbacks or CGROUP_TASK_MIGRATING 2707 * notifications fails and guarantees that either all or none of the tasks in 2708 * @mgctx are migrated. @mgctx is consumed regardless of success. 2709 */ 2710 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx) 2711 { 2712 struct cgroup_taskset *tset = &mgctx->tset; 2713 struct cgroup_subsys *ss; 2714 struct task_struct *task, *tmp_task; 2715 struct css_set *cset, *tmp_cset; 2716 bool dfl_migration = false; 2717 int ssid, failed_ssid, ret; 2718 2719 /* check that we can legitimately attach to the cgroup */ 2720 if (tset->nr_tasks) { 2721 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) { 2722 if (ss->can_attach) { 2723 tset->ssid = ssid; 2724 ret = ss->can_attach(tset); 2725 if (ret) { 2726 failed_ssid = ssid; 2727 goto out_cancel_attach; 2728 } 2729 } 2730 } while_each_subsys_mask(); 2731 } 2732 2733 /* 2734 * Notify each task about the impending migration. An error return fails 2735 * the migration. Only migrations on the default hierarchy are reported: 2736 * a migration modifies either every moved task's dfl cgroup or, on 2737 * cgroup1 or for subtree_control writes, none. 2738 */ 2739 list_for_each_entry(cset, &tset->src_csets, mg_node) { 2740 if (cset->dfl_cgrp == cset->mg_dst_cset->dfl_cgrp) 2741 continue; 2742 dfl_migration = true; 2743 list_for_each_entry(task, &cset->mg_tasks, cg_list) { 2744 struct cgroup_task_migrate_ctx ctx = { 2745 .task = task, 2746 .src_dcgrp = cset->dfl_cgrp, 2747 .dst_dcgrp = cset->mg_dst_cset->dfl_cgrp, 2748 }; 2749 2750 ret = blocking_notifier_call_chain_robust(&cgroup_task_notifier, 2751 CGROUP_TASK_MIGRATING, 2752 CGROUP_TASK_MIGRATE_CANCELED, 2753 &ctx); 2754 ret = notifier_to_errno(ret); 2755 if (ret) 2756 goto out_cancel_migrating; 2757 } 2758 } 2759 2760 /* 2761 * Now that we're guaranteed success, proceed to move all tasks to 2762 * the new cgroup. There are no failure cases after here, so this 2763 * is the commit point. 2764 */ 2765 spin_lock_irq(&css_set_lock); 2766 list_for_each_entry(cset, &tset->src_csets, mg_node) { 2767 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) { 2768 struct css_set *from_cset = task_css_set(task); 2769 struct css_set *to_cset = cset->mg_dst_cset; 2770 2771 get_css_set(to_cset); 2772 to_cset->nr_tasks++; 2773 css_set_move_task(task, from_cset, to_cset, true); 2774 from_cset->nr_tasks--; 2775 /* 2776 * If the source or destination cgroup is frozen, 2777 * the task might require to change its state. 2778 */ 2779 cgroup_freezer_migrate_task(task, from_cset->dfl_cgrp, 2780 to_cset->dfl_cgrp); 2781 put_css_set_locked(from_cset); 2782 2783 } 2784 } 2785 spin_unlock_irq(&css_set_lock); 2786 2787 /* 2788 * Migration is committed, all target tasks are now on dst_csets. 2789 * Nothing is sensitive to fork() after this point. Notify 2790 * controllers that migration is complete. 2791 */ 2792 tset->csets = &tset->dst_csets; 2793 2794 if (tset->nr_tasks) { 2795 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) { 2796 if (ss->attach) { 2797 tset->ssid = ssid; 2798 ss->attach(tset); 2799 } 2800 } while_each_subsys_mask(); 2801 } 2802 2803 /* 2804 * Notify each task after successful migration. The operation can no 2805 * longer fail and the return value is ignored. The MIGRATING loop 2806 * above explains why only dfl migrations are reported. Per-task 2807 * sources are not tracked past the commit point, so src_dcgrp is 2808 * NULL. 2809 */ 2810 if (dfl_migration) { 2811 list_for_each_entry(cset, &tset->dst_csets, mg_node) { 2812 list_for_each_entry(task, &cset->mg_tasks, cg_list) { 2813 struct cgroup_task_migrate_ctx ctx = { 2814 .task = task, 2815 .dst_dcgrp = cset->dfl_cgrp, 2816 }; 2817 2818 blocking_notifier_call_chain( 2819 &cgroup_task_notifier, 2820 CGROUP_TASK_MIGRATED, &ctx); 2821 } 2822 } 2823 } 2824 2825 ret = 0; 2826 goto out_release_tset; 2827 2828 out_cancel_migrating: 2829 list_for_each_entry_continue_reverse(task, &cset->mg_tasks, cg_list) 2830 cgroup_migrate_notify_canceled(cset, task); 2831 list_for_each_entry_continue_reverse(cset, &tset->src_csets, mg_node) { 2832 if (cset->dfl_cgrp == cset->mg_dst_cset->dfl_cgrp) 2833 continue; 2834 list_for_each_entry_reverse(task, &cset->mg_tasks, cg_list) 2835 cgroup_migrate_notify_canceled(cset, task); 2836 } 2837 failed_ssid = CGROUP_SUBSYS_COUNT; 2838 out_cancel_attach: 2839 if (tset->nr_tasks) { 2840 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) { 2841 if (ssid == failed_ssid) 2842 break; 2843 if (ss->cancel_attach) { 2844 tset->ssid = ssid; 2845 ss->cancel_attach(tset); 2846 } 2847 } while_each_subsys_mask(); 2848 } 2849 out_release_tset: 2850 spin_lock_irq(&css_set_lock); 2851 list_splice_init(&tset->dst_csets, &tset->src_csets); 2852 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) { 2853 list_splice_tail_init(&cset->mg_tasks, &cset->tasks); 2854 list_del_init(&cset->mg_node); 2855 } 2856 spin_unlock_irq(&css_set_lock); 2857 2858 /* 2859 * Re-initialize the cgroup_taskset structure in case it is reused 2860 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute() 2861 * iteration. 2862 */ 2863 tset->nr_tasks = 0; 2864 tset->csets = &tset->src_csets; 2865 return ret; 2866 } 2867 2868 /** 2869 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination 2870 * @dst_cgrp: destination cgroup to test 2871 * 2872 * On the default hierarchy, except for the mixable, (possible) thread root 2873 * and threaded cgroups, subtree_control must be zero for migration 2874 * destination cgroups with tasks so that child cgroups don't compete 2875 * against tasks. 2876 */ 2877 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp) 2878 { 2879 /* v1 doesn't have any restriction */ 2880 if (!cgroup_on_dfl(dst_cgrp)) 2881 return 0; 2882 2883 /* verify @dst_cgrp can host resources */ 2884 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp)) 2885 return -EOPNOTSUPP; 2886 2887 /* 2888 * If @dst_cgrp is already or can become a thread root or is 2889 * threaded, it doesn't matter. 2890 */ 2891 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp)) 2892 return 0; 2893 2894 /* apply no-internal-process constraint */ 2895 if (dst_cgrp->subtree_control) 2896 return -EBUSY; 2897 2898 return 0; 2899 } 2900 2901 /** 2902 * cgroup_migrate_finish - cleanup after attach 2903 * @mgctx: migration context 2904 * 2905 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See 2906 * those functions for details. 2907 */ 2908 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx) 2909 { 2910 struct css_set *cset, *tmp_cset; 2911 2912 lockdep_assert_held(&cgroup_mutex); 2913 2914 spin_lock_irq(&css_set_lock); 2915 2916 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_src_csets, 2917 mg_src_preload_node) { 2918 cset->mg_src_cgrp = NULL; 2919 cset->mg_dst_cgrp = NULL; 2920 cset->mg_dst_cset = NULL; 2921 list_del_init(&cset->mg_src_preload_node); 2922 put_css_set_locked(cset); 2923 } 2924 2925 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_dst_csets, 2926 mg_dst_preload_node) { 2927 cset->mg_src_cgrp = NULL; 2928 cset->mg_dst_cgrp = NULL; 2929 cset->mg_dst_cset = NULL; 2930 list_del_init(&cset->mg_dst_preload_node); 2931 put_css_set_locked(cset); 2932 } 2933 2934 spin_unlock_irq(&css_set_lock); 2935 } 2936 2937 /** 2938 * cgroup_migrate_add_src - add a migration source css_set 2939 * @src_cset: the source css_set to add 2940 * @dst_cgrp: the destination cgroup 2941 * @mgctx: migration context 2942 * 2943 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin 2944 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned 2945 * up by cgroup_migrate_finish(). 2946 * 2947 * This function may be called without holding cgroup_threadgroup_rwsem 2948 * even if the target is a process. Threads may be created and destroyed 2949 * but as long as cgroup_mutex is not dropped, no new css_set can be put 2950 * into play and the preloaded css_sets are guaranteed to cover all 2951 * migrations. 2952 */ 2953 void cgroup_migrate_add_src(struct css_set *src_cset, 2954 struct cgroup *dst_cgrp, 2955 struct cgroup_mgctx *mgctx) 2956 { 2957 struct cgroup *src_cgrp; 2958 2959 lockdep_assert_held(&cgroup_mutex); 2960 lockdep_assert_held(&css_set_lock); 2961 2962 /* 2963 * If ->dead, @src_set is associated with one or more dead cgroups 2964 * and doesn't contain any migratable tasks. Ignore it early so 2965 * that the rest of migration path doesn't get confused by it. 2966 */ 2967 if (src_cset->dead) 2968 return; 2969 2970 if (!list_empty(&src_cset->mg_src_preload_node)) 2971 return; 2972 2973 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root); 2974 2975 WARN_ON(src_cset->mg_src_cgrp); 2976 WARN_ON(src_cset->mg_dst_cgrp); 2977 WARN_ON(!list_empty(&src_cset->mg_tasks)); 2978 WARN_ON(!list_empty(&src_cset->mg_node)); 2979 2980 src_cset->mg_src_cgrp = src_cgrp; 2981 src_cset->mg_dst_cgrp = dst_cgrp; 2982 get_css_set(src_cset); 2983 list_add_tail(&src_cset->mg_src_preload_node, &mgctx->preloaded_src_csets); 2984 } 2985 2986 /** 2987 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration 2988 * @mgctx: migration context 2989 * 2990 * Tasks are about to be moved and all the source css_sets have been 2991 * preloaded to @mgctx->preloaded_src_csets. This function looks up and 2992 * pins all destination css_sets, links each to its source, and append them 2993 * to @mgctx->preloaded_dst_csets. 2994 * 2995 * This function must be called after cgroup_migrate_add_src() has been 2996 * called on each migration source css_set. After migration is performed 2997 * using cgroup_migrate(), cgroup_migrate_finish() must be called on 2998 * @mgctx. 2999 */ 3000 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx) 3001 { 3002 struct css_set *src_cset, *tmp_cset; 3003 3004 lockdep_assert_held(&cgroup_mutex); 3005 3006 /* look up the dst cset for each src cset and link it to src */ 3007 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets, 3008 mg_src_preload_node) { 3009 struct css_set *dst_cset; 3010 struct cgroup_subsys *ss; 3011 int ssid; 3012 3013 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp); 3014 if (!dst_cset) 3015 return -ENOMEM; 3016 3017 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset); 3018 3019 /* 3020 * If src cset equals dst, it's noop. Drop the src. 3021 * cgroup_migrate() will skip the cset too. Note that we 3022 * can't handle src == dst as some nodes are used by both. 3023 */ 3024 if (src_cset == dst_cset) { 3025 src_cset->mg_src_cgrp = NULL; 3026 src_cset->mg_dst_cgrp = NULL; 3027 list_del_init(&src_cset->mg_src_preload_node); 3028 put_css_set(src_cset); 3029 put_css_set(dst_cset); 3030 continue; 3031 } 3032 3033 src_cset->mg_dst_cset = dst_cset; 3034 3035 if (list_empty(&dst_cset->mg_dst_preload_node)) 3036 list_add_tail(&dst_cset->mg_dst_preload_node, 3037 &mgctx->preloaded_dst_csets); 3038 else 3039 put_css_set(dst_cset); 3040 3041 for_each_subsys(ss, ssid) 3042 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid]) 3043 mgctx->ss_mask |= 1 << ssid; 3044 } 3045 3046 return 0; 3047 } 3048 3049 /** 3050 * cgroup_migrate - migrate a process or task to a cgroup 3051 * @leader: the leader of the process or the task to migrate 3052 * @threadgroup: whether @leader points to the whole process or a single task 3053 * @mgctx: migration context 3054 * 3055 * Migrate a process or task denoted by @leader. If migrating a process, 3056 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also 3057 * responsible for invoking cgroup_migrate_add_src() and 3058 * cgroup_migrate_prepare_dst() on the targets before invoking this 3059 * function and following up with cgroup_migrate_finish(). 3060 * 3061 * As long as a controller's ->can_attach() or a CGROUP_TASK_MIGRATING 3062 * notification doesn't fail, this function is guaranteed to succeed. This 3063 * means that, excluding those failures, when migrating multiple targets, 3064 * the success or failure can be decided for all targets by invoking 3065 * group_migrate_prepare_dst() before actually starting migrating. 3066 */ 3067 int cgroup_migrate(struct task_struct *leader, bool threadgroup, 3068 struct cgroup_mgctx *mgctx) 3069 { 3070 struct task_struct *task; 3071 3072 /* 3073 * The following thread iteration should be inside an RCU critical 3074 * section to prevent tasks from being freed while taking the snapshot. 3075 * spin_lock_irq() implies RCU critical section here. 3076 */ 3077 spin_lock_irq(&css_set_lock); 3078 task = leader; 3079 do { 3080 cgroup_migrate_add_task(task, mgctx); 3081 if (!threadgroup) 3082 break; 3083 } while_each_thread(leader, task); 3084 spin_unlock_irq(&css_set_lock); 3085 3086 return cgroup_migrate_execute(mgctx); 3087 } 3088 3089 /** 3090 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup 3091 * @dst_cgrp: the cgroup to attach to 3092 * @leader: the task or the leader of the threadgroup to be attached 3093 * @threadgroup: attach the whole threadgroup? 3094 * 3095 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem. 3096 */ 3097 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader, 3098 bool threadgroup) 3099 { 3100 DEFINE_CGROUP_MGCTX(mgctx); 3101 struct task_struct *task; 3102 int ret = 0; 3103 3104 /* look up all src csets */ 3105 spin_lock_irq(&css_set_lock); 3106 task = leader; 3107 do { 3108 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx); 3109 if (!threadgroup) 3110 break; 3111 } while_each_thread(leader, task); 3112 spin_unlock_irq(&css_set_lock); 3113 3114 /* prepare dst csets and commit */ 3115 ret = cgroup_migrate_prepare_dst(&mgctx); 3116 if (!ret) 3117 ret = cgroup_migrate(leader, threadgroup, &mgctx); 3118 3119 cgroup_migrate_finish(&mgctx); 3120 3121 if (!ret) 3122 TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup); 3123 3124 return ret; 3125 } 3126 3127 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup, 3128 enum cgroup_attach_lock_mode *lock_mode) 3129 { 3130 struct task_struct *tsk; 3131 pid_t pid; 3132 3133 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0) 3134 return ERR_PTR(-EINVAL); 3135 3136 retry_find_task: 3137 rcu_read_lock(); 3138 if (pid) { 3139 tsk = find_task_by_vpid(pid); 3140 if (!tsk) { 3141 tsk = ERR_PTR(-ESRCH); 3142 goto out_unlock_rcu; 3143 } 3144 } else { 3145 tsk = current; 3146 } 3147 3148 if (threadgroup) 3149 tsk = tsk->group_leader; 3150 3151 /* 3152 * kthreads may acquire PF_NO_SETAFFINITY during initialization. 3153 * If userland migrates such a kthread to a non-root cgroup, it can 3154 * become trapped in a cpuset, or RT kthread may be born in a 3155 * cgroup with no rt_runtime allocated. Just say no. 3156 */ 3157 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) { 3158 tsk = ERR_PTR(-EINVAL); 3159 goto out_unlock_rcu; 3160 } 3161 get_task_struct(tsk); 3162 rcu_read_unlock(); 3163 3164 /* 3165 * If we migrate a single thread, we don't care about threadgroup 3166 * stability. If the thread is `current`, it won't exit(2) under our 3167 * hands or change PID through exec(2). We exclude 3168 * cgroup_update_dfl_csses and other cgroup_{proc,thread}s_write callers 3169 * by cgroup_mutex. Therefore, we can skip the global lock. 3170 */ 3171 lockdep_assert_held(&cgroup_mutex); 3172 3173 if (pid || threadgroup) { 3174 if (cgroup_enable_per_threadgroup_rwsem) 3175 *lock_mode = CGRP_ATTACH_LOCK_PER_THREADGROUP; 3176 else 3177 *lock_mode = CGRP_ATTACH_LOCK_GLOBAL; 3178 } else { 3179 *lock_mode = CGRP_ATTACH_LOCK_NONE; 3180 } 3181 3182 cgroup_attach_lock(*lock_mode, tsk); 3183 3184 if (threadgroup) { 3185 if (!thread_group_leader(tsk)) { 3186 /* 3187 * A race with de_thread from another thread's exec() 3188 * may strip us of our leadership. If this happens, 3189 * throw this task away and try again. 3190 */ 3191 cgroup_attach_unlock(*lock_mode, tsk); 3192 put_task_struct(tsk); 3193 goto retry_find_task; 3194 } 3195 } 3196 3197 return tsk; 3198 3199 out_unlock_rcu: 3200 rcu_read_unlock(); 3201 return tsk; 3202 } 3203 3204 void cgroup_procs_write_finish(struct task_struct *task, 3205 enum cgroup_attach_lock_mode lock_mode) 3206 { 3207 cgroup_attach_unlock(lock_mode, task); 3208 3209 /* release reference from cgroup_procs_write_start() */ 3210 put_task_struct(task); 3211 } 3212 3213 static void cgroup_print_ss_mask(struct seq_file *seq, u32 ss_mask) 3214 { 3215 struct cgroup_subsys *ss; 3216 bool printed = false; 3217 int ssid; 3218 3219 do_each_subsys_mask(ss, ssid, ss_mask) { 3220 if (printed) 3221 seq_putc(seq, ' '); 3222 seq_puts(seq, ss->name); 3223 printed = true; 3224 } while_each_subsys_mask(); 3225 if (printed) 3226 seq_putc(seq, '\n'); 3227 } 3228 3229 /* show controllers which are enabled from the parent */ 3230 static int cgroup_controllers_show(struct seq_file *seq, void *v) 3231 { 3232 struct cgroup *cgrp = seq_css(seq)->cgroup; 3233 3234 cgroup_print_ss_mask(seq, cgroup_control(cgrp)); 3235 return 0; 3236 } 3237 3238 /* show controllers which are enabled for a given cgroup's children */ 3239 static int cgroup_subtree_control_show(struct seq_file *seq, void *v) 3240 { 3241 struct cgroup *cgrp = seq_css(seq)->cgroup; 3242 3243 cgroup_print_ss_mask(seq, cgrp->subtree_control); 3244 return 0; 3245 } 3246 3247 /** 3248 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy 3249 * @cgrp: root of the subtree to update csses for 3250 * 3251 * @cgrp's control masks have changed and its subtree's css associations 3252 * need to be updated accordingly. This function looks up all css_sets 3253 * which are attached to the subtree, creates the matching updated css_sets 3254 * and migrates the tasks to the new ones. 3255 */ 3256 static int cgroup_update_dfl_csses(struct cgroup *cgrp) 3257 { 3258 DEFINE_CGROUP_MGCTX(mgctx); 3259 struct cgroup_subsys_state *d_css; 3260 struct cgroup *dsct; 3261 struct css_set *src_cset; 3262 enum cgroup_attach_lock_mode lock_mode; 3263 bool has_tasks; 3264 int ret; 3265 3266 lockdep_assert_held(&cgroup_mutex); 3267 3268 /* look up all csses currently attached to @cgrp's subtree */ 3269 spin_lock_irq(&css_set_lock); 3270 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) { 3271 struct cgrp_cset_link *link; 3272 3273 /* 3274 * As cgroup_update_dfl_csses() is only called by 3275 * cgroup_apply_control(). The csses associated with the 3276 * given cgrp will not be affected by changes made to 3277 * its subtree_control file. We can skip them. 3278 */ 3279 if (dsct == cgrp) 3280 continue; 3281 3282 list_for_each_entry(link, &dsct->cset_links, cset_link) 3283 cgroup_migrate_add_src(link->cset, dsct, &mgctx); 3284 } 3285 spin_unlock_irq(&css_set_lock); 3286 3287 /* 3288 * We need to write-lock threadgroup_rwsem while migrating tasks. 3289 * However, if there are no source csets for @cgrp, changing its 3290 * controllers isn't gonna produce any task migrations and the 3291 * write-locking can be skipped safely. 3292 */ 3293 has_tasks = !list_empty(&mgctx.preloaded_src_csets); 3294 3295 if (has_tasks) 3296 lock_mode = CGRP_ATTACH_LOCK_GLOBAL; 3297 else 3298 lock_mode = CGRP_ATTACH_LOCK_NONE; 3299 3300 cgroup_attach_lock(lock_mode, NULL); 3301 3302 /* NULL dst indicates self on default hierarchy */ 3303 ret = cgroup_migrate_prepare_dst(&mgctx); 3304 if (ret) 3305 goto out_finish; 3306 3307 spin_lock_irq(&css_set_lock); 3308 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets, 3309 mg_src_preload_node) { 3310 struct task_struct *task, *ntask; 3311 3312 /* all tasks in src_csets need to be migrated */ 3313 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list) 3314 cgroup_migrate_add_task(task, &mgctx); 3315 } 3316 spin_unlock_irq(&css_set_lock); 3317 3318 ret = cgroup_migrate_execute(&mgctx); 3319 out_finish: 3320 cgroup_migrate_finish(&mgctx); 3321 cgroup_attach_unlock(lock_mode, NULL); 3322 return ret; 3323 } 3324 3325 /** 3326 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses 3327 * @cgrp: root of the target subtree 3328 * 3329 * Because css offlining is asynchronous, userland may try to re-enable a 3330 * controller while the previous css is still around. This function grabs 3331 * cgroup_mutex and waits until no css in @cgrp's subtree is dying. A dying css 3332 * offlines only after every task that still pins it has finished exiting, which 3333 * can take arbitrarily long, so the wait is interruptible. 3334 * 3335 * Returns 0 with cgroup_mutex held once the subtree is drained, or -ERESTARTSYS 3336 * without it if interrupted by a signal. 3337 */ 3338 int cgroup_lock_and_drain_offline(struct cgroup *cgrp) 3339 { 3340 struct cgroup *dsct; 3341 struct cgroup_subsys_state *d_css; 3342 struct cgroup_subsys *ss; 3343 int ssid, ret; 3344 3345 restart: 3346 cgroup_lock(); 3347 3348 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) { 3349 for_each_subsys(ss, ssid) { 3350 struct cgroup_subsys_state *css = cgroup_css(dsct, ss); 3351 DEFINE_WAIT(wait); 3352 3353 if (!css || !css_is_dying(css)) 3354 continue; 3355 3356 cgroup_get_live(dsct); 3357 ret = prepare_to_wait_event(&dsct->offline_waitq, &wait, 3358 TASK_INTERRUPTIBLE); 3359 cgroup_unlock(); 3360 if (!ret) 3361 schedule(); 3362 finish_wait(&dsct->offline_waitq, &wait); 3363 cgroup_put(dsct); 3364 if (unlikely(ret)) 3365 return ret; 3366 goto restart; 3367 } 3368 } 3369 3370 return 0; 3371 } 3372 3373 /** 3374 * cgroup_save_control - save control masks and dom_cgrp of a subtree 3375 * @cgrp: root of the target subtree 3376 * 3377 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the 3378 * respective old_ prefixed fields for @cgrp's subtree including @cgrp 3379 * itself. 3380 */ 3381 static void cgroup_save_control(struct cgroup *cgrp) 3382 { 3383 struct cgroup *dsct; 3384 struct cgroup_subsys_state *d_css; 3385 3386 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) { 3387 dsct->old_subtree_control = dsct->subtree_control; 3388 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask; 3389 dsct->old_dom_cgrp = dsct->dom_cgrp; 3390 } 3391 } 3392 3393 /** 3394 * cgroup_propagate_control - refresh control masks of a subtree 3395 * @cgrp: root of the target subtree 3396 * 3397 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches 3398 * ->subtree_control and propagate controller availability through the 3399 * subtree so that descendants don't have unavailable controllers enabled. 3400 */ 3401 static void cgroup_propagate_control(struct cgroup *cgrp) 3402 { 3403 struct cgroup *dsct; 3404 struct cgroup_subsys_state *d_css; 3405 3406 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) { 3407 dsct->subtree_control &= cgroup_control(dsct); 3408 dsct->subtree_ss_mask = 3409 cgroup_calc_subtree_ss_mask(dsct->subtree_control, 3410 cgroup_ss_mask(dsct)); 3411 } 3412 } 3413 3414 /** 3415 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree 3416 * @cgrp: root of the target subtree 3417 * 3418 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the 3419 * respective old_ prefixed fields for @cgrp's subtree including @cgrp 3420 * itself. 3421 */ 3422 static void cgroup_restore_control(struct cgroup *cgrp) 3423 { 3424 struct cgroup *dsct; 3425 struct cgroup_subsys_state *d_css; 3426 3427 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) { 3428 dsct->subtree_control = dsct->old_subtree_control; 3429 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask; 3430 dsct->dom_cgrp = dsct->old_dom_cgrp; 3431 } 3432 } 3433 3434 static bool css_visible(struct cgroup_subsys_state *css) 3435 { 3436 struct cgroup_subsys *ss = css->ss; 3437 struct cgroup *cgrp = css->cgroup; 3438 3439 if (cgroup_control(cgrp) & (1 << ss->id)) 3440 return true; 3441 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) 3442 return false; 3443 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl; 3444 } 3445 3446 /** 3447 * cgroup_apply_control_enable - enable or show csses according to control 3448 * @cgrp: root of the target subtree 3449 * 3450 * Walk @cgrp's subtree and create new csses or make the existing ones 3451 * visible. A css is created invisible if it's being implicitly enabled 3452 * through dependency. An invisible css is made visible when the userland 3453 * explicitly enables it. 3454 * 3455 * Returns 0 on success, -errno on failure. On failure, csses which have 3456 * been processed already aren't cleaned up. The caller is responsible for 3457 * cleaning up with cgroup_apply_control_disable(). 3458 */ 3459 static int cgroup_apply_control_enable(struct cgroup *cgrp) 3460 { 3461 struct cgroup *dsct; 3462 struct cgroup_subsys_state *d_css; 3463 struct cgroup_subsys *ss; 3464 int ssid, ret; 3465 3466 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) { 3467 for_each_subsys(ss, ssid) { 3468 struct cgroup_subsys_state *css = cgroup_css(dsct, ss); 3469 3470 if (!(cgroup_ss_mask(dsct) & (1 << ss->id))) 3471 continue; 3472 3473 if (!css) { 3474 css = css_create(dsct, ss); 3475 if (IS_ERR(css)) 3476 return PTR_ERR(css); 3477 } 3478 3479 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt)); 3480 3481 if (css_visible(css)) { 3482 ret = css_populate_dir(css); 3483 if (ret) 3484 return ret; 3485 } 3486 } 3487 } 3488 3489 return 0; 3490 } 3491 3492 /** 3493 * cgroup_apply_control_disable - kill or hide csses according to control 3494 * @cgrp: root of the target subtree 3495 * 3496 * Walk @cgrp's subtree and kill and hide csses so that they match 3497 * cgroup_ss_mask() and cgroup_visible_mask(). 3498 * 3499 * A css is hidden when the userland requests it to be disabled while other 3500 * subsystems are still depending on it. The css must not actively control 3501 * resources and be in the vanilla state if it's made visible again later. 3502 * Controllers which may be depended upon should provide ->css_reset() for 3503 * this purpose. 3504 */ 3505 static void cgroup_apply_control_disable(struct cgroup *cgrp) 3506 { 3507 struct cgroup *dsct; 3508 struct cgroup_subsys_state *d_css; 3509 struct cgroup_subsys *ss; 3510 int ssid; 3511 3512 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) { 3513 for_each_subsys(ss, ssid) { 3514 struct cgroup_subsys_state *css = cgroup_css(dsct, ss); 3515 3516 if (!css) 3517 continue; 3518 3519 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt)); 3520 3521 if (css->parent && 3522 !(cgroup_ss_mask(dsct) & (1 << ss->id))) { 3523 kill_css_sync(css); 3524 if (!css_is_populated(css)) 3525 kill_css_finish(css); 3526 } else if (!css_visible(css)) { 3527 css_clear_dir(css); 3528 if (ss->css_reset) 3529 ss->css_reset(css); 3530 } 3531 } 3532 } 3533 } 3534 3535 /** 3536 * cgroup_apply_control - apply control mask updates to the subtree 3537 * @cgrp: root of the target subtree 3538 * 3539 * subsystems can be enabled and disabled in a subtree using the following 3540 * steps. 3541 * 3542 * 1. Call cgroup_save_control() to stash the current state. 3543 * 2. Update ->subtree_control masks in the subtree as desired. 3544 * 3. Call cgroup_apply_control() to apply the changes. 3545 * 4. Optionally perform other related operations. 3546 * 5. Call cgroup_finalize_control() to finish up. 3547 * 3548 * This function implements step 3 and propagates the mask changes 3549 * throughout @cgrp's subtree, updates csses accordingly and perform 3550 * process migrations. 3551 */ 3552 static int cgroup_apply_control(struct cgroup *cgrp) 3553 { 3554 int ret; 3555 3556 cgroup_propagate_control(cgrp); 3557 3558 ret = cgroup_apply_control_enable(cgrp); 3559 if (ret) 3560 return ret; 3561 3562 /* 3563 * At this point, cgroup_e_css_by_mask() results reflect the new csses 3564 * making the following cgroup_update_dfl_csses() properly update 3565 * css associations of all tasks in the subtree. 3566 */ 3567 return cgroup_update_dfl_csses(cgrp); 3568 } 3569 3570 /** 3571 * cgroup_finalize_control - finalize control mask update 3572 * @cgrp: root of the target subtree 3573 * @ret: the result of the update 3574 * 3575 * Finalize control mask update. See cgroup_apply_control() for more info. 3576 */ 3577 static void cgroup_finalize_control(struct cgroup *cgrp, int ret) 3578 { 3579 if (ret) { 3580 cgroup_restore_control(cgrp); 3581 cgroup_propagate_control(cgrp); 3582 } 3583 3584 cgroup_apply_control_disable(cgrp); 3585 } 3586 3587 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u32 enable) 3588 { 3589 u32 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask; 3590 3591 /* if nothing is getting enabled, nothing to worry about */ 3592 if (!enable) 3593 return 0; 3594 3595 /* can @cgrp host any resources? */ 3596 if (!cgroup_is_valid_domain(cgrp->dom_cgrp)) 3597 return -EOPNOTSUPP; 3598 3599 /* mixables don't care */ 3600 if (cgroup_is_mixable(cgrp)) 3601 return 0; 3602 3603 if (domain_enable) { 3604 /* can't enable domain controllers inside a thread subtree */ 3605 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp)) 3606 return -EOPNOTSUPP; 3607 } else { 3608 /* 3609 * Threaded controllers can handle internal competitions 3610 * and are always allowed inside a (prospective) thread 3611 * subtree. 3612 */ 3613 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp)) 3614 return 0; 3615 } 3616 3617 /* 3618 * Controllers can't be enabled for a cgroup with tasks to avoid 3619 * child cgroups competing against tasks. 3620 */ 3621 if (cgroup_has_tasks(cgrp)) 3622 return -EBUSY; 3623 3624 return 0; 3625 } 3626 3627 /* change the enabled child controllers for a cgroup in the default hierarchy */ 3628 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of, 3629 char *buf, size_t nbytes, 3630 loff_t off) 3631 { 3632 u32 enable = 0, disable = 0; 3633 struct cgroup *cgrp, *child; 3634 struct cgroup_subsys *ss; 3635 char *tok; 3636 int ssid, ret; 3637 3638 /* 3639 * Parse input - space separated list of subsystem names prefixed 3640 * with either + or -. 3641 */ 3642 buf = strstrip(buf); 3643 while ((tok = strsep(&buf, " "))) { 3644 if (tok[0] == '\0') 3645 continue; 3646 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) { 3647 if (!cgroup_ssid_enabled(ssid) || 3648 strcmp(tok + 1, ss->name)) 3649 continue; 3650 3651 if (*tok == '+') { 3652 enable |= 1 << ssid; 3653 disable &= ~(1 << ssid); 3654 } else if (*tok == '-') { 3655 disable |= 1 << ssid; 3656 enable &= ~(1 << ssid); 3657 } else { 3658 return -EINVAL; 3659 } 3660 break; 3661 } while_each_subsys_mask(); 3662 if (ssid == CGROUP_SUBSYS_COUNT) 3663 return -EINVAL; 3664 } 3665 3666 cgrp = cgroup_kn_lock_live(of->kn, true); 3667 if (IS_ERR(cgrp)) 3668 return PTR_ERR(cgrp); 3669 3670 for_each_subsys(ss, ssid) { 3671 if (enable & (1 << ssid)) { 3672 if (cgrp->subtree_control & (1 << ssid)) { 3673 enable &= ~(1 << ssid); 3674 continue; 3675 } 3676 3677 if (!(cgroup_control(cgrp) & (1 << ssid))) { 3678 ret = -ENOENT; 3679 goto out_unlock; 3680 } 3681 } else if (disable & (1 << ssid)) { 3682 if (!(cgrp->subtree_control & (1 << ssid))) { 3683 disable &= ~(1 << ssid); 3684 continue; 3685 } 3686 3687 /* a child has it enabled? */ 3688 cgroup_for_each_live_child(child, cgrp) { 3689 if (child->subtree_control & (1 << ssid)) { 3690 ret = -EBUSY; 3691 goto out_unlock; 3692 } 3693 } 3694 } 3695 } 3696 3697 if (!enable && !disable) { 3698 ret = 0; 3699 goto out_unlock; 3700 } 3701 3702 ret = cgroup_vet_subtree_control_enable(cgrp, enable); 3703 if (ret) 3704 goto out_unlock; 3705 3706 /* save and update control masks and prepare csses */ 3707 cgroup_save_control(cgrp); 3708 3709 cgrp->subtree_control |= enable; 3710 cgrp->subtree_control &= ~disable; 3711 3712 ret = cgroup_apply_control(cgrp); 3713 cgroup_finalize_control(cgrp, ret); 3714 if (ret) 3715 goto out_unlock; 3716 3717 kernfs_activate(cgrp->kn); 3718 out_unlock: 3719 cgroup_kn_unlock(of->kn); 3720 return ret ?: nbytes; 3721 } 3722 3723 /** 3724 * cgroup_enable_threaded - make @cgrp threaded 3725 * @cgrp: the target cgroup 3726 * 3727 * Called when "threaded" is written to the cgroup.type interface file and 3728 * tries to make @cgrp threaded and join the parent's resource domain. 3729 * This function is never called on the root cgroup as cgroup.type doesn't 3730 * exist on it. 3731 */ 3732 static int cgroup_enable_threaded(struct cgroup *cgrp) 3733 { 3734 struct cgroup *parent = cgroup_parent(cgrp); 3735 struct cgroup *dom_cgrp = parent->dom_cgrp; 3736 struct cgroup *dsct; 3737 struct cgroup_subsys_state *d_css; 3738 int ret; 3739 3740 lockdep_assert_held(&cgroup_mutex); 3741 3742 /* noop if already threaded */ 3743 if (cgroup_is_threaded(cgrp)) 3744 return 0; 3745 3746 /* 3747 * If @cgroup is populated or has domain controllers enabled, it 3748 * can't be switched. While the below cgroup_can_be_thread_root() 3749 * test can catch the same conditions, that's only when @parent is 3750 * not mixable, so let's check it explicitly. 3751 */ 3752 if (cgroup_is_populated(cgrp) || 3753 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask) 3754 return -EOPNOTSUPP; 3755 3756 /* we're joining the parent's domain, ensure its validity */ 3757 if (!cgroup_is_valid_domain(dom_cgrp) || 3758 !cgroup_can_be_thread_root(dom_cgrp)) 3759 return -EOPNOTSUPP; 3760 3761 /* 3762 * The following shouldn't cause actual migrations and should 3763 * always succeed. 3764 */ 3765 cgroup_save_control(cgrp); 3766 3767 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) 3768 if (dsct == cgrp || cgroup_is_threaded(dsct)) 3769 dsct->dom_cgrp = dom_cgrp; 3770 3771 ret = cgroup_apply_control(cgrp); 3772 if (!ret) 3773 parent->nr_threaded_children++; 3774 3775 cgroup_finalize_control(cgrp, ret); 3776 return ret; 3777 } 3778 3779 static int cgroup_type_show(struct seq_file *seq, void *v) 3780 { 3781 struct cgroup *cgrp = seq_css(seq)->cgroup; 3782 3783 if (cgroup_is_threaded(cgrp)) 3784 seq_puts(seq, "threaded\n"); 3785 else if (!cgroup_is_valid_domain(cgrp)) 3786 seq_puts(seq, "domain invalid\n"); 3787 else if (cgroup_is_thread_root(cgrp)) 3788 seq_puts(seq, "domain threaded\n"); 3789 else 3790 seq_puts(seq, "domain\n"); 3791 3792 return 0; 3793 } 3794 3795 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf, 3796 size_t nbytes, loff_t off) 3797 { 3798 struct cgroup *cgrp; 3799 int ret; 3800 3801 /* only switching to threaded mode is supported */ 3802 if (strcmp(strstrip(buf), "threaded")) 3803 return -EINVAL; 3804 3805 /* drain dying csses before we re-apply (threaded) subtree control */ 3806 cgrp = cgroup_kn_lock_live(of->kn, true); 3807 if (IS_ERR(cgrp)) 3808 return PTR_ERR(cgrp); 3809 3810 /* threaded can only be enabled */ 3811 ret = cgroup_enable_threaded(cgrp); 3812 3813 cgroup_kn_unlock(of->kn); 3814 return ret ?: nbytes; 3815 } 3816 3817 static int cgroup_max_descendants_show(struct seq_file *seq, void *v) 3818 { 3819 struct cgroup *cgrp = seq_css(seq)->cgroup; 3820 int descendants = READ_ONCE(cgrp->max_descendants); 3821 3822 if (descendants == INT_MAX) 3823 seq_puts(seq, "max\n"); 3824 else 3825 seq_printf(seq, "%d\n", descendants); 3826 3827 return 0; 3828 } 3829 3830 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of, 3831 char *buf, size_t nbytes, loff_t off) 3832 { 3833 struct cgroup *cgrp; 3834 int descendants; 3835 ssize_t ret; 3836 3837 buf = strstrip(buf); 3838 if (!strcmp(buf, "max")) { 3839 descendants = INT_MAX; 3840 } else { 3841 ret = kstrtoint(buf, 0, &descendants); 3842 if (ret) 3843 return ret; 3844 } 3845 3846 if (descendants < 0) 3847 return -ERANGE; 3848 3849 cgrp = cgroup_kn_lock_live(of->kn, false); 3850 if (IS_ERR(cgrp)) 3851 return PTR_ERR(cgrp); 3852 3853 WRITE_ONCE(cgrp->max_descendants, descendants); 3854 3855 cgroup_kn_unlock(of->kn); 3856 3857 return nbytes; 3858 } 3859 3860 static int cgroup_max_depth_show(struct seq_file *seq, void *v) 3861 { 3862 struct cgroup *cgrp = seq_css(seq)->cgroup; 3863 int depth = READ_ONCE(cgrp->max_depth); 3864 3865 if (depth == INT_MAX) 3866 seq_puts(seq, "max\n"); 3867 else 3868 seq_printf(seq, "%d\n", depth); 3869 3870 return 0; 3871 } 3872 3873 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of, 3874 char *buf, size_t nbytes, loff_t off) 3875 { 3876 struct cgroup *cgrp; 3877 ssize_t ret; 3878 int depth; 3879 3880 buf = strstrip(buf); 3881 if (!strcmp(buf, "max")) { 3882 depth = INT_MAX; 3883 } else { 3884 ret = kstrtoint(buf, 0, &depth); 3885 if (ret) 3886 return ret; 3887 } 3888 3889 if (depth < 0) 3890 return -ERANGE; 3891 3892 cgrp = cgroup_kn_lock_live(of->kn, false); 3893 if (IS_ERR(cgrp)) 3894 return PTR_ERR(cgrp); 3895 3896 WRITE_ONCE(cgrp->max_depth, depth); 3897 3898 cgroup_kn_unlock(of->kn); 3899 3900 return nbytes; 3901 } 3902 3903 static int cgroup_events_show(struct seq_file *seq, void *v) 3904 { 3905 struct cgroup *cgrp = seq_css(seq)->cgroup; 3906 3907 seq_printf(seq, "populated %d\n", cgroup_is_populated(cgrp)); 3908 seq_printf(seq, "frozen %d\n", test_bit(CGRP_FROZEN, &cgrp->flags)); 3909 3910 return 0; 3911 } 3912 3913 static int cgroup_stat_show(struct seq_file *seq, void *v) 3914 { 3915 struct cgroup *cgroup = seq_css(seq)->cgroup; 3916 struct cgroup_subsys_state *css; 3917 int dying_cnt[CGROUP_SUBSYS_COUNT]; 3918 int ssid; 3919 3920 seq_printf(seq, "nr_descendants %d\n", 3921 cgroup->nr_descendants); 3922 3923 /* 3924 * Show the number of live and dying csses associated with each of 3925 * non-inhibited cgroup subsystems that is bound to cgroup v2. 3926 * 3927 * Without proper lock protection, racing is possible. So the 3928 * numbers may not be consistent when that happens. 3929 */ 3930 rcu_read_lock(); 3931 for (ssid = 0; ssid < CGROUP_SUBSYS_COUNT; ssid++) { 3932 dying_cnt[ssid] = -1; 3933 if ((BIT(ssid) & cgrp_dfl_inhibit_ss_mask) || 3934 (cgroup_subsys[ssid]->root != &cgrp_dfl_root)) 3935 continue; 3936 css = rcu_dereference_raw(cgroup->subsys[ssid]); 3937 dying_cnt[ssid] = cgroup->nr_dying_subsys[ssid]; 3938 seq_printf(seq, "nr_subsys_%s %d\n", cgroup_subsys[ssid]->name, 3939 css ? (css->nr_descendants + 1) : 0); 3940 } 3941 3942 seq_printf(seq, "nr_dying_descendants %d\n", 3943 cgroup->nr_dying_descendants); 3944 for (ssid = 0; ssid < CGROUP_SUBSYS_COUNT; ssid++) { 3945 if (dying_cnt[ssid] >= 0) 3946 seq_printf(seq, "nr_dying_subsys_%s %d\n", 3947 cgroup_subsys[ssid]->name, dying_cnt[ssid]); 3948 } 3949 rcu_read_unlock(); 3950 return 0; 3951 } 3952 3953 static int cgroup_core_local_stat_show(struct seq_file *seq, void *v) 3954 { 3955 struct cgroup *cgrp = seq_css(seq)->cgroup; 3956 unsigned int sequence; 3957 u64 freeze_time; 3958 3959 do { 3960 sequence = read_seqcount_begin(&cgrp->freezer.freeze_seq); 3961 freeze_time = cgrp->freezer.frozen_nsec; 3962 /* Add in current freezer interval if the cgroup is freezing. */ 3963 if (test_bit(CGRP_FREEZE, &cgrp->flags)) 3964 freeze_time += (ktime_get_ns() - 3965 cgrp->freezer.freeze_start_nsec); 3966 } while (read_seqcount_retry(&cgrp->freezer.freeze_seq, sequence)); 3967 3968 do_div(freeze_time, NSEC_PER_USEC); 3969 seq_printf(seq, "frozen_usec %llu\n", freeze_time); 3970 3971 return 0; 3972 } 3973 3974 #ifdef CONFIG_CGROUP_SCHED 3975 /** 3976 * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem 3977 * @cgrp: the cgroup of interest 3978 * @ss: the subsystem of interest 3979 * 3980 * Find and get @cgrp's css associated with @ss. If the css doesn't exist 3981 * or is offline, %NULL is returned. 3982 */ 3983 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp, 3984 struct cgroup_subsys *ss) 3985 { 3986 struct cgroup_subsys_state *css; 3987 3988 rcu_read_lock(); 3989 css = cgroup_css(cgrp, ss); 3990 if (css && !css_tryget_online(css)) 3991 css = NULL; 3992 rcu_read_unlock(); 3993 3994 return css; 3995 } 3996 3997 static int cgroup_extra_stat_show(struct seq_file *seq, int ssid) 3998 { 3999 struct cgroup *cgrp = seq_css(seq)->cgroup; 4000 struct cgroup_subsys *ss = cgroup_subsys[ssid]; 4001 struct cgroup_subsys_state *css; 4002 int ret; 4003 4004 if (!ss->css_extra_stat_show) 4005 return 0; 4006 4007 css = cgroup_tryget_css(cgrp, ss); 4008 if (!css) 4009 return 0; 4010 4011 ret = ss->css_extra_stat_show(seq, css); 4012 css_put(css); 4013 return ret; 4014 } 4015 4016 static int cgroup_local_stat_show(struct seq_file *seq, 4017 struct cgroup *cgrp, int ssid) 4018 { 4019 struct cgroup_subsys *ss = cgroup_subsys[ssid]; 4020 struct cgroup_subsys_state *css; 4021 int ret; 4022 4023 if (!ss->css_local_stat_show) 4024 return 0; 4025 4026 css = cgroup_tryget_css(cgrp, ss); 4027 if (!css) 4028 return 0; 4029 4030 ret = ss->css_local_stat_show(seq, css); 4031 css_put(css); 4032 return ret; 4033 } 4034 #endif 4035 4036 static int cpu_stat_show(struct seq_file *seq, void *v) 4037 { 4038 int ret = 0; 4039 4040 cgroup_base_stat_cputime_show(seq); 4041 #ifdef CONFIG_CGROUP_SCHED 4042 ret = cgroup_extra_stat_show(seq, cpu_cgrp_id); 4043 #endif 4044 return ret; 4045 } 4046 4047 static int cpu_local_stat_show(struct seq_file *seq, void *v) 4048 { 4049 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup; 4050 int ret = 0; 4051 4052 #ifdef CONFIG_CGROUP_SCHED 4053 ret = cgroup_local_stat_show(seq, cgrp, cpu_cgrp_id); 4054 #endif 4055 return ret; 4056 } 4057 4058 #ifdef CONFIG_PSI 4059 static int cgroup_io_pressure_show(struct seq_file *seq, void *v) 4060 { 4061 struct cgroup *cgrp = seq_css(seq)->cgroup; 4062 struct psi_group *psi = cgroup_psi(cgrp); 4063 4064 return psi_show(seq, psi, PSI_IO); 4065 } 4066 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v) 4067 { 4068 struct cgroup *cgrp = seq_css(seq)->cgroup; 4069 struct psi_group *psi = cgroup_psi(cgrp); 4070 4071 return psi_show(seq, psi, PSI_MEM); 4072 } 4073 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v) 4074 { 4075 struct cgroup *cgrp = seq_css(seq)->cgroup; 4076 struct psi_group *psi = cgroup_psi(cgrp); 4077 4078 return psi_show(seq, psi, PSI_CPU); 4079 } 4080 4081 static ssize_t pressure_write(struct kernfs_open_file *of, char *buf, 4082 size_t nbytes, enum psi_res res) 4083 { 4084 struct cgroup_file_ctx *ctx; 4085 struct psi_trigger *new; 4086 struct cgroup *cgrp; 4087 struct psi_group *psi; 4088 bool need_rtpoll_worker; 4089 ssize_t ret = 0; 4090 4091 cgrp = cgroup_kn_lock_live(of->kn, false); 4092 if (IS_ERR(cgrp)) 4093 return PTR_ERR(cgrp); 4094 4095 ctx = of->priv; 4096 if (!ctx) { 4097 ret = -ENODEV; 4098 goto out_unlock; 4099 } 4100 4101 /* Allow only one trigger per file descriptor */ 4102 if (ctx->psi.trigger) { 4103 ret = -EBUSY; 4104 goto out_unlock; 4105 } 4106 4107 psi = cgroup_psi(cgrp); 4108 new = psi_trigger_create(psi, buf, res, of->file, of, 4109 &need_rtpoll_worker); 4110 if (IS_ERR(new)) { 4111 ret = PTR_ERR(new); 4112 goto out_unlock; 4113 } 4114 4115 /* 4116 * The worker fork must run with neither cgroup_mutex nor the file's 4117 * kernfs active reference held. The latter is broken since 4118 * cgroup_kn_lock_live(). @of->priv may be released while unlocked, so 4119 * recheck before publishing @new. 4120 */ 4121 if (need_rtpoll_worker) { 4122 cgroup_unlock(); 4123 ret = psi_trigger_create_rtpoll_worker(psi); 4124 cgroup_lock(); 4125 4126 if (!ret && !of->priv) 4127 ret = -ENODEV; 4128 if (ret) { 4129 psi_trigger_destroy(new); 4130 goto out_unlock; 4131 } 4132 } 4133 4134 smp_store_release(&ctx->psi.trigger, new); 4135 4136 out_unlock: 4137 cgroup_kn_unlock(of->kn); 4138 if (ret) 4139 return ret; 4140 4141 return nbytes; 4142 } 4143 4144 static ssize_t cgroup_io_pressure_write(struct kernfs_open_file *of, 4145 char *buf, size_t nbytes, 4146 loff_t off) 4147 { 4148 return pressure_write(of, buf, nbytes, PSI_IO); 4149 } 4150 4151 static ssize_t cgroup_memory_pressure_write(struct kernfs_open_file *of, 4152 char *buf, size_t nbytes, 4153 loff_t off) 4154 { 4155 return pressure_write(of, buf, nbytes, PSI_MEM); 4156 } 4157 4158 static ssize_t cgroup_cpu_pressure_write(struct kernfs_open_file *of, 4159 char *buf, size_t nbytes, 4160 loff_t off) 4161 { 4162 return pressure_write(of, buf, nbytes, PSI_CPU); 4163 } 4164 4165 #ifdef CONFIG_IRQ_TIME_ACCOUNTING 4166 static int cgroup_irq_pressure_show(struct seq_file *seq, void *v) 4167 { 4168 struct cgroup *cgrp = seq_css(seq)->cgroup; 4169 struct psi_group *psi = cgroup_psi(cgrp); 4170 4171 return psi_show(seq, psi, PSI_IRQ); 4172 } 4173 4174 static ssize_t cgroup_irq_pressure_write(struct kernfs_open_file *of, 4175 char *buf, size_t nbytes, 4176 loff_t off) 4177 { 4178 return pressure_write(of, buf, nbytes, PSI_IRQ); 4179 } 4180 #endif 4181 4182 static int cgroup_pressure_show(struct seq_file *seq, void *v) 4183 { 4184 struct cgroup *cgrp = seq_css(seq)->cgroup; 4185 struct psi_group *psi = cgroup_psi(cgrp); 4186 4187 seq_printf(seq, "%d\n", psi->enabled); 4188 4189 return 0; 4190 } 4191 4192 static ssize_t cgroup_pressure_write(struct kernfs_open_file *of, 4193 char *buf, size_t nbytes, 4194 loff_t off) 4195 { 4196 ssize_t ret; 4197 int enable; 4198 struct cgroup *cgrp; 4199 struct psi_group *psi; 4200 4201 ret = kstrtoint(strstrip(buf), 0, &enable); 4202 if (ret) 4203 return ret; 4204 4205 if (enable < 0 || enable > 1) 4206 return -ERANGE; 4207 4208 cgrp = cgroup_kn_lock_live(of->kn, false); 4209 if (IS_ERR(cgrp)) 4210 return PTR_ERR(cgrp); 4211 4212 psi = cgroup_psi(cgrp); 4213 if (psi->enabled != enable) { 4214 int i; 4215 4216 /* show or hide {cpu,memory,io,irq}.pressure files */ 4217 for (i = 0; i < NR_PSI_RESOURCES; i++) 4218 cgroup_file_show(&cgrp->psi_files[i], enable); 4219 4220 psi->enabled = enable; 4221 if (enable) 4222 psi_cgroup_restart(psi); 4223 } 4224 4225 cgroup_kn_unlock(of->kn); 4226 4227 return nbytes; 4228 } 4229 4230 static __poll_t cgroup_pressure_poll(struct kernfs_open_file *of, 4231 poll_table *pt) 4232 { 4233 struct cgroup_file_ctx *ctx = of->priv; 4234 4235 return psi_trigger_poll(&ctx->psi.trigger, of->file, pt); 4236 } 4237 4238 static void cgroup_pressure_release(struct kernfs_open_file *of) 4239 { 4240 struct cgroup_file_ctx *ctx = of->priv; 4241 4242 psi_trigger_destroy(ctx->psi.trigger); 4243 } 4244 4245 bool cgroup_psi_enabled(void) 4246 { 4247 if (static_branch_likely(&psi_disabled)) 4248 return false; 4249 4250 return (cgroup_feature_disable_mask & (1 << OPT_FEATURE_PRESSURE)) == 0; 4251 } 4252 4253 #else /* CONFIG_PSI */ 4254 bool cgroup_psi_enabled(void) 4255 { 4256 return false; 4257 } 4258 4259 #endif /* CONFIG_PSI */ 4260 4261 static int cgroup_freeze_show(struct seq_file *seq, void *v) 4262 { 4263 struct cgroup *cgrp = seq_css(seq)->cgroup; 4264 4265 seq_printf(seq, "%d\n", cgrp->freezer.freeze); 4266 4267 return 0; 4268 } 4269 4270 static ssize_t cgroup_freeze_write(struct kernfs_open_file *of, 4271 char *buf, size_t nbytes, loff_t off) 4272 { 4273 struct cgroup *cgrp; 4274 ssize_t ret; 4275 int freeze; 4276 4277 ret = kstrtoint(strstrip(buf), 0, &freeze); 4278 if (ret) 4279 return ret; 4280 4281 if (freeze < 0 || freeze > 1) 4282 return -ERANGE; 4283 4284 cgrp = cgroup_kn_lock_live(of->kn, false); 4285 if (IS_ERR(cgrp)) 4286 return PTR_ERR(cgrp); 4287 4288 cgroup_freeze(cgrp, freeze); 4289 4290 cgroup_kn_unlock(of->kn); 4291 4292 return nbytes; 4293 } 4294 4295 static void __cgroup_kill(struct cgroup *cgrp) 4296 { 4297 struct css_task_iter it; 4298 struct task_struct *task; 4299 4300 lockdep_assert_held(&cgroup_mutex); 4301 4302 spin_lock_irq(&css_set_lock); 4303 cgrp->kill_seq++; 4304 spin_unlock_irq(&css_set_lock); 4305 4306 css_task_iter_start(&cgrp->self, CSS_TASK_ITER_THREADED, &it); 4307 while ((task = css_task_iter_next(&it))) { 4308 /* Ignore kernel threads here. */ 4309 if (task->flags & PF_KTHREAD) 4310 continue; 4311 4312 /* Skip tasks that are already dying. */ 4313 if (__fatal_signal_pending(task)) 4314 continue; 4315 4316 send_sig(SIGKILL, task, 0); 4317 } 4318 css_task_iter_end(&it); 4319 } 4320 4321 static void cgroup_kill(struct cgroup *cgrp) 4322 { 4323 struct cgroup_subsys_state *css; 4324 struct cgroup *dsct; 4325 4326 lockdep_assert_held(&cgroup_mutex); 4327 4328 cgroup_for_each_live_descendant_pre(dsct, css, cgrp) 4329 __cgroup_kill(dsct); 4330 } 4331 4332 static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf, 4333 size_t nbytes, loff_t off) 4334 { 4335 ssize_t ret = 0; 4336 int kill; 4337 struct cgroup *cgrp; 4338 4339 ret = kstrtoint(strstrip(buf), 0, &kill); 4340 if (ret) 4341 return ret; 4342 4343 if (kill != 1) 4344 return -ERANGE; 4345 4346 cgrp = cgroup_kn_lock_live(of->kn, false); 4347 if (IS_ERR(cgrp)) 4348 return PTR_ERR(cgrp); 4349 4350 /* 4351 * Killing is a process directed operation, i.e. the whole thread-group 4352 * is taken down so act like we do for cgroup.procs and only make this 4353 * writable in non-threaded cgroups. 4354 */ 4355 if (cgroup_is_threaded(cgrp)) 4356 ret = -EOPNOTSUPP; 4357 else 4358 cgroup_kill(cgrp); 4359 4360 cgroup_kn_unlock(of->kn); 4361 4362 return ret ?: nbytes; 4363 } 4364 4365 static int cgroup_file_open(struct kernfs_open_file *of) 4366 { 4367 struct cftype *cft = of_cft(of); 4368 struct cgroup_file_ctx *ctx; 4369 int ret; 4370 4371 ctx = kzalloc_obj(*ctx); 4372 if (!ctx) 4373 return -ENOMEM; 4374 4375 ctx->ns = current->nsproxy->cgroup_ns; 4376 get_cgroup_ns(ctx->ns); 4377 of->priv = ctx; 4378 4379 if (!cft->open) 4380 return 0; 4381 4382 ret = cft->open(of); 4383 if (ret) { 4384 put_cgroup_ns(ctx->ns); 4385 kfree(ctx); 4386 } 4387 return ret; 4388 } 4389 4390 static void cgroup_file_release(struct kernfs_open_file *of) 4391 { 4392 struct cftype *cft = of_cft(of); 4393 struct cgroup_file_ctx *ctx = of->priv; 4394 4395 if (cft->release) 4396 cft->release(of); 4397 put_cgroup_ns(ctx->ns); 4398 kfree(ctx); 4399 of->priv = NULL; 4400 } 4401 4402 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf, 4403 size_t nbytes, loff_t off) 4404 { 4405 struct cgroup_file_ctx *ctx = of->priv; 4406 struct cgroup *cgrp = kn_priv(of->kn); 4407 struct cftype *cft = of_cft(of); 4408 struct cgroup_subsys_state *css; 4409 int ret; 4410 4411 if (!nbytes) 4412 return 0; 4413 4414 /* 4415 * If namespaces are delegation boundaries, disallow writes to 4416 * files in an non-init namespace root from inside the namespace 4417 * except for the files explicitly marked delegatable - 4418 * eg. cgroup.procs, cgroup.threads and cgroup.subtree_control. 4419 */ 4420 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) && 4421 !(cft->flags & CFTYPE_NS_DELEGATABLE) && 4422 ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp) 4423 return -EPERM; 4424 4425 if (cft->write) 4426 return cft->write(of, buf, nbytes, off); 4427 4428 /* 4429 * kernfs guarantees that a file isn't deleted with operations in 4430 * flight, which means that the matching css is and stays alive and 4431 * doesn't need to be pinned. The RCU locking is not necessary 4432 * either. It's just for the convenience of using cgroup_css(). 4433 */ 4434 rcu_read_lock(); 4435 css = cgroup_css(cgrp, cft->ss); 4436 rcu_read_unlock(); 4437 4438 if (cft->write_u64) { 4439 unsigned long long v; 4440 ret = kstrtoull(buf, 0, &v); 4441 if (!ret) 4442 ret = cft->write_u64(css, cft, v); 4443 } else if (cft->write_s64) { 4444 long long v; 4445 ret = kstrtoll(buf, 0, &v); 4446 if (!ret) 4447 ret = cft->write_s64(css, cft, v); 4448 } else { 4449 ret = -EINVAL; 4450 } 4451 4452 return ret ?: nbytes; 4453 } 4454 4455 static __poll_t cgroup_file_poll(struct kernfs_open_file *of, poll_table *pt) 4456 { 4457 struct cftype *cft = of_cft(of); 4458 4459 if (cft->poll) 4460 return cft->poll(of, pt); 4461 4462 return kernfs_generic_poll(of, pt); 4463 } 4464 4465 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos) 4466 { 4467 return seq_cft(seq)->seq_start(seq, ppos); 4468 } 4469 4470 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos) 4471 { 4472 return seq_cft(seq)->seq_next(seq, v, ppos); 4473 } 4474 4475 static void cgroup_seqfile_stop(struct seq_file *seq, void *v) 4476 { 4477 if (seq_cft(seq)->seq_stop) 4478 seq_cft(seq)->seq_stop(seq, v); 4479 } 4480 4481 static int cgroup_seqfile_show(struct seq_file *m, void *arg) 4482 { 4483 struct cftype *cft = seq_cft(m); 4484 struct cgroup_subsys_state *css = seq_css(m); 4485 4486 if (cft->seq_show) 4487 return cft->seq_show(m, arg); 4488 4489 if (cft->read_u64) 4490 seq_printf(m, "%llu\n", cft->read_u64(css, cft)); 4491 else if (cft->read_s64) 4492 seq_printf(m, "%lld\n", cft->read_s64(css, cft)); 4493 else 4494 return -EINVAL; 4495 return 0; 4496 } 4497 4498 static struct kernfs_ops cgroup_kf_single_ops = { 4499 .atomic_write_len = PAGE_SIZE, 4500 .open = cgroup_file_open, 4501 .release = cgroup_file_release, 4502 .write = cgroup_file_write, 4503 .poll = cgroup_file_poll, 4504 .seq_show = cgroup_seqfile_show, 4505 }; 4506 4507 static struct kernfs_ops cgroup_kf_ops = { 4508 .atomic_write_len = PAGE_SIZE, 4509 .open = cgroup_file_open, 4510 .release = cgroup_file_release, 4511 .write = cgroup_file_write, 4512 .poll = cgroup_file_poll, 4513 .seq_start = cgroup_seqfile_start, 4514 .seq_next = cgroup_seqfile_next, 4515 .seq_stop = cgroup_seqfile_stop, 4516 .seq_show = cgroup_seqfile_show, 4517 }; 4518 4519 static void cgroup_file_notify_timer(struct timer_list *timer) 4520 { 4521 cgroup_file_notify(container_of(timer, struct cgroup_file, 4522 notify_timer)); 4523 } 4524 4525 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp, 4526 struct cftype *cft) 4527 { 4528 char name[CGROUP_FILE_NAME_MAX]; 4529 struct kernfs_node *kn; 4530 struct lock_class_key *key = NULL; 4531 4532 #ifdef CONFIG_DEBUG_LOCK_ALLOC 4533 key = &cft->lockdep_key; 4534 #endif 4535 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name), 4536 cgroup_file_mode(cft), 4537 current_fsuid(), current_fsgid(), 4538 0, cft->kf_ops, cft, 4539 NULL, key); 4540 if (IS_ERR(kn)) 4541 return PTR_ERR(kn); 4542 4543 if (cft->file_offset) { 4544 struct cgroup_file *cfile = (void *)css + cft->file_offset; 4545 4546 timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0); 4547 spin_lock_init(&cfile->lock); 4548 cfile->kn = kn; 4549 } 4550 4551 return 0; 4552 } 4553 4554 /** 4555 * cgroup_addrm_files - add or remove files to a cgroup directory 4556 * @css: the target css 4557 * @cgrp: the target cgroup (usually css->cgroup) 4558 * @cfts: array of cftypes to be added 4559 * @is_add: whether to add or remove 4560 * 4561 * Depending on @is_add, add or remove files defined by @cfts on @cgrp. 4562 * For removals, this function never fails. 4563 */ 4564 static int cgroup_addrm_files(struct cgroup_subsys_state *css, 4565 struct cgroup *cgrp, struct cftype cfts[], 4566 bool is_add) 4567 { 4568 struct cftype *cft, *cft_end = NULL; 4569 int ret = 0; 4570 4571 lockdep_assert_held(&cgroup_mutex); 4572 4573 restart: 4574 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) { 4575 /* does cft->flags tell us to skip this file on @cgrp? */ 4576 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp)) 4577 continue; 4578 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp)) 4579 continue; 4580 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp)) 4581 continue; 4582 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp)) 4583 continue; 4584 if ((cft->flags & CFTYPE_DEBUG) && !cgroup_debug) 4585 continue; 4586 if (is_add) { 4587 ret = cgroup_add_file(css, cgrp, cft); 4588 if (ret) { 4589 pr_warn("%s: failed to add %s, err=%d\n", 4590 __func__, cft->name, ret); 4591 cft_end = cft; 4592 is_add = false; 4593 goto restart; 4594 } 4595 } else { 4596 cgroup_rm_file(cgrp, cft); 4597 } 4598 } 4599 return ret; 4600 } 4601 4602 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add) 4603 { 4604 struct cgroup_subsys *ss = cfts[0].ss; 4605 struct cgroup *root = &ss->root->cgrp; 4606 struct cgroup_subsys_state *css; 4607 int ret = 0; 4608 4609 lockdep_assert_held(&cgroup_mutex); 4610 4611 /* add/rm files for all cgroups created before */ 4612 css_for_each_descendant_pre(css, cgroup_css(root, ss)) { 4613 struct cgroup *cgrp = css->cgroup; 4614 4615 if (!(css->flags & CSS_VISIBLE)) 4616 continue; 4617 4618 ret = cgroup_addrm_files(css, cgrp, cfts, is_add); 4619 if (ret) 4620 break; 4621 } 4622 4623 if (is_add && !ret) 4624 kernfs_activate(root->kn); 4625 return ret; 4626 } 4627 4628 static void cgroup_exit_cftypes(struct cftype *cfts) 4629 { 4630 struct cftype *cft; 4631 4632 for (cft = cfts; cft->name[0] != '\0'; cft++) { 4633 /* free copy for custom atomic_write_len, see init_cftypes() */ 4634 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) 4635 kfree(cft->kf_ops); 4636 cft->kf_ops = NULL; 4637 cft->ss = NULL; 4638 4639 /* revert flags set by cgroup core while adding @cfts */ 4640 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL | 4641 __CFTYPE_ADDED); 4642 } 4643 } 4644 4645 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts) 4646 { 4647 struct cftype *cft; 4648 int ret = 0; 4649 4650 for (cft = cfts; cft->name[0] != '\0'; cft++) { 4651 struct kernfs_ops *kf_ops; 4652 4653 WARN_ON(cft->ss || cft->kf_ops); 4654 4655 if (cft->flags & __CFTYPE_ADDED) { 4656 ret = -EBUSY; 4657 break; 4658 } 4659 4660 if (cft->seq_start) 4661 kf_ops = &cgroup_kf_ops; 4662 else 4663 kf_ops = &cgroup_kf_single_ops; 4664 4665 /* 4666 * Ugh... if @cft wants a custom max_write_len, we need to 4667 * make a copy of kf_ops to set its atomic_write_len. 4668 */ 4669 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) { 4670 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL); 4671 if (!kf_ops) { 4672 ret = -ENOMEM; 4673 break; 4674 } 4675 kf_ops->atomic_write_len = cft->max_write_len; 4676 } 4677 4678 cft->kf_ops = kf_ops; 4679 cft->ss = ss; 4680 cft->flags |= __CFTYPE_ADDED; 4681 } 4682 4683 if (ret) 4684 cgroup_exit_cftypes(cfts); 4685 return ret; 4686 } 4687 4688 static void cgroup_rm_cftypes_locked(struct cftype *cfts) 4689 { 4690 lockdep_assert_held(&cgroup_mutex); 4691 4692 list_del(&cfts->node); 4693 cgroup_apply_cftypes(cfts, false); 4694 cgroup_exit_cftypes(cfts); 4695 } 4696 4697 /** 4698 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem 4699 * @cfts: zero-length name terminated array of cftypes 4700 * 4701 * Unregister @cfts. Files described by @cfts are removed from all 4702 * existing cgroups and all future cgroups won't have them either. This 4703 * function can be called anytime whether @cfts' subsys is attached or not. 4704 * 4705 * Returns 0 on successful unregistration, -ENOENT if @cfts is not 4706 * registered. 4707 */ 4708 int cgroup_rm_cftypes(struct cftype *cfts) 4709 { 4710 if (!cfts || cfts[0].name[0] == '\0') 4711 return 0; 4712 4713 if (!(cfts[0].flags & __CFTYPE_ADDED)) 4714 return -ENOENT; 4715 4716 cgroup_lock(); 4717 cgroup_rm_cftypes_locked(cfts); 4718 cgroup_unlock(); 4719 return 0; 4720 } 4721 4722 /** 4723 * cgroup_add_cftypes - add an array of cftypes to a subsystem 4724 * @ss: target cgroup subsystem 4725 * @cfts: zero-length name terminated array of cftypes 4726 * 4727 * Register @cfts to @ss. Files described by @cfts are created for all 4728 * existing cgroups to which @ss is attached and all future cgroups will 4729 * have them too. This function can be called anytime whether @ss is 4730 * attached or not. 4731 * 4732 * Returns 0 on successful registration, -errno on failure. Note that this 4733 * function currently returns 0 as long as @cfts registration is successful 4734 * even if some file creation attempts on existing cgroups fail. 4735 */ 4736 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts) 4737 { 4738 int ret; 4739 4740 if (!cgroup_ssid_enabled(ss->id)) 4741 return 0; 4742 4743 if (!cfts || cfts[0].name[0] == '\0') 4744 return 0; 4745 4746 ret = cgroup_init_cftypes(ss, cfts); 4747 if (ret) 4748 return ret; 4749 4750 cgroup_lock(); 4751 4752 list_add_tail(&cfts->node, &ss->cfts); 4753 ret = cgroup_apply_cftypes(cfts, true); 4754 if (ret) 4755 cgroup_rm_cftypes_locked(cfts); 4756 4757 cgroup_unlock(); 4758 return ret; 4759 } 4760 4761 /** 4762 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy 4763 * @ss: target cgroup subsystem 4764 * @cfts: zero-length name terminated array of cftypes 4765 * 4766 * Similar to cgroup_add_cftypes() but the added files are only used for 4767 * the default hierarchy. 4768 */ 4769 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts) 4770 { 4771 struct cftype *cft; 4772 4773 for (cft = cfts; cft && cft->name[0] != '\0'; cft++) 4774 cft->flags |= __CFTYPE_ONLY_ON_DFL; 4775 return cgroup_add_cftypes(ss, cfts); 4776 } 4777 4778 /** 4779 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies 4780 * @ss: target cgroup subsystem 4781 * @cfts: zero-length name terminated array of cftypes 4782 * 4783 * Similar to cgroup_add_cftypes() but the added files are only used for 4784 * the legacy hierarchies. 4785 */ 4786 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts) 4787 { 4788 struct cftype *cft; 4789 4790 for (cft = cfts; cft && cft->name[0] != '\0'; cft++) 4791 cft->flags |= __CFTYPE_NOT_ON_DFL; 4792 return cgroup_add_cftypes(ss, cfts); 4793 } 4794 4795 /** 4796 * cgroup_file_notify - generate a file modified event for a cgroup_file 4797 * @cfile: target cgroup_file 4798 * 4799 * @cfile must have been obtained by setting cftype->file_offset. 4800 */ 4801 void cgroup_file_notify(struct cgroup_file *cfile) 4802 { 4803 unsigned long flags, last, next; 4804 struct kernfs_node *kn = NULL; 4805 4806 if (!READ_ONCE(cfile->kn)) 4807 return; 4808 4809 if (timer_pending(&cfile->notify_timer)) 4810 return; 4811 4812 spin_lock_irqsave(&cfile->lock, flags); 4813 if (cfile->kn) { 4814 last = cfile->notified_at; 4815 next = last + CGROUP_FILE_NOTIFY_MIN_INTV; 4816 4817 if (time_in_range(jiffies, last, next)) { 4818 timer_reduce(&cfile->notify_timer, next); 4819 } else { 4820 kn = cfile->kn; 4821 kernfs_get(kn); 4822 cfile->notified_at = jiffies; 4823 } 4824 } 4825 spin_unlock_irqrestore(&cfile->lock, flags); 4826 4827 if (kn) { 4828 kernfs_notify(kn); 4829 kernfs_put(kn); 4830 } 4831 } 4832 EXPORT_SYMBOL_GPL(cgroup_file_notify); 4833 4834 /** 4835 * cgroup_file_show - show or hide a hidden cgroup file 4836 * @cfile: target cgroup_file obtained by setting cftype->file_offset 4837 * @show: whether to show or hide 4838 */ 4839 void cgroup_file_show(struct cgroup_file *cfile, bool show) 4840 { 4841 struct kernfs_node *kn; 4842 4843 spin_lock_irq(&cfile->lock); 4844 kn = cfile->kn; 4845 kernfs_get(kn); 4846 spin_unlock_irq(&cfile->lock); 4847 4848 if (kn) 4849 kernfs_show(kn, show); 4850 4851 kernfs_put(kn); 4852 } 4853 4854 /** 4855 * css_next_child - find the next child of a given css 4856 * @pos: the current position (%NULL to initiate traversal) 4857 * @parent: css whose children to walk 4858 * 4859 * This function returns the next child of @parent and should be called 4860 * under either cgroup_mutex or RCU read lock. The only requirement is 4861 * that @parent and @pos are accessible. The next sibling is guaranteed to 4862 * be returned regardless of their states. 4863 * 4864 * If a subsystem synchronizes ->css_online() and the start of iteration, a 4865 * css which finished ->css_online() is guaranteed to be visible in the 4866 * future iterations and will stay visible until the last reference is put. 4867 * A css which hasn't finished ->css_online() or already finished 4868 * ->css_offline() may show up during traversal. It's each subsystem's 4869 * responsibility to synchronize against on/offlining. 4870 */ 4871 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos, 4872 struct cgroup_subsys_state *parent) 4873 { 4874 struct cgroup_subsys_state *next; 4875 4876 cgroup_assert_mutex_or_rcu_locked(); 4877 4878 /* 4879 * @pos could already have been unlinked from the sibling list. 4880 * Once a cgroup is removed, its ->sibling.next is no longer 4881 * updated when its next sibling changes. CSS_RELEASED is set when 4882 * @pos is taken off list, at which time its next pointer is valid, 4883 * and, as releases are serialized, the one pointed to by the next 4884 * pointer is guaranteed to not have started release yet. This 4885 * implies that if we observe !CSS_RELEASED on @pos in this RCU 4886 * critical section, the one pointed to by its next pointer is 4887 * guaranteed to not have finished its RCU grace period even if we 4888 * have dropped rcu_read_lock() in-between iterations. 4889 * 4890 * If @pos has CSS_RELEASED set, its next pointer can't be 4891 * dereferenced; however, as each css is given a monotonically 4892 * increasing unique serial number and always appended to the 4893 * sibling list, the next one can be found by walking the parent's 4894 * children until the first css with higher serial number than 4895 * @pos's. While this path can be slower, it happens iff iteration 4896 * races against release and the race window is very small. 4897 */ 4898 if (!pos) { 4899 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling); 4900 } else if (likely(!(pos->flags & CSS_RELEASED))) { 4901 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling); 4902 } else { 4903 list_for_each_entry_rcu(next, &parent->children, sibling, 4904 lockdep_is_held(&cgroup_mutex)) 4905 if (next->serial_nr > pos->serial_nr) 4906 break; 4907 } 4908 4909 /* 4910 * @next, if not pointing to the head, can be dereferenced and is 4911 * the next sibling. 4912 */ 4913 if (&next->sibling != &parent->children) 4914 return next; 4915 return NULL; 4916 } 4917 4918 /** 4919 * css_next_descendant_pre - find the next descendant for pre-order walk 4920 * @pos: the current position (%NULL to initiate traversal) 4921 * @root: css whose descendants to walk 4922 * 4923 * To be used by css_for_each_descendant_pre(). Find the next descendant 4924 * to visit for pre-order traversal of @root's descendants. @root is 4925 * included in the iteration and the first node to be visited. 4926 * 4927 * While this function requires cgroup_mutex or RCU read locking, it 4928 * doesn't require the whole traversal to be contained in a single critical 4929 * section. Additionally, it isn't necessary to hold onto a reference to @pos. 4930 * This function will return the correct next descendant as long as both @pos 4931 * and @root are accessible and @pos is a descendant of @root. 4932 * 4933 * If a subsystem synchronizes ->css_online() and the start of iteration, a 4934 * css which finished ->css_online() is guaranteed to be visible in the 4935 * future iterations and will stay visible until the last reference is put. 4936 * A css which hasn't finished ->css_online() or already finished 4937 * ->css_offline() may show up during traversal. It's each subsystem's 4938 * responsibility to synchronize against on/offlining. 4939 */ 4940 struct cgroup_subsys_state * 4941 css_next_descendant_pre(struct cgroup_subsys_state *pos, 4942 struct cgroup_subsys_state *root) 4943 { 4944 struct cgroup_subsys_state *next; 4945 4946 cgroup_assert_mutex_or_rcu_locked(); 4947 4948 /* if first iteration, visit @root */ 4949 if (!pos) 4950 return root; 4951 4952 /* visit the first child if exists */ 4953 next = css_next_child(NULL, pos); 4954 if (next) 4955 return next; 4956 4957 /* no child, visit my or the closest ancestor's next sibling */ 4958 while (pos != root) { 4959 next = css_next_child(pos, pos->parent); 4960 if (next) 4961 return next; 4962 pos = pos->parent; 4963 } 4964 4965 return NULL; 4966 } 4967 EXPORT_SYMBOL_GPL(css_next_descendant_pre); 4968 4969 /** 4970 * css_rightmost_descendant - return the rightmost descendant of a css 4971 * @pos: css of interest 4972 * 4973 * Return the rightmost descendant of @pos. If there's no descendant, @pos 4974 * is returned. This can be used during pre-order traversal to skip 4975 * subtree of @pos. 4976 * 4977 * While this function requires cgroup_mutex or RCU read locking, it 4978 * doesn't require the whole traversal to be contained in a single critical 4979 * section. Additionally, it isn't necessary to hold onto a reference to @pos. 4980 * This function will return the correct rightmost descendant as long as @pos 4981 * is accessible. 4982 */ 4983 struct cgroup_subsys_state * 4984 css_rightmost_descendant(struct cgroup_subsys_state *pos) 4985 { 4986 struct cgroup_subsys_state *last, *tmp; 4987 4988 cgroup_assert_mutex_or_rcu_locked(); 4989 4990 do { 4991 last = pos; 4992 /* ->prev isn't RCU safe, walk ->next till the end */ 4993 pos = NULL; 4994 css_for_each_child(tmp, last) 4995 pos = tmp; 4996 } while (pos); 4997 4998 return last; 4999 } 5000 5001 static struct cgroup_subsys_state * 5002 css_leftmost_descendant(struct cgroup_subsys_state *pos) 5003 { 5004 struct cgroup_subsys_state *last; 5005 5006 do { 5007 last = pos; 5008 pos = css_next_child(NULL, pos); 5009 } while (pos); 5010 5011 return last; 5012 } 5013 5014 /** 5015 * css_next_descendant_post - find the next descendant for post-order walk 5016 * @pos: the current position (%NULL to initiate traversal) 5017 * @root: css whose descendants to walk 5018 * 5019 * To be used by css_for_each_descendant_post(). Find the next descendant 5020 * to visit for post-order traversal of @root's descendants. @root is 5021 * included in the iteration and the last node to be visited. 5022 * 5023 * While this function requires cgroup_mutex or RCU read locking, it 5024 * doesn't require the whole traversal to be contained in a single critical 5025 * section. Additionally, it isn't necessary to hold onto a reference to @pos. 5026 * This function will return the correct next descendant as long as both @pos 5027 * and @cgroup are accessible and @pos is a descendant of @cgroup. 5028 * 5029 * If a subsystem synchronizes ->css_online() and the start of iteration, a 5030 * css which finished ->css_online() is guaranteed to be visible in the 5031 * future iterations and will stay visible until the last reference is put. 5032 * A css which hasn't finished ->css_online() or already finished 5033 * ->css_offline() may show up during traversal. It's each subsystem's 5034 * responsibility to synchronize against on/offlining. 5035 */ 5036 struct cgroup_subsys_state * 5037 css_next_descendant_post(struct cgroup_subsys_state *pos, 5038 struct cgroup_subsys_state *root) 5039 { 5040 struct cgroup_subsys_state *next; 5041 5042 cgroup_assert_mutex_or_rcu_locked(); 5043 5044 /* if first iteration, visit leftmost descendant which may be @root */ 5045 if (!pos) 5046 return css_leftmost_descendant(root); 5047 5048 /* if we visited @root, we're done */ 5049 if (pos == root) 5050 return NULL; 5051 5052 /* if there's an unvisited sibling, visit its leftmost descendant */ 5053 next = css_next_child(pos, pos->parent); 5054 if (next) 5055 return css_leftmost_descendant(next); 5056 5057 /* no sibling left, visit parent */ 5058 return pos->parent; 5059 } 5060 5061 /** 5062 * css_has_online_children - does a css have online children 5063 * @css: the target css 5064 * 5065 * Returns %true if @css has any online children; otherwise, %false. This 5066 * function can be called from any context but the caller is responsible 5067 * for synchronizing against on/offlining as necessary. 5068 */ 5069 bool css_has_online_children(struct cgroup_subsys_state *css) 5070 { 5071 struct cgroup_subsys_state *child; 5072 bool ret = false; 5073 5074 rcu_read_lock(); 5075 css_for_each_child(child, css) { 5076 if (css_is_online(child)) { 5077 ret = true; 5078 break; 5079 } 5080 } 5081 rcu_read_unlock(); 5082 return ret; 5083 } 5084 5085 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it) 5086 { 5087 struct list_head *l; 5088 struct cgrp_cset_link *link; 5089 struct css_set *cset; 5090 5091 lockdep_assert_held(&css_set_lock); 5092 5093 /* find the next threaded cset */ 5094 if (it->tcset_pos) { 5095 l = it->tcset_pos->next; 5096 5097 if (l != it->tcset_head) { 5098 it->tcset_pos = l; 5099 return container_of(l, struct css_set, 5100 threaded_csets_node); 5101 } 5102 5103 it->tcset_pos = NULL; 5104 } 5105 5106 /* find the next cset */ 5107 l = it->cset_pos; 5108 l = l->next; 5109 if (l == it->cset_head) { 5110 it->cset_pos = NULL; 5111 return NULL; 5112 } 5113 5114 if (it->ss) { 5115 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]); 5116 } else { 5117 link = list_entry(l, struct cgrp_cset_link, cset_link); 5118 cset = link->cset; 5119 } 5120 5121 it->cset_pos = l; 5122 5123 /* initialize threaded css_set walking */ 5124 if (it->flags & CSS_TASK_ITER_THREADED) { 5125 if (it->cur_dcset) 5126 put_css_set_locked(it->cur_dcset); 5127 it->cur_dcset = cset; 5128 get_css_set(cset); 5129 5130 it->tcset_head = &cset->threaded_csets; 5131 it->tcset_pos = &cset->threaded_csets; 5132 } 5133 5134 return cset; 5135 } 5136 5137 /** 5138 * css_task_iter_advance_css_set - advance a task iterator to the next css_set 5139 * @it: the iterator to advance 5140 * 5141 * Advance @it to the next css_set to walk. 5142 */ 5143 static void css_task_iter_advance_css_set(struct css_task_iter *it) 5144 { 5145 struct css_set *cset; 5146 5147 lockdep_assert_held(&css_set_lock); 5148 5149 /* Advance to the next non-empty css_set and find first non-empty tasks list*/ 5150 while ((cset = css_task_iter_next_css_set(it))) { 5151 if (!list_empty(&cset->tasks)) { 5152 it->cur_tasks_head = &cset->tasks; 5153 break; 5154 } else if (!list_empty(&cset->mg_tasks)) { 5155 it->cur_tasks_head = &cset->mg_tasks; 5156 break; 5157 } else if (!list_empty(&cset->dying_tasks)) { 5158 it->cur_tasks_head = &cset->dying_tasks; 5159 break; 5160 } 5161 } 5162 if (!cset) { 5163 it->task_pos = NULL; 5164 return; 5165 } 5166 it->task_pos = it->cur_tasks_head->next; 5167 5168 /* 5169 * We don't keep css_sets locked across iteration steps and thus 5170 * need to take steps to ensure that iteration can be resumed after 5171 * the lock is re-acquired. Iteration is performed at two levels - 5172 * css_sets and tasks in them. 5173 * 5174 * Once created, a css_set never leaves its cgroup lists, so a 5175 * pinned css_set is guaranteed to stay put and we can resume 5176 * iteration afterwards. 5177 * 5178 * Tasks may leave @cset across iteration steps. This is resolved 5179 * by registering each iterator with the css_set currently being 5180 * walked and making css_set_move_task() advance iterators whose 5181 * next task is leaving. 5182 */ 5183 if (it->cur_cset) { 5184 list_del(&it->iters_node); 5185 put_css_set_locked(it->cur_cset); 5186 } 5187 get_css_set(cset); 5188 it->cur_cset = cset; 5189 list_add(&it->iters_node, &cset->task_iters); 5190 } 5191 5192 static void css_task_iter_skip(struct css_task_iter *it, 5193 struct task_struct *task) 5194 { 5195 lockdep_assert_held(&css_set_lock); 5196 5197 if (it->task_pos == &task->cg_list) { 5198 it->task_pos = it->task_pos->next; 5199 it->flags |= CSS_TASK_ITER_SKIPPED; 5200 } 5201 } 5202 5203 static void css_task_iter_advance(struct css_task_iter *it) 5204 { 5205 struct task_struct *task; 5206 5207 lockdep_assert_held(&css_set_lock); 5208 repeat: 5209 if (it->task_pos) { 5210 /* 5211 * Advance iterator to find next entry. We go through cset 5212 * tasks, mg_tasks and dying_tasks, when consumed we move onto 5213 * the next cset. 5214 */ 5215 if (it->flags & CSS_TASK_ITER_SKIPPED) 5216 it->flags &= ~CSS_TASK_ITER_SKIPPED; 5217 else 5218 it->task_pos = it->task_pos->next; 5219 5220 if (it->task_pos == &it->cur_cset->tasks) { 5221 it->cur_tasks_head = &it->cur_cset->mg_tasks; 5222 it->task_pos = it->cur_tasks_head->next; 5223 } 5224 if (it->task_pos == &it->cur_cset->mg_tasks) { 5225 it->cur_tasks_head = &it->cur_cset->dying_tasks; 5226 it->task_pos = it->cur_tasks_head->next; 5227 } 5228 if (it->task_pos == &it->cur_cset->dying_tasks) 5229 css_task_iter_advance_css_set(it); 5230 } else { 5231 /* called from start, proceed to the first cset */ 5232 css_task_iter_advance_css_set(it); 5233 } 5234 5235 if (!it->task_pos) 5236 return; 5237 5238 task = list_entry(it->task_pos, struct task_struct, cg_list); 5239 /* 5240 * Hide tasks that are exiting but not yet removed by default. Keep 5241 * zombie leaders with live threads visible. Usages that need to walk 5242 * every existing task can opt out via CSS_TASK_ITER_WITH_DEAD. 5243 */ 5244 if (!(it->flags & CSS_TASK_ITER_WITH_DEAD) && 5245 (task->flags & PF_EXITING) && !atomic_read(&task->signal->live)) 5246 goto repeat; 5247 5248 if (it->flags & CSS_TASK_ITER_PROCS) { 5249 /* if PROCS, skip over tasks which aren't group leaders */ 5250 if (!thread_group_leader(task)) 5251 goto repeat; 5252 5253 /* and dying leaders w/o live member threads */ 5254 if (it->cur_tasks_head == &it->cur_cset->dying_tasks && 5255 !atomic_read(&task->signal->live)) 5256 goto repeat; 5257 } else { 5258 /* skip all dying ones */ 5259 if (it->cur_tasks_head == &it->cur_cset->dying_tasks) 5260 goto repeat; 5261 } 5262 } 5263 5264 /** 5265 * css_task_iter_start - initiate task iteration 5266 * @css: the css to walk tasks of 5267 * @flags: CSS_TASK_ITER_* flags 5268 * @it: the task iterator to use 5269 * 5270 * Initiate iteration through the tasks of @css. The caller can call 5271 * css_task_iter_next() to walk through the tasks until the function 5272 * returns NULL. On completion of iteration, css_task_iter_end() must be 5273 * called. 5274 */ 5275 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags, 5276 struct css_task_iter *it) 5277 { 5278 unsigned long irqflags; 5279 5280 memset(it, 0, sizeof(*it)); 5281 5282 spin_lock_irqsave(&css_set_lock, irqflags); 5283 5284 it->ss = css->ss; 5285 it->flags = flags; 5286 5287 if (CGROUP_HAS_SUBSYS_CONFIG && it->ss) 5288 it->cset_pos = &css->cgroup->e_csets[css->ss->id]; 5289 else 5290 it->cset_pos = &css->cgroup->cset_links; 5291 5292 it->cset_head = it->cset_pos; 5293 5294 css_task_iter_advance(it); 5295 5296 spin_unlock_irqrestore(&css_set_lock, irqflags); 5297 } 5298 5299 /** 5300 * css_task_iter_next - return the next task for the iterator 5301 * @it: the task iterator being iterated 5302 * 5303 * The "next" function for task iteration. @it should have been 5304 * initialized via css_task_iter_start(). Returns NULL when the iteration 5305 * reaches the end. 5306 */ 5307 struct task_struct *css_task_iter_next(struct css_task_iter *it) 5308 { 5309 unsigned long irqflags; 5310 5311 if (it->cur_task) { 5312 put_task_struct(it->cur_task); 5313 it->cur_task = NULL; 5314 } 5315 5316 spin_lock_irqsave(&css_set_lock, irqflags); 5317 5318 /* @it may be half-advanced by skips, finish advancing */ 5319 if (it->flags & CSS_TASK_ITER_SKIPPED) 5320 css_task_iter_advance(it); 5321 5322 while (it->task_pos && !it->cur_task) { 5323 it->cur_task = list_entry(it->task_pos, struct task_struct, 5324 cg_list); 5325 /* a task on dying_tasks with zero refcount is only valid for 5326 * RCU readers, not even interesting for 5327 * CSS_TASK_ITER_WITH_DEAD, find another one */ 5328 it->cur_task = tryget_task_struct(it->cur_task); 5329 css_task_iter_advance(it); 5330 } 5331 5332 spin_unlock_irqrestore(&css_set_lock, irqflags); 5333 5334 return it->cur_task; 5335 } 5336 5337 /** 5338 * css_task_iter_end - finish task iteration 5339 * @it: the task iterator to finish 5340 * 5341 * Finish task iteration started by css_task_iter_start(). 5342 */ 5343 void css_task_iter_end(struct css_task_iter *it) 5344 { 5345 unsigned long irqflags; 5346 5347 if (it->cur_cset) { 5348 spin_lock_irqsave(&css_set_lock, irqflags); 5349 list_del(&it->iters_node); 5350 put_css_set_locked(it->cur_cset); 5351 spin_unlock_irqrestore(&css_set_lock, irqflags); 5352 } 5353 5354 if (it->cur_dcset) 5355 put_css_set(it->cur_dcset); 5356 5357 if (it->cur_task) 5358 put_task_struct(it->cur_task); 5359 } 5360 5361 static void cgroup_procs_release(struct kernfs_open_file *of) 5362 { 5363 struct cgroup_file_ctx *ctx = of->priv; 5364 5365 if (ctx->procs.started) 5366 css_task_iter_end(&ctx->procs.iter); 5367 } 5368 5369 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos) 5370 { 5371 struct kernfs_open_file *of = s->private; 5372 struct cgroup_file_ctx *ctx = of->priv; 5373 5374 if (pos) 5375 (*pos)++; 5376 5377 return css_task_iter_next(&ctx->procs.iter); 5378 } 5379 5380 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos, 5381 unsigned int iter_flags) 5382 { 5383 struct kernfs_open_file *of = s->private; 5384 struct cgroup *cgrp = seq_css(s)->cgroup; 5385 struct cgroup_file_ctx *ctx = of->priv; 5386 struct css_task_iter *it = &ctx->procs.iter; 5387 5388 /* 5389 * When a seq_file is seeked, it's always traversed sequentially 5390 * from position 0, so we can simply keep iterating on !0 *pos. 5391 */ 5392 if (!ctx->procs.started) { 5393 if (WARN_ON_ONCE((*pos))) 5394 return ERR_PTR(-EINVAL); 5395 css_task_iter_start(&cgrp->self, iter_flags, it); 5396 ctx->procs.started = true; 5397 } else if (!(*pos)) { 5398 css_task_iter_end(it); 5399 css_task_iter_start(&cgrp->self, iter_flags, it); 5400 } else 5401 return it->cur_task; 5402 5403 return cgroup_procs_next(s, NULL, NULL); 5404 } 5405 5406 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos) 5407 { 5408 struct cgroup *cgrp = seq_css(s)->cgroup; 5409 5410 /* 5411 * All processes of a threaded subtree belong to the domain cgroup 5412 * of the subtree. Only threads can be distributed across the 5413 * subtree. Reject reads on cgroup.procs in the subtree proper. 5414 * They're always empty anyway. 5415 */ 5416 if (cgroup_is_threaded(cgrp)) 5417 return ERR_PTR(-EOPNOTSUPP); 5418 5419 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS | 5420 CSS_TASK_ITER_THREADED); 5421 } 5422 5423 static int cgroup_procs_show(struct seq_file *s, void *v) 5424 { 5425 seq_printf(s, "%d\n", task_pid_vnr(v)); 5426 return 0; 5427 } 5428 5429 static int cgroup_may_write(const struct cgroup *cgrp, struct super_block *sb) 5430 { 5431 int ret; 5432 struct inode *inode; 5433 5434 lockdep_assert_held(&cgroup_mutex); 5435 5436 inode = kernfs_get_inode(sb, cgrp->procs_file.kn); 5437 if (!inode) 5438 return -ENOMEM; 5439 5440 ret = inode_permission(&nop_mnt_idmap, inode, MAY_WRITE); 5441 iput(inode); 5442 return ret; 5443 } 5444 5445 static int cgroup_procs_write_permission(struct cgroup *src_cgrp, 5446 struct cgroup *dst_cgrp, 5447 struct super_block *sb, 5448 struct cgroup_namespace *ns) 5449 { 5450 struct cgroup *com_cgrp = src_cgrp; 5451 int ret; 5452 5453 lockdep_assert_held(&cgroup_mutex); 5454 5455 /* find the common ancestor */ 5456 while (!cgroup_is_descendant(dst_cgrp, com_cgrp)) 5457 com_cgrp = cgroup_parent(com_cgrp); 5458 5459 /* %current should be authorized to migrate to the common ancestor */ 5460 ret = cgroup_may_write(com_cgrp, sb); 5461 if (ret) 5462 return ret; 5463 5464 /* 5465 * If namespaces are delegation boundaries, %current must be able 5466 * to see both source and destination cgroups from its namespace. 5467 */ 5468 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) && 5469 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) || 5470 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp))) 5471 return -ENOENT; 5472 5473 return 0; 5474 } 5475 5476 static int cgroup_attach_permissions(struct cgroup *src_cgrp, 5477 struct cgroup *dst_cgrp, 5478 struct super_block *sb, bool threadgroup, 5479 struct cgroup_namespace *ns) 5480 { 5481 int ret = 0; 5482 5483 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp, sb, ns); 5484 if (ret) 5485 return ret; 5486 5487 ret = cgroup_migrate_vet_dst(dst_cgrp); 5488 if (ret) 5489 return ret; 5490 5491 if (!threadgroup && (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp)) 5492 ret = -EOPNOTSUPP; 5493 5494 return ret; 5495 } 5496 5497 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf, 5498 bool threadgroup) 5499 { 5500 struct cgroup_file_ctx *ctx = of->priv; 5501 struct cgroup *src_cgrp, *dst_cgrp; 5502 struct task_struct *task; 5503 ssize_t ret; 5504 enum cgroup_attach_lock_mode lock_mode; 5505 5506 dst_cgrp = cgroup_kn_lock_live(of->kn, false); 5507 if (IS_ERR(dst_cgrp)) 5508 return PTR_ERR(dst_cgrp); 5509 5510 task = cgroup_procs_write_start(buf, threadgroup, &lock_mode); 5511 ret = PTR_ERR_OR_ZERO(task); 5512 if (ret) 5513 goto out_unlock; 5514 5515 /* find the source cgroup */ 5516 spin_lock_irq(&css_set_lock); 5517 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root); 5518 spin_unlock_irq(&css_set_lock); 5519 5520 /* 5521 * Process and thread migrations follow same delegation rule. Check 5522 * permissions using the credentials from file open to protect against 5523 * inherited fd attacks. 5524 */ 5525 scoped_with_creds(of->file->f_cred) 5526 ret = cgroup_attach_permissions(src_cgrp, dst_cgrp, 5527 of->file->f_path.dentry->d_sb, 5528 threadgroup, ctx->ns); 5529 if (ret) 5530 goto out_finish; 5531 5532 ret = cgroup_attach_task(dst_cgrp, task, threadgroup); 5533 5534 out_finish: 5535 cgroup_procs_write_finish(task, lock_mode); 5536 out_unlock: 5537 cgroup_kn_unlock(of->kn); 5538 5539 return ret; 5540 } 5541 5542 static ssize_t cgroup_procs_write(struct kernfs_open_file *of, 5543 char *buf, size_t nbytes, loff_t off) 5544 { 5545 return __cgroup_procs_write(of, buf, true) ?: nbytes; 5546 } 5547 5548 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos) 5549 { 5550 return __cgroup_procs_start(s, pos, 0); 5551 } 5552 5553 static ssize_t cgroup_threads_write(struct kernfs_open_file *of, 5554 char *buf, size_t nbytes, loff_t off) 5555 { 5556 return __cgroup_procs_write(of, buf, false) ?: nbytes; 5557 } 5558 5559 /* cgroup core interface files for the default hierarchy */ 5560 static struct cftype cgroup_base_files[] = { 5561 { 5562 .name = "cgroup.type", 5563 .flags = CFTYPE_NOT_ON_ROOT, 5564 .seq_show = cgroup_type_show, 5565 .write = cgroup_type_write, 5566 }, 5567 { 5568 .name = "cgroup.procs", 5569 .flags = CFTYPE_NS_DELEGATABLE, 5570 .file_offset = offsetof(struct cgroup, procs_file), 5571 .release = cgroup_procs_release, 5572 .seq_start = cgroup_procs_start, 5573 .seq_next = cgroup_procs_next, 5574 .seq_show = cgroup_procs_show, 5575 .write = cgroup_procs_write, 5576 }, 5577 { 5578 .name = "cgroup.threads", 5579 .flags = CFTYPE_NS_DELEGATABLE, 5580 .release = cgroup_procs_release, 5581 .seq_start = cgroup_threads_start, 5582 .seq_next = cgroup_procs_next, 5583 .seq_show = cgroup_procs_show, 5584 .write = cgroup_threads_write, 5585 }, 5586 { 5587 .name = "cgroup.controllers", 5588 .seq_show = cgroup_controllers_show, 5589 }, 5590 { 5591 .name = "cgroup.subtree_control", 5592 .flags = CFTYPE_NS_DELEGATABLE, 5593 .seq_show = cgroup_subtree_control_show, 5594 .write = cgroup_subtree_control_write, 5595 }, 5596 { 5597 .name = "cgroup.events", 5598 .flags = CFTYPE_NOT_ON_ROOT, 5599 .file_offset = offsetof(struct cgroup, events_file), 5600 .seq_show = cgroup_events_show, 5601 }, 5602 { 5603 .name = "cgroup.max.descendants", 5604 .seq_show = cgroup_max_descendants_show, 5605 .write = cgroup_max_descendants_write, 5606 }, 5607 { 5608 .name = "cgroup.max.depth", 5609 .seq_show = cgroup_max_depth_show, 5610 .write = cgroup_max_depth_write, 5611 }, 5612 { 5613 .name = "cgroup.stat", 5614 .seq_show = cgroup_stat_show, 5615 }, 5616 { 5617 .name = "cgroup.stat.local", 5618 .flags = CFTYPE_NOT_ON_ROOT, 5619 .seq_show = cgroup_core_local_stat_show, 5620 }, 5621 { 5622 .name = "cgroup.freeze", 5623 .flags = CFTYPE_NOT_ON_ROOT, 5624 .seq_show = cgroup_freeze_show, 5625 .write = cgroup_freeze_write, 5626 }, 5627 { 5628 .name = "cgroup.kill", 5629 .flags = CFTYPE_NOT_ON_ROOT, 5630 .write = cgroup_kill_write, 5631 }, 5632 { 5633 .name = "cpu.stat", 5634 .seq_show = cpu_stat_show, 5635 }, 5636 { 5637 .name = "cpu.stat.local", 5638 .seq_show = cpu_local_stat_show, 5639 }, 5640 { } /* terminate */ 5641 }; 5642 5643 static struct cftype cgroup_psi_files[] = { 5644 #ifdef CONFIG_PSI 5645 { 5646 .name = "io.pressure", 5647 .file_offset = offsetof(struct cgroup, psi_files[PSI_IO]), 5648 .seq_show = cgroup_io_pressure_show, 5649 .write = cgroup_io_pressure_write, 5650 .poll = cgroup_pressure_poll, 5651 .release = cgroup_pressure_release, 5652 }, 5653 { 5654 .name = "memory.pressure", 5655 .file_offset = offsetof(struct cgroup, psi_files[PSI_MEM]), 5656 .seq_show = cgroup_memory_pressure_show, 5657 .write = cgroup_memory_pressure_write, 5658 .poll = cgroup_pressure_poll, 5659 .release = cgroup_pressure_release, 5660 }, 5661 { 5662 .name = "cpu.pressure", 5663 .file_offset = offsetof(struct cgroup, psi_files[PSI_CPU]), 5664 .seq_show = cgroup_cpu_pressure_show, 5665 .write = cgroup_cpu_pressure_write, 5666 .poll = cgroup_pressure_poll, 5667 .release = cgroup_pressure_release, 5668 }, 5669 #ifdef CONFIG_IRQ_TIME_ACCOUNTING 5670 { 5671 .name = "irq.pressure", 5672 .file_offset = offsetof(struct cgroup, psi_files[PSI_IRQ]), 5673 .seq_show = cgroup_irq_pressure_show, 5674 .write = cgroup_irq_pressure_write, 5675 .poll = cgroup_pressure_poll, 5676 .release = cgroup_pressure_release, 5677 }, 5678 #endif 5679 { 5680 .name = "cgroup.pressure", 5681 .seq_show = cgroup_pressure_show, 5682 .write = cgroup_pressure_write, 5683 }, 5684 #endif /* CONFIG_PSI */ 5685 { } /* terminate */ 5686 }; 5687 5688 /* 5689 * css destruction is four-stage process. 5690 * 5691 * 1. Destruction starts. Killing of the percpu_ref is initiated. 5692 * Implemented in kill_css_finish(). 5693 * 5694 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs 5695 * and thus css_tryget_online() is guaranteed to fail, the css can be 5696 * offlined by invoking offline_css(). After offlining, the base ref is 5697 * put. Implemented in css_killed_work_fn(). 5698 * 5699 * 3. When the percpu_ref reaches zero, the only possible remaining 5700 * accessors are inside RCU read sections. css_release() schedules the 5701 * RCU callback. 5702 * 5703 * 4. After the grace period, the css can be freed. Implemented in 5704 * css_free_rwork_fn(). 5705 * 5706 * It is actually hairier because both step 2 and 4 require process context 5707 * and thus involve punting to css->destroy_work adding two additional 5708 * steps to the already complex sequence. 5709 */ 5710 static void css_free_rwork_fn(struct work_struct *work) 5711 { 5712 struct cgroup_subsys_state *css = container_of(to_rcu_work(work), 5713 struct cgroup_subsys_state, destroy_rwork); 5714 struct cgroup_subsys *ss = css->ss; 5715 struct cgroup *cgrp = css->cgroup; 5716 5717 percpu_ref_exit(&css->refcnt); 5718 css_rstat_exit(css); 5719 5720 if (!css_is_self(css)) { 5721 /* css free path */ 5722 struct cgroup_subsys_state *parent = css->parent; 5723 int id = css->id; 5724 5725 ss->css_free(css); 5726 cgroup_idr_remove(&ss->css_idr, id); 5727 cgroup_put(cgrp); 5728 5729 if (parent) 5730 css_put(parent); 5731 } else { 5732 /* cgroup free path */ 5733 atomic_dec(&cgrp->root->nr_cgrps); 5734 if (!cgroup_on_dfl(cgrp)) 5735 cgroup1_pidlist_destroy_all(cgrp); 5736 cancel_work_sync(&cgrp->release_agent_work); 5737 bpf_cgrp_storage_free(cgrp); 5738 5739 if (cgroup_parent(cgrp)) { 5740 /* 5741 * We get a ref to the parent, and put the ref when 5742 * this cgroup is being freed, so it's guaranteed 5743 * that the parent won't be destroyed before its 5744 * children. 5745 */ 5746 cgroup_put(cgroup_parent(cgrp)); 5747 kernfs_put(cgrp->kn); 5748 psi_cgroup_free(cgrp); 5749 kfree(cgrp); 5750 } else { 5751 /* 5752 * This is root cgroup's refcnt reaching zero, 5753 * which indicates that the root should be 5754 * released. 5755 */ 5756 cgroup_destroy_root(cgrp->root); 5757 } 5758 } 5759 } 5760 5761 static void css_release_work_fn(struct work_struct *work) 5762 { 5763 struct cgroup_subsys_state *css = 5764 container_of(work, struct cgroup_subsys_state, destroy_work); 5765 struct cgroup_subsys *ss = css->ss; 5766 struct cgroup *cgrp = css->cgroup; 5767 5768 cgroup_lock(); 5769 5770 css->flags |= CSS_RELEASED; 5771 list_del_rcu(&css->sibling); 5772 5773 if (!css_is_self(css)) { 5774 struct cgroup *parent_cgrp; 5775 5776 css_rstat_flush(css); 5777 5778 cgroup_idr_replace(&ss->css_idr, NULL, css->id); 5779 if (ss->css_released) 5780 ss->css_released(css); 5781 5782 cgrp->nr_dying_subsys[ss->id]--; 5783 /* 5784 * When a css is released and ready to be freed, its 5785 * nr_descendants must be zero. However, the corresponding 5786 * cgrp->nr_dying_subsys[ss->id] may not be 0 if a subsystem 5787 * is activated and deactivated multiple times with one or 5788 * more of its previous activation leaving behind dying csses. 5789 */ 5790 WARN_ON_ONCE(css->nr_descendants); 5791 parent_cgrp = cgroup_parent(cgrp); 5792 while (parent_cgrp) { 5793 parent_cgrp->nr_dying_subsys[ss->id]--; 5794 parent_cgrp = cgroup_parent(parent_cgrp); 5795 } 5796 } else { 5797 struct cgroup *tcgrp; 5798 5799 /* cgroup release path */ 5800 TRACE_CGROUP_PATH(release, cgrp); 5801 5802 css_rstat_flush(&cgrp->self); 5803 5804 spin_lock_irq(&css_set_lock); 5805 for (tcgrp = cgroup_parent(cgrp); tcgrp; 5806 tcgrp = cgroup_parent(tcgrp)) 5807 tcgrp->nr_dying_descendants--; 5808 spin_unlock_irq(&css_set_lock); 5809 5810 /* 5811 * There are two control paths which try to determine 5812 * cgroup from dentry without going through kernfs - 5813 * cgroupstats_build() and css_tryget_online_from_dir(). 5814 * Those are supported by RCU protecting clearing of 5815 * cgrp->kn->priv backpointer. 5816 */ 5817 if (cgrp->kn) 5818 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, 5819 NULL); 5820 } 5821 5822 cgroup_unlock(); 5823 5824 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn); 5825 queue_rcu_work(cgroup_free_wq, &css->destroy_rwork); 5826 } 5827 5828 static void css_release(struct percpu_ref *ref) 5829 { 5830 struct cgroup_subsys_state *css = 5831 container_of(ref, struct cgroup_subsys_state, refcnt); 5832 5833 INIT_WORK(&css->destroy_work, css_release_work_fn); 5834 queue_work(cgroup_release_wq, &css->destroy_work); 5835 } 5836 5837 /* 5838 * Deferred kill_css_finish() fired from css_update_populated() once a dying 5839 * css's hierarchical populated state drops to zero. Pinned by css_get() at the 5840 * queue site; matched by css_put() here. 5841 */ 5842 static void kill_css_finish_work_fn(struct work_struct *work) 5843 { 5844 struct cgroup_subsys_state *css = 5845 container_of(work, struct cgroup_subsys_state, kill_finish_work); 5846 5847 cgroup_lock(); 5848 kill_css_finish(css); 5849 cgroup_unlock(); 5850 css_put(css); 5851 } 5852 5853 static void init_and_link_css(struct cgroup_subsys_state *css, 5854 struct cgroup_subsys *ss, struct cgroup *cgrp) 5855 { 5856 lockdep_assert_held(&cgroup_mutex); 5857 5858 cgroup_get_live(cgrp); 5859 5860 memset(css, 0, sizeof(*css)); 5861 css->cgroup = cgrp; 5862 css->ss = ss; 5863 css->id = -1; 5864 INIT_LIST_HEAD(&css->sibling); 5865 INIT_LIST_HEAD(&css->children); 5866 INIT_WORK(&css->kill_finish_work, kill_css_finish_work_fn); 5867 css->serial_nr = css_serial_nr_next++; 5868 atomic_set(&css->online_cnt, 0); 5869 5870 if (cgroup_parent(cgrp)) { 5871 css->parent = cgroup_css(cgroup_parent(cgrp), ss); 5872 css_get(css->parent); 5873 } 5874 5875 BUG_ON(cgroup_css(cgrp, ss)); 5876 } 5877 5878 static void cgroup_update_e_css(struct cgroup *cgrp, struct cgroup_subsys *ss) 5879 { 5880 struct cgroup_subsys_state *d_css; 5881 5882 lockdep_assert_held(&cgroup_mutex); 5883 5884 css_for_each_descendant_pre(d_css, &cgrp->self) { 5885 struct cgroup *dsct = d_css->cgroup; 5886 struct cgroup_subsys_state *css = cgroup_css(dsct, ss); 5887 5888 if (!css) 5889 css = cgroup_e_css(cgroup_parent(dsct), ss); 5890 rcu_assign_pointer(dsct->e_css[ss->id], css); 5891 } 5892 } 5893 5894 /* invoke ->css_online() on a new CSS and mark it online if successful */ 5895 static int online_css(struct cgroup_subsys_state *css) 5896 { 5897 struct cgroup_subsys *ss = css->ss; 5898 int ret = 0; 5899 5900 lockdep_assert_held(&cgroup_mutex); 5901 5902 if (ss->css_online) 5903 ret = ss->css_online(css); 5904 if (!ret) { 5905 css->flags |= CSS_ONLINE; 5906 rcu_assign_pointer(css->cgroup->subsys[ss->id], css); 5907 cgroup_update_e_css(css->cgroup, ss); 5908 5909 atomic_inc(&css->online_cnt); 5910 if (css->parent) { 5911 atomic_inc(&css->parent->online_cnt); 5912 while ((css = css->parent)) 5913 css->nr_descendants++; 5914 } 5915 } 5916 return ret; 5917 } 5918 5919 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */ 5920 static void offline_css(struct cgroup_subsys_state *css) 5921 { 5922 struct cgroup_subsys *ss = css->ss; 5923 5924 lockdep_assert_held(&cgroup_mutex); 5925 5926 if (!css_is_online(css)) 5927 return; 5928 5929 if (ss->css_offline) 5930 ss->css_offline(css); 5931 5932 css->flags &= ~CSS_ONLINE; 5933 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL); 5934 cgroup_update_e_css(css->cgroup, ss); 5935 5936 wake_up_all(&css->cgroup->offline_waitq); 5937 } 5938 5939 /** 5940 * css_create - create a cgroup_subsys_state 5941 * @cgrp: the cgroup new css will be associated with 5942 * @ss: the subsys of new css 5943 * 5944 * Create a new css associated with @cgrp - @ss pair. On success, the new 5945 * css is online and installed in @cgrp. This function doesn't create the 5946 * interface files. Returns 0 on success, -errno on failure. 5947 */ 5948 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp, 5949 struct cgroup_subsys *ss) 5950 { 5951 struct cgroup *parent = cgroup_parent(cgrp); 5952 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss); 5953 struct cgroup_subsys_state *css; 5954 int err; 5955 5956 lockdep_assert_held(&cgroup_mutex); 5957 5958 css = ss->css_alloc(parent_css); 5959 if (!css) 5960 css = ERR_PTR(-ENOMEM); 5961 if (IS_ERR(css)) 5962 return css; 5963 5964 init_and_link_css(css, ss, cgrp); 5965 5966 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL); 5967 if (err) 5968 goto err_free_css; 5969 5970 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL); 5971 if (err < 0) 5972 goto err_free_css; 5973 css->id = err; 5974 5975 err = css_rstat_init(css); 5976 if (err) 5977 goto err_free_css; 5978 5979 /* @css is ready to be brought online now, make it visible */ 5980 list_add_tail_rcu(&css->sibling, &parent_css->children); 5981 cgroup_idr_replace(&ss->css_idr, css, css->id); 5982 5983 err = online_css(css); 5984 if (err) 5985 goto err_list_del; 5986 5987 return css; 5988 5989 err_list_del: 5990 list_del_rcu(&css->sibling); 5991 err_free_css: 5992 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn); 5993 queue_rcu_work(cgroup_free_wq, &css->destroy_rwork); 5994 return ERR_PTR(err); 5995 } 5996 5997 /* 5998 * The returned cgroup is fully initialized including its control mask, but 5999 * it doesn't have the control mask applied. 6000 */ 6001 static struct cgroup *cgroup_create(struct cgroup *parent, const char *name, 6002 umode_t mode) 6003 { 6004 struct cgroup_root *root = parent->root; 6005 struct cgroup *cgrp, *tcgrp; 6006 struct cgroup_subsys *ss; 6007 struct kernfs_node *kn; 6008 int i, level = parent->level + 1; 6009 int ret; 6010 6011 /* allocate the cgroup and its ID, 0 is reserved for the root */ 6012 cgrp = kzalloc_flex(*cgrp, _low_ancestors, level); 6013 if (!cgrp) 6014 return ERR_PTR(-ENOMEM); 6015 6016 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL); 6017 if (ret) 6018 goto out_free_cgrp; 6019 6020 /* create the directory */ 6021 kn = kernfs_create_dir_ns(parent->kn, name, mode, 6022 current_fsuid(), current_fsgid(), 6023 cgrp, NULL); 6024 if (IS_ERR(kn)) { 6025 ret = PTR_ERR(kn); 6026 goto out_cancel_ref; 6027 } 6028 cgrp->kn = kn; 6029 6030 init_cgroup_housekeeping(cgrp); 6031 6032 cgrp->self.parent = &parent->self; 6033 cgrp->root = root; 6034 cgrp->level = level; 6035 6036 /* 6037 * Now that init_cgroup_housekeeping() has been called and cgrp->self 6038 * is setup, it is safe to perform rstat initialization on it. 6039 */ 6040 ret = css_rstat_init(&cgrp->self); 6041 if (ret) 6042 goto out_kernfs_remove; 6043 6044 ret = psi_cgroup_alloc(cgrp); 6045 if (ret) 6046 goto out_stat_exit; 6047 6048 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) 6049 cgrp->ancestors[tcgrp->level] = tcgrp; 6050 6051 for_each_subsys(ss, i) 6052 RCU_INIT_POINTER(cgrp->e_css[i], cgroup_e_css(parent, ss)); 6053 6054 /* 6055 * New cgroup inherits effective freeze counter, and 6056 * if the parent has to be frozen, the child has too. 6057 */ 6058 cgrp->freezer.e_freeze = parent->freezer.e_freeze; 6059 seqcount_spinlock_init(&cgrp->freezer.freeze_seq, &css_set_lock); 6060 if (cgrp->freezer.e_freeze) { 6061 /* 6062 * Set the CGRP_FREEZE flag, so when a process will be 6063 * attached to the child cgroup, it will become frozen. 6064 * At this point the new cgroup is unpopulated, so we can 6065 * consider it frozen immediately. 6066 */ 6067 set_bit(CGRP_FREEZE, &cgrp->flags); 6068 cgrp->freezer.freeze_start_nsec = ktime_get_ns(); 6069 set_bit(CGRP_FROZEN, &cgrp->flags); 6070 } 6071 6072 if (notify_on_release(parent)) 6073 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags); 6074 6075 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags)) 6076 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags); 6077 6078 cgrp->self.serial_nr = css_serial_nr_next++; 6079 6080 ret = blocking_notifier_call_chain_robust(&cgroup_lifetime_notifier, 6081 CGROUP_LIFETIME_ONLINE, 6082 CGROUP_LIFETIME_OFFLINE, cgrp); 6083 ret = notifier_to_errno(ret); 6084 if (ret) 6085 goto out_psi_free; 6086 6087 /* allocation complete, commit to creation */ 6088 spin_lock_irq(&css_set_lock); 6089 for (i = 0; i < level; i++) { 6090 tcgrp = cgrp->ancestors[i]; 6091 tcgrp->nr_descendants++; 6092 6093 /* 6094 * If the new cgroup is frozen, all ancestor cgroups get a new 6095 * frozen descendant, but their state can't change because of 6096 * this. 6097 */ 6098 if (cgrp->freezer.e_freeze) 6099 tcgrp->freezer.nr_frozen_descendants++; 6100 } 6101 spin_unlock_irq(&css_set_lock); 6102 6103 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children); 6104 atomic_inc(&root->nr_cgrps); 6105 cgroup_get_live(parent); 6106 6107 /* 6108 * On the default hierarchy, a child doesn't automatically inherit 6109 * subtree_control from the parent. Each is configured manually. 6110 */ 6111 if (!cgroup_on_dfl(cgrp)) 6112 cgrp->subtree_control = cgroup_control(cgrp); 6113 6114 cgroup_propagate_control(cgrp); 6115 6116 return cgrp; 6117 6118 out_psi_free: 6119 psi_cgroup_free(cgrp); 6120 out_stat_exit: 6121 css_rstat_exit(&cgrp->self); 6122 out_kernfs_remove: 6123 kernfs_remove(cgrp->kn); 6124 out_cancel_ref: 6125 percpu_ref_exit(&cgrp->self.refcnt); 6126 out_free_cgrp: 6127 kfree(cgrp); 6128 return ERR_PTR(ret); 6129 } 6130 6131 static bool cgroup_check_hierarchy_limits(struct cgroup *parent) 6132 { 6133 struct cgroup *cgroup; 6134 int ret = false; 6135 int level = 0; 6136 6137 lockdep_assert_held(&cgroup_mutex); 6138 6139 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) { 6140 if (cgroup->nr_descendants >= cgroup->max_descendants) 6141 goto fail; 6142 6143 if (level >= cgroup->max_depth) 6144 goto fail; 6145 6146 level++; 6147 } 6148 6149 ret = true; 6150 fail: 6151 return ret; 6152 } 6153 6154 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode) 6155 { 6156 struct cgroup *parent, *cgrp; 6157 int ret; 6158 6159 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */ 6160 if (strchr(name, '\n')) 6161 return -EINVAL; 6162 6163 parent = cgroup_kn_lock_live(parent_kn, false); 6164 if (IS_ERR(parent)) 6165 return PTR_ERR(parent); 6166 6167 if (!cgroup_check_hierarchy_limits(parent)) { 6168 ret = -EAGAIN; 6169 goto out_unlock; 6170 } 6171 6172 cgrp = cgroup_create(parent, name, mode); 6173 if (IS_ERR(cgrp)) { 6174 ret = PTR_ERR(cgrp); 6175 goto out_unlock; 6176 } 6177 6178 /* 6179 * This extra ref will be put in css_free_rwork_fn() and guarantees 6180 * that @cgrp->kn is always accessible. 6181 */ 6182 kernfs_get(cgrp->kn); 6183 6184 ret = css_populate_dir(&cgrp->self); 6185 if (ret) 6186 goto out_destroy; 6187 6188 ret = cgroup_apply_control_enable(cgrp); 6189 if (ret) 6190 goto out_destroy; 6191 6192 TRACE_CGROUP_PATH(mkdir, cgrp); 6193 6194 /* let's create and online css's */ 6195 kernfs_activate(cgrp->kn); 6196 6197 ret = 0; 6198 goto out_unlock; 6199 6200 out_destroy: 6201 cgroup_destroy_locked(cgrp); 6202 out_unlock: 6203 cgroup_kn_unlock(parent_kn); 6204 return ret; 6205 } 6206 6207 /* 6208 * This is called when the refcnt of a css is confirmed to be killed. 6209 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to 6210 * initiate destruction and put the css ref from kill_css_finish(). 6211 */ 6212 static void css_killed_work_fn(struct work_struct *work) 6213 { 6214 struct cgroup_subsys_state *css; 6215 6216 css = container_of(to_rcu_work(work), struct cgroup_subsys_state, destroy_rwork); 6217 6218 cgroup_lock(); 6219 6220 do { 6221 offline_css(css); 6222 css_put(css); 6223 /* @css can't go away while we're holding cgroup_mutex */ 6224 css = css->parent; 6225 } while (css && atomic_dec_and_test(&css->online_cnt)); 6226 6227 cgroup_unlock(); 6228 } 6229 6230 /* css kill confirmation processing requires process context, bounce */ 6231 static void css_killed_ref_fn(struct percpu_ref *ref) 6232 { 6233 struct cgroup_subsys_state *css = 6234 container_of(ref, struct cgroup_subsys_state, refcnt); 6235 6236 if (atomic_dec_and_test(&css->online_cnt)) { 6237 INIT_RCU_WORK(&css->destroy_rwork, css_killed_work_fn); 6238 queue_rcu_work(cgroup_offline_wq, &css->destroy_rwork); 6239 } 6240 } 6241 6242 /** 6243 * kill_css_sync - synchronous half of css teardown 6244 * @css: css being killed 6245 * 6246 * See cgroup_destroy_locked(). 6247 */ 6248 static void kill_css_sync(struct cgroup_subsys_state *css) 6249 { 6250 struct cgroup_subsys *ss = css->ss; 6251 6252 lockdep_assert_held(&cgroup_mutex); 6253 6254 if (css->flags & CSS_DYING) 6255 return; 6256 6257 /* 6258 * Call css_killed(), if defined, before setting the CSS_DYING flag 6259 */ 6260 if (css->ss->css_killed) 6261 css->ss->css_killed(css); 6262 6263 css->flags |= CSS_DYING; 6264 6265 /* 6266 * Pair with smp_mb() in css_update_populated(). Either our 6267 * caller observes the walker's decrement and fires 6268 * synchronously, or the walker observes CSS_DYING and queues. 6269 */ 6270 smp_mb(); 6271 6272 /* 6273 * This must happen before css is disassociated with its cgroup. 6274 * See seq_css() for details. 6275 */ 6276 css_clear_dir(css); 6277 6278 css->cgroup->nr_dying_subsys[ss->id]++; 6279 /* 6280 * Parent css and cgroup cannot be freed until after the freeing 6281 * of child css, see css_free_rwork_fn(). 6282 */ 6283 while ((css = css->parent)) { 6284 css->nr_descendants--; 6285 css->cgroup->nr_dying_subsys[ss->id]++; 6286 } 6287 } 6288 6289 /** 6290 * kill_css_finish - deferred half of css teardown 6291 * @css: css being killed 6292 * 6293 * See cgroup_destroy_locked(). 6294 */ 6295 static void kill_css_finish(struct cgroup_subsys_state *css) 6296 { 6297 lockdep_assert_held(&cgroup_mutex); 6298 6299 /* 6300 * Skip on re-entry: cgroup_apply_control_disable() may have killed @css 6301 * earlier. cgroup_destroy_locked() can still walk it because 6302 * offline_css() (which NULLs cgrp->subsys[ssid]) runs async. 6303 */ 6304 if (percpu_ref_is_dying(&css->refcnt)) 6305 return; 6306 6307 /* 6308 * Killing would put the base ref, but we need to keep it alive until 6309 * after ->css_offline(). 6310 */ 6311 css_get(css); 6312 6313 /* 6314 * cgroup core guarantees that, by the time ->css_offline() is invoked, 6315 * no new css reference will be given out via css_tryget_online(). We 6316 * can't simply call percpu_ref_kill() and proceed to offlining css's 6317 * because percpu_ref_kill() doesn't guarantee that the ref is seen as 6318 * killed on all CPUs on return. 6319 * 6320 * Use percpu_ref_kill_and_confirm() to get notifications as each css is 6321 * confirmed to be seen as killed on all CPUs. 6322 */ 6323 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn); 6324 } 6325 6326 /** 6327 * cgroup_destroy_locked - destroy @cgrp (called on rmdir) 6328 * @cgrp: cgroup to be destroyed 6329 * 6330 * Tear down @cgrp on behalf of rmdir. Constraints: 6331 * 6332 * - Userspace: rmdir must succeed when cgroup.procs and friends are empty. 6333 * 6334 * - Kernel: subsystem ->css_offline() must not run while any task in @cgrp's 6335 * subtree is still doing kernel work. A task hidden from cgroup.procs (past 6336 * exit_signals() with signal->live cleared) can still schedule, allocate, and 6337 * consume resources until its final context switch. Dying descendants in the 6338 * subtree can host such tasks too. 6339 * 6340 * - Kernel: css_tryget_online() must fail by the time ->css_offline() runs. 6341 * 6342 * The destruction runs in three parts: 6343 * 6344 * - This function: synchronous user-visible state teardown plus kill_css_sync() 6345 * on each subsystem css. 6346 * 6347 * - For each subsys css: fire kill_css_finish() synchronously if the subtree is 6348 * already drained, otherwise rely on css_update_populated() to queue 6349 * kill_finish_work when the last populated cset under the css empties. 6350 * 6351 * - The percpu_ref kill chain: css_killed_ref_fn -> css_killed_work_fn -> 6352 * ->css_offline() -> release/free. 6353 * 6354 * Return 0 on success, -EBUSY if a userspace-visible task or an online child 6355 * remains. 6356 */ 6357 static int cgroup_destroy_locked(struct cgroup *cgrp) 6358 { 6359 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp); 6360 struct cgroup_subsys_state *css; 6361 struct cgrp_cset_link *link; 6362 struct css_task_iter it; 6363 struct task_struct *task; 6364 int ssid, ret; 6365 6366 lockdep_assert_held(&cgroup_mutex); 6367 6368 css_task_iter_start(&cgrp->self, 0, &it); 6369 task = css_task_iter_next(&it); 6370 css_task_iter_end(&it); 6371 if (task) 6372 return -EBUSY; 6373 6374 /* 6375 * Make sure there's no live children. We can't test emptiness of 6376 * ->self.children as dead children linger on it while being 6377 * drained; otherwise, "rmdir parent/child parent" may fail. 6378 */ 6379 if (css_has_online_children(&cgrp->self)) 6380 return -EBUSY; 6381 6382 /* 6383 * Mark @cgrp and the associated csets dead. The former prevents 6384 * further task migration and child creation by disabling 6385 * cgroup_kn_lock_live(). The latter makes the csets ignored by 6386 * the migration path. 6387 */ 6388 cgrp->self.flags &= ~CSS_ONLINE; 6389 6390 spin_lock_irq(&css_set_lock); 6391 list_for_each_entry(link, &cgrp->cset_links, cset_link) 6392 link->cset->dead = true; 6393 spin_unlock_irq(&css_set_lock); 6394 6395 for_each_css(css, ssid, cgrp) 6396 kill_css_sync(css); 6397 6398 /* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */ 6399 css_clear_dir(&cgrp->self); 6400 kernfs_remove(cgrp->kn); 6401 6402 if (cgroup_is_threaded(cgrp)) 6403 parent->nr_threaded_children--; 6404 6405 spin_lock_irq(&css_set_lock); 6406 for (tcgrp = parent; tcgrp; tcgrp = cgroup_parent(tcgrp)) { 6407 tcgrp->nr_descendants--; 6408 tcgrp->nr_dying_descendants++; 6409 /* 6410 * If the dying cgroup is frozen, decrease frozen descendants 6411 * counters of ancestor cgroups. 6412 */ 6413 if (test_bit(CGRP_FROZEN, &cgrp->flags)) 6414 tcgrp->freezer.nr_frozen_descendants--; 6415 } 6416 spin_unlock_irq(&css_set_lock); 6417 6418 cgroup1_check_for_release(parent); 6419 6420 ret = blocking_notifier_call_chain(&cgroup_lifetime_notifier, 6421 CGROUP_LIFETIME_OFFLINE, cgrp); 6422 WARN_ON_ONCE(notifier_to_errno(ret)); 6423 6424 /* put the base reference */ 6425 percpu_ref_kill(&cgrp->self.refcnt); 6426 6427 for_each_css(css, ssid, cgrp) { 6428 if (!css_is_populated(css)) 6429 kill_css_finish(css); 6430 } 6431 6432 return 0; 6433 }; 6434 6435 int cgroup_rmdir(struct kernfs_node *kn) 6436 { 6437 struct cgroup *cgrp; 6438 int ret = 0; 6439 6440 cgrp = cgroup_kn_lock_live(kn, false); 6441 if (IS_ERR(cgrp)) 6442 return 0; 6443 6444 ret = cgroup_destroy_locked(cgrp); 6445 if (!ret) 6446 TRACE_CGROUP_PATH(rmdir, cgrp); 6447 6448 cgroup_kn_unlock(kn); 6449 return ret; 6450 } 6451 6452 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = { 6453 .show_options = cgroup_show_options, 6454 .mkdir = cgroup_mkdir, 6455 .rmdir = cgroup_rmdir, 6456 .show_path = cgroup_show_path, 6457 }; 6458 6459 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early) 6460 { 6461 struct cgroup_subsys_state *css; 6462 6463 pr_debug("Initializing cgroup subsys %s\n", ss->name); 6464 6465 cgroup_lock(); 6466 6467 idr_init(&ss->css_idr); 6468 INIT_LIST_HEAD(&ss->cfts); 6469 6470 /* Create the root cgroup state for this subsystem */ 6471 ss->root = &cgrp_dfl_root; 6472 css = ss->css_alloc(NULL); 6473 /* We don't handle early failures gracefully */ 6474 BUG_ON(IS_ERR(css)); 6475 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp); 6476 6477 /* 6478 * Root csses are never destroyed and we can't initialize 6479 * percpu_ref during early init. Disable refcnting. 6480 */ 6481 css->flags |= CSS_NO_REF; 6482 6483 if (early) { 6484 /* allocation can't be done safely during early init */ 6485 css->id = 1; 6486 } else { 6487 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL); 6488 BUG_ON(css->id < 0); 6489 6490 BUG_ON(ss_rstat_init(ss)); 6491 BUG_ON(css_rstat_init(css)); 6492 } 6493 6494 /* Update the init_css_set to contain a subsys 6495 * pointer to this state - since the subsystem is 6496 * newly registered, all tasks and hence the 6497 * init_css_set is in the subsystem's root cgroup. */ 6498 init_css_set.subsys[ss->id] = css; 6499 6500 have_fork_callback |= (bool)ss->fork << ss->id; 6501 have_exit_callback |= (bool)ss->exit << ss->id; 6502 have_release_callback |= (bool)ss->release << ss->id; 6503 have_canfork_callback |= (bool)ss->can_fork << ss->id; 6504 6505 /* At system boot, before all subsystems have been 6506 * registered, no tasks have been forked, so we don't 6507 * need to invoke fork callbacks here. */ 6508 BUG_ON(!list_empty(&init_task.tasks)); 6509 6510 BUG_ON(online_css(css)); 6511 6512 cgroup_unlock(); 6513 } 6514 6515 /** 6516 * cgroup_init_early - cgroup initialization at system boot 6517 * 6518 * Initialize cgroups at system boot, and initialize any 6519 * subsystems that request early init. 6520 */ 6521 int __init cgroup_init_early(void) 6522 { 6523 static struct cgroup_fs_context __initdata ctx; 6524 struct cgroup_subsys *ss; 6525 int i; 6526 6527 ctx.root = &cgrp_dfl_root; 6528 init_cgroup_root(&ctx); 6529 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF; 6530 6531 RCU_INIT_POINTER(init_task.cgroups, &init_css_set); 6532 6533 for_each_subsys(ss, i) { 6534 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id, 6535 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n", 6536 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free, 6537 ss->id, ss->name); 6538 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN, 6539 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]); 6540 WARN(ss->early_init && ss->css_rstat_flush, 6541 "cgroup rstat cannot be used with early init subsystem\n"); 6542 6543 ss->id = i; 6544 ss->name = cgroup_subsys_name[i]; 6545 if (!ss->legacy_name) 6546 ss->legacy_name = cgroup_subsys_name[i]; 6547 6548 if (ss->early_init) 6549 cgroup_init_subsys(ss, true); 6550 } 6551 return 0; 6552 } 6553 6554 /** 6555 * cgroup_init - cgroup initialization 6556 * 6557 * Register cgroup filesystem and /proc file, and initialize 6558 * any subsystems that didn't request early init. 6559 */ 6560 int __init cgroup_init(void) 6561 { 6562 struct cgroup_subsys *ss; 6563 int ssid; 6564 6565 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 32); 6566 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files)); 6567 BUG_ON(cgroup_init_cftypes(NULL, cgroup_psi_files)); 6568 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files)); 6569 6570 BUG_ON(ss_rstat_init(NULL)); 6571 6572 get_user_ns(init_cgroup_ns.user_ns); 6573 cgroup_rt_init(); 6574 6575 cgroup_lock(); 6576 6577 /* 6578 * Add init_css_set to the hash table so that dfl_root can link to 6579 * it during init. 6580 */ 6581 hash_add(css_set_table, &init_css_set.hlist, 6582 css_set_hash(init_css_set.subsys)); 6583 6584 cgroup_bpf_lifetime_notifier_init(); 6585 6586 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0)); 6587 6588 cgroup_unlock(); 6589 6590 for_each_subsys(ss, ssid) { 6591 if (ss->early_init) { 6592 struct cgroup_subsys_state *css = 6593 init_css_set.subsys[ss->id]; 6594 6595 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, 6596 GFP_KERNEL); 6597 BUG_ON(css->id < 0); 6598 } else { 6599 cgroup_init_subsys(ss, false); 6600 } 6601 6602 list_add_tail(&init_css_set.e_cset_node[ssid], 6603 &cgrp_dfl_root.cgrp.e_csets[ssid]); 6604 6605 /* 6606 * Setting dfl_root subsys_mask needs to consider the 6607 * disabled flag and cftype registration needs kmalloc, 6608 * both of which aren't available during early_init. 6609 */ 6610 if (!cgroup_ssid_enabled(ssid)) 6611 continue; 6612 6613 if (cgroup1_ssid_disabled(ssid)) 6614 pr_info("Disabling %s control group subsystem in v1 mounts\n", 6615 ss->legacy_name); 6616 6617 cgrp_dfl_root.subsys_mask |= 1 << ss->id; 6618 6619 /* implicit controllers must be threaded too */ 6620 WARN_ON(ss->implicit_on_dfl && !ss->threaded); 6621 6622 if (ss->implicit_on_dfl) 6623 cgrp_dfl_implicit_ss_mask |= 1 << ss->id; 6624 else if (!ss->dfl_cftypes) 6625 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id; 6626 6627 if (ss->threaded) 6628 cgrp_dfl_threaded_ss_mask |= 1 << ss->id; 6629 6630 if (ss->dfl_cftypes == ss->legacy_cftypes) { 6631 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes)); 6632 } else { 6633 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes)); 6634 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes)); 6635 } 6636 6637 if (ss->bind) 6638 ss->bind(init_css_set.subsys[ssid]); 6639 6640 cgroup_lock(); 6641 css_populate_dir(init_css_set.subsys[ssid]); 6642 cgroup_unlock(); 6643 } 6644 6645 /* init_css_set.subsys[] has been updated, re-hash */ 6646 hash_del(&init_css_set.hlist); 6647 hash_add(css_set_table, &init_css_set.hlist, 6648 css_set_hash(init_css_set.subsys)); 6649 6650 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup")); 6651 WARN_ON(register_filesystem(&cgroup_fs_type)); 6652 WARN_ON(register_filesystem(&cgroup2_fs_type)); 6653 WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show)); 6654 #ifdef CONFIG_CPUSETS_V1 6655 WARN_ON(register_filesystem(&cpuset_fs_type)); 6656 #endif 6657 6658 ns_tree_add(&init_cgroup_ns); 6659 return 0; 6660 } 6661 6662 static int __init cgroup_wq_init(void) 6663 { 6664 /* 6665 * There isn't much point in executing destruction path in 6666 * parallel. Good chunk is serialized with cgroup_mutex anyway. 6667 * Use 1 for @max_active. 6668 * 6669 * We would prefer to do this in cgroup_init() above, but that 6670 * is called before init_workqueues(): so leave this until after. 6671 */ 6672 cgroup_offline_wq = alloc_workqueue("cgroup_offline", WQ_PERCPU, 1); 6673 BUG_ON(!cgroup_offline_wq); 6674 6675 cgroup_release_wq = alloc_workqueue("cgroup_release", WQ_PERCPU, 1); 6676 BUG_ON(!cgroup_release_wq); 6677 6678 cgroup_free_wq = alloc_workqueue("cgroup_free", WQ_PERCPU, 1); 6679 BUG_ON(!cgroup_free_wq); 6680 return 0; 6681 } 6682 core_initcall(cgroup_wq_init); 6683 6684 void cgroup_path_from_kernfs_id(u64 id, char *buf, size_t buflen) 6685 { 6686 struct kernfs_node *kn; 6687 6688 kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id); 6689 if (!kn) 6690 return; 6691 kernfs_path(kn, buf, buflen); 6692 kernfs_put(kn); 6693 } 6694 6695 /* 6696 * __cgroup_get_from_id : get the cgroup associated with cgroup id 6697 * @id: cgroup id 6698 * On success return the cgrp or ERR_PTR on failure 6699 * There are no cgroup NS restrictions. 6700 */ 6701 struct cgroup *__cgroup_get_from_id(u64 id) 6702 { 6703 struct kernfs_node *kn; 6704 struct cgroup *cgrp; 6705 6706 kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id); 6707 if (!kn) 6708 return ERR_PTR(-ENOENT); 6709 6710 if (kernfs_type(kn) != KERNFS_DIR) { 6711 kernfs_put(kn); 6712 return ERR_PTR(-ENOENT); 6713 } 6714 6715 rcu_read_lock(); 6716 6717 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv); 6718 if (cgrp && !cgroup_tryget(cgrp)) 6719 cgrp = NULL; 6720 6721 rcu_read_unlock(); 6722 kernfs_put(kn); 6723 6724 if (!cgrp) 6725 return ERR_PTR(-ENOENT); 6726 return cgrp; 6727 } 6728 6729 /* 6730 * cgroup_get_from_id : get the cgroup associated with cgroup id 6731 * @id: cgroup id 6732 * On success return the cgrp or ERR_PTR on failure 6733 * Only cgroups within current task's cgroup NS are valid. 6734 */ 6735 struct cgroup *cgroup_get_from_id(u64 id) 6736 { 6737 struct cgroup *cgrp, *root_cgrp; 6738 6739 cgrp = __cgroup_get_from_id(id); 6740 if (IS_ERR(cgrp)) 6741 return cgrp; 6742 6743 root_cgrp = current_cgns_cgroup_dfl(); 6744 if (!cgroup_is_descendant(cgrp, root_cgrp)) { 6745 cgroup_put(cgrp); 6746 return ERR_PTR(-ENOENT); 6747 } 6748 6749 return cgrp; 6750 } 6751 EXPORT_SYMBOL_GPL(cgroup_get_from_id); 6752 6753 /* 6754 * proc_cgroup_show() 6755 * - Print task's cgroup paths into seq_file, one line for each hierarchy 6756 * - Used for /proc/<pid>/cgroup. 6757 */ 6758 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns, 6759 struct pid *pid, struct task_struct *tsk) 6760 { 6761 char *buf; 6762 int retval; 6763 struct cgroup_root *root; 6764 6765 retval = -ENOMEM; 6766 buf = kmalloc(PATH_MAX, GFP_KERNEL); 6767 if (!buf) 6768 goto out; 6769 6770 rcu_read_lock(); 6771 spin_lock_irq(&css_set_lock); 6772 6773 for_each_root(root) { 6774 struct cgroup_subsys *ss; 6775 struct cgroup *cgrp; 6776 int ssid, count = 0; 6777 6778 if (root == &cgrp_dfl_root && !READ_ONCE(cgrp_dfl_visible)) 6779 continue; 6780 6781 cgrp = task_cgroup_from_root(tsk, root); 6782 /* The root has already been unmounted. */ 6783 if (!cgrp) 6784 continue; 6785 6786 seq_printf(m, "%d:", root->hierarchy_id); 6787 if (root != &cgrp_dfl_root) 6788 for_each_subsys(ss, ssid) 6789 if (root->subsys_mask & (1 << ssid)) 6790 seq_printf(m, "%s%s", count++ ? "," : "", 6791 ss->legacy_name); 6792 if (strlen(root->name)) 6793 seq_printf(m, "%sname=%s", count ? "," : "", 6794 root->name); 6795 seq_putc(m, ':'); 6796 /* 6797 * On traditional hierarchies, all zombie tasks show up as 6798 * belonging to the root cgroup. On the default hierarchy, 6799 * while a zombie doesn't show up in "cgroup.procs" and 6800 * thus can't be migrated, its /proc/PID/cgroup keeps 6801 * reporting the cgroup it belonged to before exiting. If 6802 * the cgroup is removed before the zombie is reaped, 6803 * " (deleted)" is appended to the cgroup path. 6804 */ 6805 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) { 6806 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX, 6807 current->nsproxy->cgroup_ns); 6808 if (retval == -E2BIG) 6809 retval = -ENAMETOOLONG; 6810 if (retval < 0) 6811 goto out_unlock; 6812 6813 seq_puts(m, buf); 6814 } else { 6815 seq_puts(m, "/"); 6816 } 6817 6818 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp)) 6819 seq_puts(m, " (deleted)\n"); 6820 else 6821 seq_putc(m, '\n'); 6822 } 6823 6824 retval = 0; 6825 out_unlock: 6826 spin_unlock_irq(&css_set_lock); 6827 rcu_read_unlock(); 6828 kfree(buf); 6829 out: 6830 return retval; 6831 } 6832 6833 /** 6834 * cgroup_fork - initialize cgroup related fields during copy_process() 6835 * @child: pointer to task_struct of forking parent process. 6836 * 6837 * A task is associated with the init_css_set until cgroup_post_fork() 6838 * attaches it to the target css_set. 6839 */ 6840 void cgroup_fork(struct task_struct *child) 6841 { 6842 RCU_INIT_POINTER(child->cgroups, &init_css_set); 6843 INIT_LIST_HEAD(&child->cg_list); 6844 } 6845 6846 /** 6847 * cgroup_v1v2_get_from_file - get a cgroup pointer from a file pointer 6848 * @f: file corresponding to cgroup_dir 6849 * 6850 * Find the cgroup from a file pointer associated with a cgroup directory. 6851 * Returns a pointer to the cgroup on success. ERR_PTR is returned if the 6852 * cgroup cannot be found. 6853 */ 6854 static struct cgroup *cgroup_v1v2_get_from_file(struct file *f) 6855 { 6856 struct cgroup_subsys_state *css; 6857 6858 css = css_tryget_online_from_dir(f->f_path.dentry, NULL); 6859 if (IS_ERR(css)) 6860 return ERR_CAST(css); 6861 6862 return css->cgroup; 6863 } 6864 6865 /** 6866 * cgroup_get_from_file - same as cgroup_v1v2_get_from_file, but only supports 6867 * cgroup2. 6868 * @f: file corresponding to cgroup2_dir 6869 */ 6870 static struct cgroup *cgroup_get_from_file(struct file *f) 6871 { 6872 struct cgroup *cgrp = cgroup_v1v2_get_from_file(f); 6873 6874 if (IS_ERR(cgrp)) 6875 return ERR_CAST(cgrp); 6876 6877 if (!cgroup_on_dfl(cgrp)) { 6878 cgroup_put(cgrp); 6879 return ERR_PTR(-EBADF); 6880 } 6881 6882 return cgrp; 6883 } 6884 6885 /* 6886 * A new threadgroup gets its own cgroup_threadgroup_rwsem. Once its PID is 6887 * visible, a cgroup.procs writer can find the child and lock that rwsem even 6888 * though cgroup_post_fork() has not linked the child to its css_set yet. 6889 * 6890 * cgroup_can_fork() already holds the global read lock, which keeps 6891 * cgroup_enable_per_threadgroup_rwsem stable. Lock the child's rwsem as a 6892 * nested instance until cgroup_post_fork() finishes. Threads share their 6893 * parent's signal_struct and are covered by the existing read lock. 6894 */ 6895 static void cgroup_fork_child_lock(struct task_struct *child) 6896 { 6897 if (cgroup_enable_per_threadgroup_rwsem && 6898 child->signal != current->signal) 6899 down_read_nested(&child->signal->cgroup_threadgroup_rwsem, 6900 SINGLE_DEPTH_NESTING); 6901 } 6902 6903 static void cgroup_fork_child_unlock(struct task_struct *child) 6904 { 6905 if (cgroup_enable_per_threadgroup_rwsem && 6906 child->signal != current->signal) 6907 up_read(&child->signal->cgroup_threadgroup_rwsem); 6908 } 6909 6910 /** 6911 * cgroup_css_set_fork - find or create a css_set for a child process 6912 * @kargs: the arguments passed to create the child process 6913 * 6914 * This functions finds or creates a new css_set which the child 6915 * process will be attached to in cgroup_post_fork(). By default, 6916 * the child process will be given the same css_set as its parent. 6917 * 6918 * If CLONE_INTO_CGROUP is specified this function will try to find an 6919 * existing css_set which includes the requested cgroup and if not create 6920 * a new css_set that the child will be attached to later. If this function 6921 * succeeds it will hold cgroup_threadgroup_rwsem on return. If 6922 * CLONE_INTO_CGROUP is requested this function will grab cgroup mutex 6923 * before grabbing cgroup_threadgroup_rwsem and will hold a reference 6924 * to the target cgroup. 6925 */ 6926 static int cgroup_css_set_fork(struct kernel_clone_args *kargs) 6927 __acquires(&cgroup_mutex) __acquires(&cgroup_threadgroup_rwsem) 6928 { 6929 int ret; 6930 struct cgroup *dst_cgrp = NULL; 6931 struct css_set *cset; 6932 struct super_block *sb; 6933 6934 if (kargs->flags & CLONE_INTO_CGROUP) 6935 cgroup_lock(); 6936 6937 cgroup_threadgroup_change_begin(current); 6938 6939 spin_lock_irq(&css_set_lock); 6940 cset = task_css_set(current); 6941 get_css_set(cset); 6942 kargs->kill_seq = cset->dfl_cgrp->kill_seq; 6943 spin_unlock_irq(&css_set_lock); 6944 6945 if (!(kargs->flags & CLONE_INTO_CGROUP)) { 6946 kargs->cset = cset; 6947 return 0; 6948 } 6949 6950 CLASS(fd_raw, f)(kargs->cgroup); 6951 if (fd_empty(f)) { 6952 ret = -EBADF; 6953 goto err; 6954 } 6955 sb = fd_file(f)->f_path.dentry->d_sb; 6956 6957 dst_cgrp = cgroup_get_from_file(fd_file(f)); 6958 if (IS_ERR(dst_cgrp)) { 6959 ret = PTR_ERR(dst_cgrp); 6960 dst_cgrp = NULL; 6961 goto err; 6962 } 6963 6964 if (cgroup_is_dead(dst_cgrp)) { 6965 ret = -ENODEV; 6966 goto err; 6967 } 6968 6969 /* 6970 * Verify that we the target cgroup is writable for us. This is 6971 * usually done by the vfs layer but since we're not going through 6972 * the vfs layer here we need to do it "manually". 6973 */ 6974 ret = cgroup_may_write(dst_cgrp, sb); 6975 if (ret) 6976 goto err; 6977 6978 /* 6979 * Spawning a task directly into a cgroup works by passing a file 6980 * descriptor to the target cgroup directory. This can even be an O_PATH 6981 * file descriptor. But it can never be a cgroup.procs file descriptor. 6982 * This was done on purpose so spawning into a cgroup could be 6983 * conceptualized as an atomic 6984 * 6985 * fd = openat(dfd_cgroup, "cgroup.procs", ...); 6986 * write(fd, <child-pid>, ...); 6987 * 6988 * sequence, i.e. it's a shorthand for the caller opening and writing 6989 * cgroup.procs of the cgroup indicated by @dfd_cgroup. This allows us 6990 * to always use the caller's credentials. 6991 */ 6992 ret = cgroup_attach_permissions(cset->dfl_cgrp, dst_cgrp, sb, 6993 !(kargs->flags & CLONE_THREAD), 6994 current->nsproxy->cgroup_ns); 6995 if (ret) 6996 goto err; 6997 6998 kargs->cset = find_css_set(cset, dst_cgrp); 6999 if (!kargs->cset) { 7000 ret = -ENOMEM; 7001 goto err; 7002 } 7003 7004 put_css_set(cset); 7005 kargs->cgrp = dst_cgrp; 7006 kargs->kill_seq = dst_cgrp->kill_seq; 7007 return ret; 7008 7009 err: 7010 cgroup_threadgroup_change_end(current); 7011 cgroup_unlock(); 7012 if (dst_cgrp) 7013 cgroup_put(dst_cgrp); 7014 put_css_set(cset); 7015 if (kargs->cset) 7016 put_css_set(kargs->cset); 7017 return ret; 7018 } 7019 7020 /** 7021 * cgroup_css_set_put_fork - drop references we took during fork 7022 * @kargs: the arguments passed to create the child process 7023 * 7024 * Drop references to the prepared css_set and target cgroup if 7025 * CLONE_INTO_CGROUP was requested. 7026 */ 7027 static void cgroup_css_set_put_fork(struct kernel_clone_args *kargs) 7028 __releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex) 7029 { 7030 struct cgroup *cgrp = kargs->cgrp; 7031 struct css_set *cset = kargs->cset; 7032 7033 cgroup_threadgroup_change_end(current); 7034 7035 if (cset) { 7036 put_css_set(cset); 7037 kargs->cset = NULL; 7038 } 7039 7040 if (kargs->flags & CLONE_INTO_CGROUP) { 7041 cgroup_unlock(); 7042 if (cgrp) { 7043 cgroup_put(cgrp); 7044 kargs->cgrp = NULL; 7045 } 7046 } 7047 } 7048 7049 /** 7050 * cgroup_can_fork - called on a new task before the process is exposed 7051 * @child: the child process 7052 * @kargs: the arguments passed to create the child process 7053 * 7054 * This prepares a new css_set for the child process which the child will 7055 * be attached to in cgroup_post_fork(). 7056 * This calls the subsystem can_fork() callbacks. If the cgroup_can_fork() 7057 * callback returns an error, the fork aborts with that error code. This 7058 * allows for a cgroup subsystem to conditionally allow or deny new forks. 7059 */ 7060 int cgroup_can_fork(struct task_struct *child, struct kernel_clone_args *kargs) 7061 { 7062 struct cgroup_subsys *ss; 7063 int i, j, ret; 7064 7065 ret = cgroup_css_set_fork(kargs); 7066 if (ret) 7067 return ret; 7068 7069 do_each_subsys_mask(ss, i, have_canfork_callback) { 7070 ret = ss->can_fork(child, kargs->cset); 7071 if (ret) 7072 goto out_revert; 7073 } while_each_subsys_mask(); 7074 7075 cgroup_fork_child_lock(child); 7076 return 0; 7077 7078 out_revert: 7079 for_each_subsys(ss, j) { 7080 if (j >= i) 7081 break; 7082 if (ss->cancel_fork) 7083 ss->cancel_fork(child, kargs->cset); 7084 } 7085 7086 cgroup_css_set_put_fork(kargs); 7087 7088 return ret; 7089 } 7090 7091 /** 7092 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork() 7093 * @child: the child process 7094 * @kargs: the arguments passed to create the child process 7095 * 7096 * This calls the cancel_fork() callbacks if a fork failed *after* 7097 * cgroup_can_fork() succeeded and cleans up references we took to 7098 * prepare a new css_set for the child process in cgroup_can_fork(). 7099 */ 7100 void cgroup_cancel_fork(struct task_struct *child, 7101 struct kernel_clone_args *kargs) 7102 { 7103 struct cgroup_subsys *ss; 7104 int i; 7105 7106 for_each_subsys(ss, i) 7107 if (ss->cancel_fork) 7108 ss->cancel_fork(child, kargs->cset); 7109 7110 cgroup_fork_child_unlock(child); 7111 cgroup_css_set_put_fork(kargs); 7112 } 7113 7114 /** 7115 * cgroup_post_fork - finalize cgroup setup for the child process 7116 * @child: the child process 7117 * @kargs: the arguments passed to create the child process 7118 * 7119 * Attach the child process to its css_set calling the subsystem fork() 7120 * callbacks. 7121 */ 7122 void cgroup_post_fork(struct task_struct *child, 7123 struct kernel_clone_args *kargs) 7124 __releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex) 7125 { 7126 unsigned int cgrp_kill_seq = 0; 7127 unsigned long cgrp_flags = 0; 7128 bool kill = false; 7129 struct cgroup_subsys *ss; 7130 struct css_set *cset; 7131 int i; 7132 7133 cset = kargs->cset; 7134 kargs->cset = NULL; 7135 7136 spin_lock_irq(&css_set_lock); 7137 7138 /* init tasks are special, only link regular threads */ 7139 if (likely(child->pid)) { 7140 if (kargs->cgrp) { 7141 cgrp_flags = kargs->cgrp->flags; 7142 cgrp_kill_seq = kargs->cgrp->kill_seq; 7143 } else { 7144 cgrp_flags = cset->dfl_cgrp->flags; 7145 cgrp_kill_seq = cset->dfl_cgrp->kill_seq; 7146 } 7147 7148 WARN_ON_ONCE(!list_empty(&child->cg_list)); 7149 cset->nr_tasks++; 7150 css_set_move_task(child, NULL, cset, false); 7151 } else { 7152 put_css_set(cset); 7153 cset = NULL; 7154 } 7155 7156 if (!(child->flags & PF_KTHREAD)) { 7157 if (unlikely(test_bit(CGRP_FREEZE, &cgrp_flags))) { 7158 /* 7159 * If the cgroup has to be frozen, the new task has 7160 * too. Let's set the JOBCTL_TRAP_FREEZE jobctl bit to 7161 * get the task into the frozen state. 7162 */ 7163 spin_lock(&child->sighand->siglock); 7164 WARN_ON_ONCE(child->frozen); 7165 child->jobctl |= JOBCTL_TRAP_FREEZE; 7166 spin_unlock(&child->sighand->siglock); 7167 7168 /* 7169 * Calling cgroup_update_frozen() isn't required here, 7170 * because it will be called anyway a bit later from 7171 * do_freezer_trap(). So we avoid cgroup's transient 7172 * switch from the frozen state and back. 7173 */ 7174 } 7175 7176 /* 7177 * If the cgroup is to be killed notice it now and take the 7178 * child down right after we finished preparing it for 7179 * userspace. 7180 */ 7181 kill = kargs->kill_seq != cgrp_kill_seq; 7182 } 7183 7184 spin_unlock_irq(&css_set_lock); 7185 7186 /* 7187 * Call ss->fork(). This must happen after @child is linked on 7188 * css_set; otherwise, @child might change state between ->fork() 7189 * and addition to css_set. 7190 */ 7191 do_each_subsys_mask(ss, i, have_fork_callback) { 7192 ss->fork(child); 7193 } while_each_subsys_mask(); 7194 7195 /* Make the new cset the root_cset of the new cgroup namespace. */ 7196 if (kargs->flags & CLONE_NEWCGROUP) { 7197 struct css_set *rcset = child->nsproxy->cgroup_ns->root_cset; 7198 7199 get_css_set(cset); 7200 child->nsproxy->cgroup_ns->root_cset = cset; 7201 put_css_set(rcset); 7202 } 7203 7204 /* Cgroup has to be killed so take down child immediately. */ 7205 if (unlikely(kill)) 7206 do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, child, PIDTYPE_TGID); 7207 7208 cgroup_fork_child_unlock(child); 7209 cgroup_css_set_put_fork(kargs); 7210 } 7211 7212 /** 7213 * cgroup_task_exit - detach cgroup from exiting task 7214 * @tsk: pointer to task_struct of exiting process 7215 * 7216 * Description: Detach cgroup from @tsk. 7217 * 7218 */ 7219 void cgroup_task_exit(struct task_struct *tsk) 7220 { 7221 struct cgroup_subsys *ss; 7222 int i; 7223 7224 /* see cgroup_post_fork() for details */ 7225 do_each_subsys_mask(ss, i, have_exit_callback) { 7226 ss->exit(tsk); 7227 } while_each_subsys_mask(); 7228 } 7229 7230 static void do_cgroup_task_dead(struct task_struct *tsk) 7231 { 7232 struct css_set *cset; 7233 unsigned long flags; 7234 7235 spin_lock_irqsave(&css_set_lock, flags); 7236 7237 WARN_ON_ONCE(list_empty(&tsk->cg_list)); 7238 cset = task_css_set(tsk); 7239 css_set_move_task(tsk, cset, NULL, false); 7240 cset->nr_tasks--; 7241 /* matches the signal->live check in css_task_iter_advance() */ 7242 if (thread_group_leader(tsk) && atomic_read(&tsk->signal->live)) 7243 list_add_tail(&tsk->cg_list, &cset->dying_tasks); 7244 7245 if (dl_task(tsk)) 7246 dec_dl_tasks_cs(tsk); 7247 7248 WARN_ON_ONCE(cgroup_task_frozen(tsk)); 7249 if (unlikely(!(tsk->flags & PF_KTHREAD) && 7250 test_bit(CGRP_FREEZE, &task_dfl_cgroup(tsk)->flags))) 7251 cgroup_update_frozen(task_dfl_cgroup(tsk)); 7252 7253 spin_unlock_irqrestore(&css_set_lock, flags); 7254 } 7255 7256 #ifdef CONFIG_PREEMPT_RT 7257 /* 7258 * cgroup_task_dead() is called from finish_task_switch() which doesn't allow 7259 * scheduling even in RT. As the task_dead path requires grabbing css_set_lock, 7260 * this lead to sleeping in the invalid context warning bug. css_set_lock is too 7261 * big to become a raw_spinlock. The task_dead path doesn't need to run 7262 * synchronously but can't be delayed indefinitely either as the dead task pins 7263 * the cgroup and task_struct can be pinned indefinitely. Bounce through lazy 7264 * irq_work to allow batching while ensuring timely completion. 7265 */ 7266 struct cgroup_dead { 7267 struct irq_work iwork; 7268 struct llist_head tasks; 7269 }; 7270 static DEFINE_PER_CPU(struct cgroup_dead, cgroup_dead); 7271 7272 static void cgrp_dead_tasks_iwork_fn(struct irq_work *iwork) 7273 { 7274 struct cgroup_dead *cgrp_dead = container_of(iwork, struct cgroup_dead, iwork); 7275 struct llist_node *lnode; 7276 struct task_struct *task, *next; 7277 7278 lnode = llist_del_all(&cgrp_dead->tasks); 7279 llist_for_each_entry_safe(task, next, lnode, cg_dead_lnode) { 7280 do_cgroup_task_dead(task); 7281 put_task_struct(task); 7282 } 7283 } 7284 7285 static void __init cgroup_rt_init(void) 7286 { 7287 int cpu; 7288 7289 for_each_possible_cpu(cpu) { 7290 struct cgroup_dead *cgrp_dead = per_cpu_ptr(&cgroup_dead, cpu); 7291 7292 init_llist_head(&cgrp_dead->tasks); 7293 cgrp_dead->iwork = IRQ_WORK_INIT_LAZY(cgrp_dead_tasks_iwork_fn); 7294 } 7295 } 7296 7297 void cgroup_task_dead(struct task_struct *task) 7298 { 7299 struct cgroup_dead *cgrp_dead = this_cpu_ptr(&cgroup_dead); 7300 7301 get_task_struct(task); 7302 llist_add(&task->cg_dead_lnode, &cgrp_dead->tasks); 7303 irq_work_queue(&cgrp_dead->iwork); 7304 } 7305 #else /* CONFIG_PREEMPT_RT */ 7306 static void __init cgroup_rt_init(void) {} 7307 7308 void cgroup_task_dead(struct task_struct *task) 7309 { 7310 do_cgroup_task_dead(task); 7311 } 7312 #endif /* CONFIG_PREEMPT_RT */ 7313 7314 void cgroup_task_release(struct task_struct *task) 7315 { 7316 struct cgroup_subsys *ss; 7317 int ssid; 7318 7319 do_each_subsys_mask(ss, ssid, have_release_callback) { 7320 ss->release(task); 7321 } while_each_subsys_mask(); 7322 } 7323 7324 void cgroup_task_free(struct task_struct *task) 7325 { 7326 struct css_set *cset = task_css_set(task); 7327 7328 if (!list_empty(&task->cg_list)) { 7329 spin_lock_irq(&css_set_lock); 7330 css_set_skip_task_iters(task_css_set(task), task); 7331 list_del_init(&task->cg_list); 7332 spin_unlock_irq(&css_set_lock); 7333 } 7334 7335 put_css_set(cset); 7336 } 7337 7338 static int __init cgroup_disable(char *str) 7339 { 7340 struct cgroup_subsys *ss; 7341 char *token; 7342 int i; 7343 7344 while ((token = strsep(&str, ",")) != NULL) { 7345 if (!*token) 7346 continue; 7347 7348 for_each_subsys(ss, i) { 7349 if (strcmp(token, ss->name) && 7350 strcmp(token, ss->legacy_name)) 7351 continue; 7352 7353 static_branch_disable(cgroup_subsys_enabled_key[i]); 7354 pr_info("Disabling %s control group subsystem\n", 7355 ss->name); 7356 } 7357 7358 for (i = 0; i < OPT_FEATURE_COUNT; i++) { 7359 if (strcmp(token, cgroup_opt_feature_names[i])) 7360 continue; 7361 cgroup_feature_disable_mask |= 1 << i; 7362 pr_info("Disabling %s control group feature\n", 7363 cgroup_opt_feature_names[i]); 7364 break; 7365 } 7366 } 7367 return 1; 7368 } 7369 __setup("cgroup_disable=", cgroup_disable); 7370 7371 void __init __weak enable_debug_cgroup(void) { } 7372 7373 static int __init enable_cgroup_debug(char *str) 7374 { 7375 cgroup_debug = true; 7376 enable_debug_cgroup(); 7377 return 1; 7378 } 7379 __setup("cgroup_debug", enable_cgroup_debug); 7380 7381 static int __init cgroup_favordynmods_setup(char *str) 7382 { 7383 return (kstrtobool(str, &have_favordynmods) == 0); 7384 } 7385 __setup("cgroup_favordynmods=", cgroup_favordynmods_setup); 7386 7387 /** 7388 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry 7389 * @dentry: directory dentry of interest 7390 * @ss: subsystem of interest 7391 * 7392 * If @dentry is a directory for a cgroup which has @ss enabled on it, try 7393 * to get the corresponding css and return it. If such css doesn't exist 7394 * or can't be pinned, an ERR_PTR value is returned. 7395 */ 7396 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry, 7397 struct cgroup_subsys *ss) 7398 { 7399 struct kernfs_node *kn = kernfs_node_from_dentry(dentry); 7400 struct file_system_type *s_type = dentry->d_sb->s_type; 7401 struct cgroup_subsys_state *css = NULL; 7402 struct cgroup *cgrp; 7403 7404 /* is @dentry a cgroup dir? */ 7405 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) || 7406 !kn || kernfs_type(kn) != KERNFS_DIR) 7407 return ERR_PTR(-EBADF); 7408 7409 rcu_read_lock(); 7410 7411 /* 7412 * This path doesn't originate from kernfs and @kn could already 7413 * have been or be removed at any point. @kn->priv is RCU 7414 * protected for this access. See css_release_work_fn() for details. 7415 */ 7416 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv); 7417 if (cgrp) 7418 css = cgroup_css(cgrp, ss); 7419 7420 if (!css || !css_tryget_online(css)) 7421 css = ERR_PTR(-ENOENT); 7422 7423 rcu_read_unlock(); 7424 return css; 7425 } 7426 7427 /** 7428 * css_from_id - lookup css by id 7429 * @id: the cgroup id 7430 * @ss: cgroup subsys to be looked into 7431 * 7432 * Returns the css if there's valid one with @id, otherwise returns NULL. 7433 * Should be called under rcu_read_lock(). 7434 */ 7435 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss) 7436 { 7437 WARN_ON_ONCE(!rcu_read_lock_held()); 7438 return idr_find(&ss->css_idr, id); 7439 } 7440 7441 /** 7442 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path 7443 * @path: path on the default hierarchy 7444 * 7445 * Find the cgroup at @path on the default hierarchy, increment its 7446 * reference count and return it. Returns pointer to the found cgroup on 7447 * success, ERR_PTR(-ENOENT) if @path doesn't exist or if the cgroup has already 7448 * been released and ERR_PTR(-ENOTDIR) if @path points to a non-directory. 7449 */ 7450 struct cgroup *cgroup_get_from_path(const char *path) 7451 { 7452 struct kernfs_node *kn; 7453 struct cgroup *cgrp = ERR_PTR(-ENOENT); 7454 struct cgroup *root_cgrp; 7455 7456 root_cgrp = current_cgns_cgroup_dfl(); 7457 kn = kernfs_walk_and_get(root_cgrp->kn, path); 7458 if (!kn) 7459 goto out; 7460 7461 if (kernfs_type(kn) != KERNFS_DIR) { 7462 cgrp = ERR_PTR(-ENOTDIR); 7463 goto out_kernfs; 7464 } 7465 7466 rcu_read_lock(); 7467 7468 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv); 7469 if (!cgrp || !cgroup_tryget(cgrp)) 7470 cgrp = ERR_PTR(-ENOENT); 7471 7472 rcu_read_unlock(); 7473 7474 out_kernfs: 7475 kernfs_put(kn); 7476 out: 7477 return cgrp; 7478 } 7479 EXPORT_SYMBOL_GPL(cgroup_get_from_path); 7480 7481 /** 7482 * cgroup_v1v2_get_from_fd - get a cgroup pointer from a fd 7483 * @fd: fd obtained by open(cgroup_dir) 7484 * 7485 * Find the cgroup from a fd which should be obtained 7486 * by opening a cgroup directory. Returns a pointer to the 7487 * cgroup on success. ERR_PTR is returned if the cgroup 7488 * cannot be found. 7489 */ 7490 struct cgroup *cgroup_v1v2_get_from_fd(int fd) 7491 { 7492 CLASS(fd_raw, f)(fd); 7493 if (fd_empty(f)) 7494 return ERR_PTR(-EBADF); 7495 7496 return cgroup_v1v2_get_from_file(fd_file(f)); 7497 } 7498 7499 /** 7500 * cgroup_get_from_fd - same as cgroup_v1v2_get_from_fd, but only supports 7501 * cgroup2. 7502 * @fd: fd obtained by open(cgroup2_dir) 7503 */ 7504 struct cgroup *cgroup_get_from_fd(int fd) 7505 { 7506 struct cgroup *cgrp = cgroup_v1v2_get_from_fd(fd); 7507 7508 if (IS_ERR(cgrp)) 7509 return ERR_CAST(cgrp); 7510 7511 if (!cgroup_on_dfl(cgrp)) { 7512 cgroup_put(cgrp); 7513 return ERR_PTR(-EBADF); 7514 } 7515 return cgrp; 7516 } 7517 EXPORT_SYMBOL_GPL(cgroup_get_from_fd); 7518 7519 static u64 power_of_ten(int power) 7520 { 7521 u64 v = 1; 7522 while (power--) 7523 v *= 10; 7524 return v; 7525 } 7526 7527 /** 7528 * cgroup_parse_float - parse a floating number 7529 * @input: input string 7530 * @dec_shift: number of decimal digits to shift 7531 * @v: output 7532 * 7533 * Parse a decimal floating point number in @input and store the result in 7534 * @v with decimal point right shifted @dec_shift times. For example, if 7535 * @input is "12.3456" and @dec_shift is 3, *@v will be set to 12345. 7536 * Returns 0 on success, -errno otherwise. 7537 * 7538 * There's nothing cgroup specific about this function except that it's 7539 * currently the only user. 7540 */ 7541 int cgroup_parse_float(const char *input, unsigned dec_shift, s64 *v) 7542 { 7543 s64 whole, frac = 0; 7544 int fstart = 0, fend = 0, flen; 7545 7546 if (!sscanf(input, "%lld.%n%lld%n", &whole, &fstart, &frac, &fend)) 7547 return -EINVAL; 7548 if (frac < 0) 7549 return -EINVAL; 7550 7551 flen = fend > fstart ? fend - fstart : 0; 7552 if (flen < dec_shift) 7553 frac *= power_of_ten(dec_shift - flen); 7554 else 7555 frac = DIV_ROUND_CLOSEST_ULL(frac, power_of_ten(flen - dec_shift)); 7556 7557 *v = whole * power_of_ten(dec_shift) + frac; 7558 return 0; 7559 } 7560 7561 /* 7562 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data 7563 * definition in cgroup-defs.h. 7564 */ 7565 #ifdef CONFIG_SOCK_CGROUP_DATA 7566 7567 void cgroup_sk_alloc(struct sock_cgroup_data *skcd) 7568 { 7569 struct cgroup *cgroup; 7570 7571 rcu_read_lock(); 7572 /* Don't associate the sock with unrelated interrupted task's cgroup. */ 7573 if (in_interrupt()) { 7574 cgroup = &cgrp_dfl_root.cgrp; 7575 cgroup_get(cgroup); 7576 goto out; 7577 } 7578 7579 while (true) { 7580 struct css_set *cset; 7581 7582 cset = task_css_set(current); 7583 if (likely(cgroup_tryget(cset->dfl_cgrp))) { 7584 cgroup = cset->dfl_cgrp; 7585 break; 7586 } 7587 cpu_relax(); 7588 } 7589 out: 7590 skcd->cgroup = cgroup; 7591 cgroup_bpf_get(cgroup); 7592 rcu_read_unlock(); 7593 } 7594 7595 void cgroup_sk_clone(struct sock_cgroup_data *skcd) 7596 { 7597 struct cgroup *cgrp = sock_cgroup_ptr(skcd); 7598 7599 /* 7600 * We might be cloning a socket which is left in an empty 7601 * cgroup and the cgroup might have already been rmdir'd. 7602 * Don't use cgroup_get_live(). 7603 */ 7604 cgroup_get(cgrp); 7605 cgroup_bpf_get(cgrp); 7606 } 7607 7608 void cgroup_sk_free(struct sock_cgroup_data *skcd) 7609 { 7610 struct cgroup *cgrp = sock_cgroup_ptr(skcd); 7611 7612 cgroup_bpf_put(cgrp); 7613 cgroup_put(cgrp); 7614 } 7615 7616 #endif /* CONFIG_SOCK_CGROUP_DATA */ 7617 7618 #ifdef CONFIG_SYSFS 7619 static ssize_t show_delegatable_files(struct cftype *files, char *buf, 7620 ssize_t size, const char *prefix) 7621 { 7622 struct cftype *cft; 7623 ssize_t ret = 0; 7624 7625 for (cft = files; cft && cft->name[0] != '\0'; cft++) { 7626 if (!(cft->flags & CFTYPE_NS_DELEGATABLE)) 7627 continue; 7628 7629 if (prefix) 7630 ret += snprintf(buf + ret, size - ret, "%s.", prefix); 7631 7632 ret += snprintf(buf + ret, size - ret, "%s\n", cft->name); 7633 7634 if (WARN_ON(ret >= size)) 7635 break; 7636 } 7637 7638 return ret; 7639 } 7640 7641 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr, 7642 char *buf) 7643 { 7644 struct cgroup_subsys *ss; 7645 int ssid; 7646 ssize_t ret = 0; 7647 7648 ret = show_delegatable_files(cgroup_base_files, buf + ret, 7649 PAGE_SIZE - ret, NULL); 7650 if (cgroup_psi_enabled()) 7651 ret += show_delegatable_files(cgroup_psi_files, buf + ret, 7652 PAGE_SIZE - ret, NULL); 7653 7654 for_each_subsys(ss, ssid) 7655 ret += show_delegatable_files(ss->dfl_cftypes, buf + ret, 7656 PAGE_SIZE - ret, 7657 cgroup_subsys_name[ssid]); 7658 7659 return ret; 7660 } 7661 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate); 7662 7663 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr, 7664 char *buf) 7665 { 7666 return snprintf(buf, PAGE_SIZE, 7667 "nsdelegate\n" 7668 "favordynmods\n" 7669 "memory_localevents\n" 7670 "memory_recursiveprot\n" 7671 "memory_hugetlb_accounting\n" 7672 "pids_localevents\n"); 7673 } 7674 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features); 7675 7676 static struct attribute *cgroup_sysfs_attrs[] = { 7677 &cgroup_delegate_attr.attr, 7678 &cgroup_features_attr.attr, 7679 NULL, 7680 }; 7681 7682 static const struct attribute_group cgroup_sysfs_attr_group = { 7683 .attrs = cgroup_sysfs_attrs, 7684 .name = "cgroup", 7685 }; 7686 7687 static int __init cgroup_sysfs_init(void) 7688 { 7689 return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group); 7690 } 7691 subsys_initcall(cgroup_sysfs_init); 7692 7693 #endif /* CONFIG_SYSFS */ 7694