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