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