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