Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
torvalds
GitHub Repository: torvalds/linux
Path: blob/master/kernel/cgroup/cgroup.c
48914 views
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 u16 cgrp_dfl_inhibit_ss_mask;
207
208
/* some controllers are implicitly enabled on the default hierarchy */
209
static u16 cgrp_dfl_implicit_ss_mask;
210
211
/* some controllers can be threaded on the default hierarchy */
212
static u16 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 u16 have_fork_callback __read_mostly;
235
static u16 have_exit_callback __read_mostly;
236
static u16 have_release_callback __read_mostly;
237
static u16 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 u16 cgroup_control(struct cgroup *cgrp)
476
{
477
struct cgroup *parent = cgroup_parent(cgrp);
478
u16 root_ss_mask = cgrp->root->subsys_mask;
479
480
if (parent) {
481
u16 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 u16 cgroup_ss_mask(struct cgroup *cgrp)
497
{
498
struct cgroup *parent = cgroup_parent(cgrp);
499
500
if (parent) {
501
u16 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(sizeof(*link), GFP_KERNEL);
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(sizeof(*cset), GFP_KERNEL);
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 u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1637
{
1638
u16 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
u16 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, u16 ss_mask)
1852
{
1853
struct cgroup *dcgrp = &dst_root->cgrp;
1854
struct cgroup_subsys *ss;
1855
int ssid, ret;
1856
u16 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, u16 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(sizeof(struct cgroup_fs_context), GFP_KERNEL);
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
list_move_tail(&task->cg_list, &cset->mg_tasks);
2612
if (list_empty(&cset->mg_node))
2613
list_add_tail(&cset->mg_node,
2614
&mgctx->tset.src_csets);
2615
if (list_empty(&cset->mg_dst_cset->mg_node))
2616
list_add_tail(&cset->mg_dst_cset->mg_node,
2617
&mgctx->tset.dst_csets);
2618
}
2619
2620
/**
2621
* cgroup_taskset_first - reset taskset and return the first task
2622
* @tset: taskset of interest
2623
* @dst_cssp: output variable for the destination css
2624
*
2625
* @tset iteration is initialized and the first task is returned.
2626
*/
2627
struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2628
struct cgroup_subsys_state **dst_cssp)
2629
{
2630
tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2631
tset->cur_task = NULL;
2632
2633
return cgroup_taskset_next(tset, dst_cssp);
2634
}
2635
2636
/**
2637
* cgroup_taskset_next - iterate to the next task in taskset
2638
* @tset: taskset of interest
2639
* @dst_cssp: output variable for the destination css
2640
*
2641
* Return the next task in @tset. Iteration must have been initialized
2642
* with cgroup_taskset_first().
2643
*/
2644
struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2645
struct cgroup_subsys_state **dst_cssp)
2646
{
2647
struct css_set *cset = tset->cur_cset;
2648
struct task_struct *task = tset->cur_task;
2649
2650
while (CGROUP_HAS_SUBSYS_CONFIG && &cset->mg_node != tset->csets) {
2651
if (!task)
2652
task = list_first_entry(&cset->mg_tasks,
2653
struct task_struct, cg_list);
2654
else
2655
task = list_next_entry(task, cg_list);
2656
2657
if (&task->cg_list != &cset->mg_tasks) {
2658
tset->cur_cset = cset;
2659
tset->cur_task = task;
2660
2661
/*
2662
* This function may be called both before and
2663
* after cgroup_migrate_execute(). The two cases
2664
* can be distinguished by looking at whether @cset
2665
* has its ->mg_dst_cset set.
2666
*/
2667
if (cset->mg_dst_cset)
2668
*dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2669
else
2670
*dst_cssp = cset->subsys[tset->ssid];
2671
2672
return task;
2673
}
2674
2675
cset = list_next_entry(cset, mg_node);
2676
task = NULL;
2677
}
2678
2679
return NULL;
2680
}
2681
2682
/**
2683
* cgroup_migrate_execute - migrate a taskset
2684
* @mgctx: migration context
2685
*
2686
* Migrate tasks in @mgctx as setup by migration preparation functions.
2687
* This function fails iff one of the ->can_attach callbacks fails and
2688
* guarantees that either all or none of the tasks in @mgctx are migrated.
2689
* @mgctx is consumed regardless of success.
2690
*/
2691
static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2692
{
2693
struct cgroup_taskset *tset = &mgctx->tset;
2694
struct cgroup_subsys *ss;
2695
struct task_struct *task, *tmp_task;
2696
struct css_set *cset, *tmp_cset;
2697
int ssid, failed_ssid, ret;
2698
2699
/* check that we can legitimately attach to the cgroup */
2700
if (tset->nr_tasks) {
2701
do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2702
if (ss->can_attach) {
2703
tset->ssid = ssid;
2704
ret = ss->can_attach(tset);
2705
if (ret) {
2706
failed_ssid = ssid;
2707
goto out_cancel_attach;
2708
}
2709
}
2710
} while_each_subsys_mask();
2711
}
2712
2713
/*
2714
* Now that we're guaranteed success, proceed to move all tasks to
2715
* the new cgroup. There are no failure cases after here, so this
2716
* is the commit point.
2717
*/
2718
spin_lock_irq(&css_set_lock);
2719
list_for_each_entry(cset, &tset->src_csets, mg_node) {
2720
list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2721
struct css_set *from_cset = task_css_set(task);
2722
struct css_set *to_cset = cset->mg_dst_cset;
2723
2724
get_css_set(to_cset);
2725
to_cset->nr_tasks++;
2726
css_set_move_task(task, from_cset, to_cset, true);
2727
from_cset->nr_tasks--;
2728
/*
2729
* If the source or destination cgroup is frozen,
2730
* the task might require to change its state.
2731
*/
2732
cgroup_freezer_migrate_task(task, from_cset->dfl_cgrp,
2733
to_cset->dfl_cgrp);
2734
put_css_set_locked(from_cset);
2735
2736
}
2737
}
2738
spin_unlock_irq(&css_set_lock);
2739
2740
/*
2741
* Migration is committed, all target tasks are now on dst_csets.
2742
* Nothing is sensitive to fork() after this point. Notify
2743
* controllers that migration is complete.
2744
*/
2745
tset->csets = &tset->dst_csets;
2746
2747
if (tset->nr_tasks) {
2748
do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2749
if (ss->attach) {
2750
tset->ssid = ssid;
2751
ss->attach(tset);
2752
}
2753
} while_each_subsys_mask();
2754
}
2755
2756
ret = 0;
2757
goto out_release_tset;
2758
2759
out_cancel_attach:
2760
if (tset->nr_tasks) {
2761
do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2762
if (ssid == failed_ssid)
2763
break;
2764
if (ss->cancel_attach) {
2765
tset->ssid = ssid;
2766
ss->cancel_attach(tset);
2767
}
2768
} while_each_subsys_mask();
2769
}
2770
out_release_tset:
2771
spin_lock_irq(&css_set_lock);
2772
list_splice_init(&tset->dst_csets, &tset->src_csets);
2773
list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2774
list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2775
list_del_init(&cset->mg_node);
2776
}
2777
spin_unlock_irq(&css_set_lock);
2778
2779
/*
2780
* Re-initialize the cgroup_taskset structure in case it is reused
2781
* again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2782
* iteration.
2783
*/
2784
tset->nr_tasks = 0;
2785
tset->csets = &tset->src_csets;
2786
return ret;
2787
}
2788
2789
/**
2790
* cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2791
* @dst_cgrp: destination cgroup to test
2792
*
2793
* On the default hierarchy, except for the mixable, (possible) thread root
2794
* and threaded cgroups, subtree_control must be zero for migration
2795
* destination cgroups with tasks so that child cgroups don't compete
2796
* against tasks.
2797
*/
2798
int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2799
{
2800
/* v1 doesn't have any restriction */
2801
if (!cgroup_on_dfl(dst_cgrp))
2802
return 0;
2803
2804
/* verify @dst_cgrp can host resources */
2805
if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2806
return -EOPNOTSUPP;
2807
2808
/*
2809
* If @dst_cgrp is already or can become a thread root or is
2810
* threaded, it doesn't matter.
2811
*/
2812
if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2813
return 0;
2814
2815
/* apply no-internal-process constraint */
2816
if (dst_cgrp->subtree_control)
2817
return -EBUSY;
2818
2819
return 0;
2820
}
2821
2822
/**
2823
* cgroup_migrate_finish - cleanup after attach
2824
* @mgctx: migration context
2825
*
2826
* Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2827
* those functions for details.
2828
*/
2829
void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2830
{
2831
struct css_set *cset, *tmp_cset;
2832
2833
lockdep_assert_held(&cgroup_mutex);
2834
2835
spin_lock_irq(&css_set_lock);
2836
2837
list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_src_csets,
2838
mg_src_preload_node) {
2839
cset->mg_src_cgrp = NULL;
2840
cset->mg_dst_cgrp = NULL;
2841
cset->mg_dst_cset = NULL;
2842
list_del_init(&cset->mg_src_preload_node);
2843
put_css_set_locked(cset);
2844
}
2845
2846
list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_dst_csets,
2847
mg_dst_preload_node) {
2848
cset->mg_src_cgrp = NULL;
2849
cset->mg_dst_cgrp = NULL;
2850
cset->mg_dst_cset = NULL;
2851
list_del_init(&cset->mg_dst_preload_node);
2852
put_css_set_locked(cset);
2853
}
2854
2855
spin_unlock_irq(&css_set_lock);
2856
}
2857
2858
/**
2859
* cgroup_migrate_add_src - add a migration source css_set
2860
* @src_cset: the source css_set to add
2861
* @dst_cgrp: the destination cgroup
2862
* @mgctx: migration context
2863
*
2864
* Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2865
* @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2866
* up by cgroup_migrate_finish().
2867
*
2868
* This function may be called without holding cgroup_threadgroup_rwsem
2869
* even if the target is a process. Threads may be created and destroyed
2870
* but as long as cgroup_mutex is not dropped, no new css_set can be put
2871
* into play and the preloaded css_sets are guaranteed to cover all
2872
* migrations.
2873
*/
2874
void cgroup_migrate_add_src(struct css_set *src_cset,
2875
struct cgroup *dst_cgrp,
2876
struct cgroup_mgctx *mgctx)
2877
{
2878
struct cgroup *src_cgrp;
2879
2880
lockdep_assert_held(&cgroup_mutex);
2881
lockdep_assert_held(&css_set_lock);
2882
2883
/*
2884
* If ->dead, @src_set is associated with one or more dead cgroups
2885
* and doesn't contain any migratable tasks. Ignore it early so
2886
* that the rest of migration path doesn't get confused by it.
2887
*/
2888
if (src_cset->dead)
2889
return;
2890
2891
if (!list_empty(&src_cset->mg_src_preload_node))
2892
return;
2893
2894
src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2895
2896
WARN_ON(src_cset->mg_src_cgrp);
2897
WARN_ON(src_cset->mg_dst_cgrp);
2898
WARN_ON(!list_empty(&src_cset->mg_tasks));
2899
WARN_ON(!list_empty(&src_cset->mg_node));
2900
2901
src_cset->mg_src_cgrp = src_cgrp;
2902
src_cset->mg_dst_cgrp = dst_cgrp;
2903
get_css_set(src_cset);
2904
list_add_tail(&src_cset->mg_src_preload_node, &mgctx->preloaded_src_csets);
2905
}
2906
2907
/**
2908
* cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2909
* @mgctx: migration context
2910
*
2911
* Tasks are about to be moved and all the source css_sets have been
2912
* preloaded to @mgctx->preloaded_src_csets. This function looks up and
2913
* pins all destination css_sets, links each to its source, and append them
2914
* to @mgctx->preloaded_dst_csets.
2915
*
2916
* This function must be called after cgroup_migrate_add_src() has been
2917
* called on each migration source css_set. After migration is performed
2918
* using cgroup_migrate(), cgroup_migrate_finish() must be called on
2919
* @mgctx.
2920
*/
2921
int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2922
{
2923
struct css_set *src_cset, *tmp_cset;
2924
2925
lockdep_assert_held(&cgroup_mutex);
2926
2927
/* look up the dst cset for each src cset and link it to src */
2928
list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2929
mg_src_preload_node) {
2930
struct css_set *dst_cset;
2931
struct cgroup_subsys *ss;
2932
int ssid;
2933
2934
dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2935
if (!dst_cset)
2936
return -ENOMEM;
2937
2938
WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2939
2940
/*
2941
* If src cset equals dst, it's noop. Drop the src.
2942
* cgroup_migrate() will skip the cset too. Note that we
2943
* can't handle src == dst as some nodes are used by both.
2944
*/
2945
if (src_cset == dst_cset) {
2946
src_cset->mg_src_cgrp = NULL;
2947
src_cset->mg_dst_cgrp = NULL;
2948
list_del_init(&src_cset->mg_src_preload_node);
2949
put_css_set(src_cset);
2950
put_css_set(dst_cset);
2951
continue;
2952
}
2953
2954
src_cset->mg_dst_cset = dst_cset;
2955
2956
if (list_empty(&dst_cset->mg_dst_preload_node))
2957
list_add_tail(&dst_cset->mg_dst_preload_node,
2958
&mgctx->preloaded_dst_csets);
2959
else
2960
put_css_set(dst_cset);
2961
2962
for_each_subsys(ss, ssid)
2963
if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2964
mgctx->ss_mask |= 1 << ssid;
2965
}
2966
2967
return 0;
2968
}
2969
2970
/**
2971
* cgroup_migrate - migrate a process or task to a cgroup
2972
* @leader: the leader of the process or the task to migrate
2973
* @threadgroup: whether @leader points to the whole process or a single task
2974
* @mgctx: migration context
2975
*
2976
* Migrate a process or task denoted by @leader. If migrating a process,
2977
* the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2978
* responsible for invoking cgroup_migrate_add_src() and
2979
* cgroup_migrate_prepare_dst() on the targets before invoking this
2980
* function and following up with cgroup_migrate_finish().
2981
*
2982
* As long as a controller's ->can_attach() doesn't fail, this function is
2983
* guaranteed to succeed. This means that, excluding ->can_attach()
2984
* failure, when migrating multiple targets, the success or failure can be
2985
* decided for all targets by invoking group_migrate_prepare_dst() before
2986
* actually starting migrating.
2987
*/
2988
int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2989
struct cgroup_mgctx *mgctx)
2990
{
2991
struct task_struct *task;
2992
2993
/*
2994
* The following thread iteration should be inside an RCU critical
2995
* section to prevent tasks from being freed while taking the snapshot.
2996
* spin_lock_irq() implies RCU critical section here.
2997
*/
2998
spin_lock_irq(&css_set_lock);
2999
task = leader;
3000
do {
3001
cgroup_migrate_add_task(task, mgctx);
3002
if (!threadgroup)
3003
break;
3004
} while_each_thread(leader, task);
3005
spin_unlock_irq(&css_set_lock);
3006
3007
return cgroup_migrate_execute(mgctx);
3008
}
3009
3010
/**
3011
* cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
3012
* @dst_cgrp: the cgroup to attach to
3013
* @leader: the task or the leader of the threadgroup to be attached
3014
* @threadgroup: attach the whole threadgroup?
3015
*
3016
* Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
3017
*/
3018
int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
3019
bool threadgroup)
3020
{
3021
DEFINE_CGROUP_MGCTX(mgctx);
3022
struct task_struct *task;
3023
int ret = 0;
3024
3025
/* look up all src csets */
3026
spin_lock_irq(&css_set_lock);
3027
task = leader;
3028
do {
3029
cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
3030
if (!threadgroup)
3031
break;
3032
} while_each_thread(leader, task);
3033
spin_unlock_irq(&css_set_lock);
3034
3035
/* prepare dst csets and commit */
3036
ret = cgroup_migrate_prepare_dst(&mgctx);
3037
if (!ret)
3038
ret = cgroup_migrate(leader, threadgroup, &mgctx);
3039
3040
cgroup_migrate_finish(&mgctx);
3041
3042
if (!ret)
3043
TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
3044
3045
return ret;
3046
}
3047
3048
struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup,
3049
enum cgroup_attach_lock_mode *lock_mode)
3050
{
3051
struct task_struct *tsk;
3052
pid_t pid;
3053
3054
if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
3055
return ERR_PTR(-EINVAL);
3056
3057
retry_find_task:
3058
rcu_read_lock();
3059
if (pid) {
3060
tsk = find_task_by_vpid(pid);
3061
if (!tsk) {
3062
tsk = ERR_PTR(-ESRCH);
3063
goto out_unlock_rcu;
3064
}
3065
} else {
3066
tsk = current;
3067
}
3068
3069
if (threadgroup)
3070
tsk = tsk->group_leader;
3071
3072
/*
3073
* kthreads may acquire PF_NO_SETAFFINITY during initialization.
3074
* If userland migrates such a kthread to a non-root cgroup, it can
3075
* become trapped in a cpuset, or RT kthread may be born in a
3076
* cgroup with no rt_runtime allocated. Just say no.
3077
*/
3078
if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
3079
tsk = ERR_PTR(-EINVAL);
3080
goto out_unlock_rcu;
3081
}
3082
get_task_struct(tsk);
3083
rcu_read_unlock();
3084
3085
/*
3086
* If we migrate a single thread, we don't care about threadgroup
3087
* stability. If the thread is `current`, it won't exit(2) under our
3088
* hands or change PID through exec(2). We exclude
3089
* cgroup_update_dfl_csses and other cgroup_{proc,thread}s_write callers
3090
* by cgroup_mutex. Therefore, we can skip the global lock.
3091
*/
3092
lockdep_assert_held(&cgroup_mutex);
3093
3094
if (pid || threadgroup) {
3095
if (cgroup_enable_per_threadgroup_rwsem)
3096
*lock_mode = CGRP_ATTACH_LOCK_PER_THREADGROUP;
3097
else
3098
*lock_mode = CGRP_ATTACH_LOCK_GLOBAL;
3099
} else {
3100
*lock_mode = CGRP_ATTACH_LOCK_NONE;
3101
}
3102
3103
cgroup_attach_lock(*lock_mode, tsk);
3104
3105
if (threadgroup) {
3106
if (!thread_group_leader(tsk)) {
3107
/*
3108
* A race with de_thread from another thread's exec()
3109
* may strip us of our leadership. If this happens,
3110
* throw this task away and try again.
3111
*/
3112
cgroup_attach_unlock(*lock_mode, tsk);
3113
put_task_struct(tsk);
3114
goto retry_find_task;
3115
}
3116
}
3117
3118
return tsk;
3119
3120
out_unlock_rcu:
3121
rcu_read_unlock();
3122
return tsk;
3123
}
3124
3125
void cgroup_procs_write_finish(struct task_struct *task,
3126
enum cgroup_attach_lock_mode lock_mode)
3127
{
3128
cgroup_attach_unlock(lock_mode, task);
3129
3130
/* release reference from cgroup_procs_write_start() */
3131
put_task_struct(task);
3132
}
3133
3134
static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
3135
{
3136
struct cgroup_subsys *ss;
3137
bool printed = false;
3138
int ssid;
3139
3140
do_each_subsys_mask(ss, ssid, ss_mask) {
3141
if (printed)
3142
seq_putc(seq, ' ');
3143
seq_puts(seq, ss->name);
3144
printed = true;
3145
} while_each_subsys_mask();
3146
if (printed)
3147
seq_putc(seq, '\n');
3148
}
3149
3150
/* show controllers which are enabled from the parent */
3151
static int cgroup_controllers_show(struct seq_file *seq, void *v)
3152
{
3153
struct cgroup *cgrp = seq_css(seq)->cgroup;
3154
3155
cgroup_print_ss_mask(seq, cgroup_control(cgrp));
3156
return 0;
3157
}
3158
3159
/* show controllers which are enabled for a given cgroup's children */
3160
static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
3161
{
3162
struct cgroup *cgrp = seq_css(seq)->cgroup;
3163
3164
cgroup_print_ss_mask(seq, cgrp->subtree_control);
3165
return 0;
3166
}
3167
3168
/**
3169
* cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
3170
* @cgrp: root of the subtree to update csses for
3171
*
3172
* @cgrp's control masks have changed and its subtree's css associations
3173
* need to be updated accordingly. This function looks up all css_sets
3174
* which are attached to the subtree, creates the matching updated css_sets
3175
* and migrates the tasks to the new ones.
3176
*/
3177
static int cgroup_update_dfl_csses(struct cgroup *cgrp)
3178
{
3179
DEFINE_CGROUP_MGCTX(mgctx);
3180
struct cgroup_subsys_state *d_css;
3181
struct cgroup *dsct;
3182
struct css_set *src_cset;
3183
enum cgroup_attach_lock_mode lock_mode;
3184
bool has_tasks;
3185
int ret;
3186
3187
lockdep_assert_held(&cgroup_mutex);
3188
3189
/* look up all csses currently attached to @cgrp's subtree */
3190
spin_lock_irq(&css_set_lock);
3191
cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3192
struct cgrp_cset_link *link;
3193
3194
/*
3195
* As cgroup_update_dfl_csses() is only called by
3196
* cgroup_apply_control(). The csses associated with the
3197
* given cgrp will not be affected by changes made to
3198
* its subtree_control file. We can skip them.
3199
*/
3200
if (dsct == cgrp)
3201
continue;
3202
3203
list_for_each_entry(link, &dsct->cset_links, cset_link)
3204
cgroup_migrate_add_src(link->cset, dsct, &mgctx);
3205
}
3206
spin_unlock_irq(&css_set_lock);
3207
3208
/*
3209
* We need to write-lock threadgroup_rwsem while migrating tasks.
3210
* However, if there are no source csets for @cgrp, changing its
3211
* controllers isn't gonna produce any task migrations and the
3212
* write-locking can be skipped safely.
3213
*/
3214
has_tasks = !list_empty(&mgctx.preloaded_src_csets);
3215
3216
if (has_tasks)
3217
lock_mode = CGRP_ATTACH_LOCK_GLOBAL;
3218
else
3219
lock_mode = CGRP_ATTACH_LOCK_NONE;
3220
3221
cgroup_attach_lock(lock_mode, NULL);
3222
3223
/* NULL dst indicates self on default hierarchy */
3224
ret = cgroup_migrate_prepare_dst(&mgctx);
3225
if (ret)
3226
goto out_finish;
3227
3228
spin_lock_irq(&css_set_lock);
3229
list_for_each_entry(src_cset, &mgctx.preloaded_src_csets,
3230
mg_src_preload_node) {
3231
struct task_struct *task, *ntask;
3232
3233
/* all tasks in src_csets need to be migrated */
3234
list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
3235
cgroup_migrate_add_task(task, &mgctx);
3236
}
3237
spin_unlock_irq(&css_set_lock);
3238
3239
ret = cgroup_migrate_execute(&mgctx);
3240
out_finish:
3241
cgroup_migrate_finish(&mgctx);
3242
cgroup_attach_unlock(lock_mode, NULL);
3243
return ret;
3244
}
3245
3246
/**
3247
* cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
3248
* @cgrp: root of the target subtree
3249
*
3250
* Because css offlining is asynchronous, userland may try to re-enable a
3251
* controller while the previous css is still around. This function grabs
3252
* cgroup_mutex and drains the previous css instances of @cgrp's subtree.
3253
*/
3254
void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
3255
__acquires(&cgroup_mutex)
3256
{
3257
struct cgroup *dsct;
3258
struct cgroup_subsys_state *d_css;
3259
struct cgroup_subsys *ss;
3260
int ssid;
3261
3262
restart:
3263
cgroup_lock();
3264
3265
cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3266
for_each_subsys(ss, ssid) {
3267
struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3268
DEFINE_WAIT(wait);
3269
3270
if (!css || !percpu_ref_is_dying(&css->refcnt))
3271
continue;
3272
3273
cgroup_get_live(dsct);
3274
prepare_to_wait(&dsct->offline_waitq, &wait,
3275
TASK_UNINTERRUPTIBLE);
3276
3277
cgroup_unlock();
3278
schedule();
3279
finish_wait(&dsct->offline_waitq, &wait);
3280
3281
cgroup_put(dsct);
3282
goto restart;
3283
}
3284
}
3285
}
3286
3287
/**
3288
* cgroup_save_control - save control masks and dom_cgrp of a subtree
3289
* @cgrp: root of the target subtree
3290
*
3291
* Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
3292
* respective old_ prefixed fields for @cgrp's subtree including @cgrp
3293
* itself.
3294
*/
3295
static void cgroup_save_control(struct cgroup *cgrp)
3296
{
3297
struct cgroup *dsct;
3298
struct cgroup_subsys_state *d_css;
3299
3300
cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3301
dsct->old_subtree_control = dsct->subtree_control;
3302
dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
3303
dsct->old_dom_cgrp = dsct->dom_cgrp;
3304
}
3305
}
3306
3307
/**
3308
* cgroup_propagate_control - refresh control masks of a subtree
3309
* @cgrp: root of the target subtree
3310
*
3311
* For @cgrp and its subtree, ensure ->subtree_ss_mask matches
3312
* ->subtree_control and propagate controller availability through the
3313
* subtree so that descendants don't have unavailable controllers enabled.
3314
*/
3315
static void cgroup_propagate_control(struct cgroup *cgrp)
3316
{
3317
struct cgroup *dsct;
3318
struct cgroup_subsys_state *d_css;
3319
3320
cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3321
dsct->subtree_control &= cgroup_control(dsct);
3322
dsct->subtree_ss_mask =
3323
cgroup_calc_subtree_ss_mask(dsct->subtree_control,
3324
cgroup_ss_mask(dsct));
3325
}
3326
}
3327
3328
/**
3329
* cgroup_restore_control - restore control masks and dom_cgrp of a subtree
3330
* @cgrp: root of the target subtree
3331
*
3332
* Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
3333
* respective old_ prefixed fields for @cgrp's subtree including @cgrp
3334
* itself.
3335
*/
3336
static void cgroup_restore_control(struct cgroup *cgrp)
3337
{
3338
struct cgroup *dsct;
3339
struct cgroup_subsys_state *d_css;
3340
3341
cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3342
dsct->subtree_control = dsct->old_subtree_control;
3343
dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
3344
dsct->dom_cgrp = dsct->old_dom_cgrp;
3345
}
3346
}
3347
3348
static bool css_visible(struct cgroup_subsys_state *css)
3349
{
3350
struct cgroup_subsys *ss = css->ss;
3351
struct cgroup *cgrp = css->cgroup;
3352
3353
if (cgroup_control(cgrp) & (1 << ss->id))
3354
return true;
3355
if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
3356
return false;
3357
return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
3358
}
3359
3360
/**
3361
* cgroup_apply_control_enable - enable or show csses according to control
3362
* @cgrp: root of the target subtree
3363
*
3364
* Walk @cgrp's subtree and create new csses or make the existing ones
3365
* visible. A css is created invisible if it's being implicitly enabled
3366
* through dependency. An invisible css is made visible when the userland
3367
* explicitly enables it.
3368
*
3369
* Returns 0 on success, -errno on failure. On failure, csses which have
3370
* been processed already aren't cleaned up. The caller is responsible for
3371
* cleaning up with cgroup_apply_control_disable().
3372
*/
3373
static int cgroup_apply_control_enable(struct cgroup *cgrp)
3374
{
3375
struct cgroup *dsct;
3376
struct cgroup_subsys_state *d_css;
3377
struct cgroup_subsys *ss;
3378
int ssid, ret;
3379
3380
cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3381
for_each_subsys(ss, ssid) {
3382
struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3383
3384
if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
3385
continue;
3386
3387
if (!css) {
3388
css = css_create(dsct, ss);
3389
if (IS_ERR(css))
3390
return PTR_ERR(css);
3391
}
3392
3393
WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3394
3395
if (css_visible(css)) {
3396
ret = css_populate_dir(css);
3397
if (ret)
3398
return ret;
3399
}
3400
}
3401
}
3402
3403
return 0;
3404
}
3405
3406
/**
3407
* cgroup_apply_control_disable - kill or hide csses according to control
3408
* @cgrp: root of the target subtree
3409
*
3410
* Walk @cgrp's subtree and kill and hide csses so that they match
3411
* cgroup_ss_mask() and cgroup_visible_mask().
3412
*
3413
* A css is hidden when the userland requests it to be disabled while other
3414
* subsystems are still depending on it. The css must not actively control
3415
* resources and be in the vanilla state if it's made visible again later.
3416
* Controllers which may be depended upon should provide ->css_reset() for
3417
* this purpose.
3418
*/
3419
static void cgroup_apply_control_disable(struct cgroup *cgrp)
3420
{
3421
struct cgroup *dsct;
3422
struct cgroup_subsys_state *d_css;
3423
struct cgroup_subsys *ss;
3424
int ssid;
3425
3426
cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3427
for_each_subsys(ss, ssid) {
3428
struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3429
3430
if (!css)
3431
continue;
3432
3433
WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3434
3435
if (css->parent &&
3436
!(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3437
kill_css(css);
3438
} else if (!css_visible(css)) {
3439
css_clear_dir(css);
3440
if (ss->css_reset)
3441
ss->css_reset(css);
3442
}
3443
}
3444
}
3445
}
3446
3447
/**
3448
* cgroup_apply_control - apply control mask updates to the subtree
3449
* @cgrp: root of the target subtree
3450
*
3451
* subsystems can be enabled and disabled in a subtree using the following
3452
* steps.
3453
*
3454
* 1. Call cgroup_save_control() to stash the current state.
3455
* 2. Update ->subtree_control masks in the subtree as desired.
3456
* 3. Call cgroup_apply_control() to apply the changes.
3457
* 4. Optionally perform other related operations.
3458
* 5. Call cgroup_finalize_control() to finish up.
3459
*
3460
* This function implements step 3 and propagates the mask changes
3461
* throughout @cgrp's subtree, updates csses accordingly and perform
3462
* process migrations.
3463
*/
3464
static int cgroup_apply_control(struct cgroup *cgrp)
3465
{
3466
int ret;
3467
3468
cgroup_propagate_control(cgrp);
3469
3470
ret = cgroup_apply_control_enable(cgrp);
3471
if (ret)
3472
return ret;
3473
3474
/*
3475
* At this point, cgroup_e_css_by_mask() results reflect the new csses
3476
* making the following cgroup_update_dfl_csses() properly update
3477
* css associations of all tasks in the subtree.
3478
*/
3479
return cgroup_update_dfl_csses(cgrp);
3480
}
3481
3482
/**
3483
* cgroup_finalize_control - finalize control mask update
3484
* @cgrp: root of the target subtree
3485
* @ret: the result of the update
3486
*
3487
* Finalize control mask update. See cgroup_apply_control() for more info.
3488
*/
3489
static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3490
{
3491
if (ret) {
3492
cgroup_restore_control(cgrp);
3493
cgroup_propagate_control(cgrp);
3494
}
3495
3496
cgroup_apply_control_disable(cgrp);
3497
}
3498
3499
static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3500
{
3501
u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3502
3503
/* if nothing is getting enabled, nothing to worry about */
3504
if (!enable)
3505
return 0;
3506
3507
/* can @cgrp host any resources? */
3508
if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3509
return -EOPNOTSUPP;
3510
3511
/* mixables don't care */
3512
if (cgroup_is_mixable(cgrp))
3513
return 0;
3514
3515
if (domain_enable) {
3516
/* can't enable domain controllers inside a thread subtree */
3517
if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3518
return -EOPNOTSUPP;
3519
} else {
3520
/*
3521
* Threaded controllers can handle internal competitions
3522
* and are always allowed inside a (prospective) thread
3523
* subtree.
3524
*/
3525
if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3526
return 0;
3527
}
3528
3529
/*
3530
* Controllers can't be enabled for a cgroup with tasks to avoid
3531
* child cgroups competing against tasks.
3532
*/
3533
if (cgroup_has_tasks(cgrp))
3534
return -EBUSY;
3535
3536
return 0;
3537
}
3538
3539
/* change the enabled child controllers for a cgroup in the default hierarchy */
3540
static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3541
char *buf, size_t nbytes,
3542
loff_t off)
3543
{
3544
u16 enable = 0, disable = 0;
3545
struct cgroup *cgrp, *child;
3546
struct cgroup_subsys *ss;
3547
char *tok;
3548
int ssid, ret;
3549
3550
/*
3551
* Parse input - space separated list of subsystem names prefixed
3552
* with either + or -.
3553
*/
3554
buf = strstrip(buf);
3555
while ((tok = strsep(&buf, " "))) {
3556
if (tok[0] == '\0')
3557
continue;
3558
do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3559
if (!cgroup_ssid_enabled(ssid) ||
3560
strcmp(tok + 1, ss->name))
3561
continue;
3562
3563
if (*tok == '+') {
3564
enable |= 1 << ssid;
3565
disable &= ~(1 << ssid);
3566
} else if (*tok == '-') {
3567
disable |= 1 << ssid;
3568
enable &= ~(1 << ssid);
3569
} else {
3570
return -EINVAL;
3571
}
3572
break;
3573
} while_each_subsys_mask();
3574
if (ssid == CGROUP_SUBSYS_COUNT)
3575
return -EINVAL;
3576
}
3577
3578
cgrp = cgroup_kn_lock_live(of->kn, true);
3579
if (!cgrp)
3580
return -ENODEV;
3581
3582
for_each_subsys(ss, ssid) {
3583
if (enable & (1 << ssid)) {
3584
if (cgrp->subtree_control & (1 << ssid)) {
3585
enable &= ~(1 << ssid);
3586
continue;
3587
}
3588
3589
if (!(cgroup_control(cgrp) & (1 << ssid))) {
3590
ret = -ENOENT;
3591
goto out_unlock;
3592
}
3593
} else if (disable & (1 << ssid)) {
3594
if (!(cgrp->subtree_control & (1 << ssid))) {
3595
disable &= ~(1 << ssid);
3596
continue;
3597
}
3598
3599
/* a child has it enabled? */
3600
cgroup_for_each_live_child(child, cgrp) {
3601
if (child->subtree_control & (1 << ssid)) {
3602
ret = -EBUSY;
3603
goto out_unlock;
3604
}
3605
}
3606
}
3607
}
3608
3609
if (!enable && !disable) {
3610
ret = 0;
3611
goto out_unlock;
3612
}
3613
3614
ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3615
if (ret)
3616
goto out_unlock;
3617
3618
/* save and update control masks and prepare csses */
3619
cgroup_save_control(cgrp);
3620
3621
cgrp->subtree_control |= enable;
3622
cgrp->subtree_control &= ~disable;
3623
3624
ret = cgroup_apply_control(cgrp);
3625
cgroup_finalize_control(cgrp, ret);
3626
if (ret)
3627
goto out_unlock;
3628
3629
kernfs_activate(cgrp->kn);
3630
out_unlock:
3631
cgroup_kn_unlock(of->kn);
3632
return ret ?: nbytes;
3633
}
3634
3635
/**
3636
* cgroup_enable_threaded - make @cgrp threaded
3637
* @cgrp: the target cgroup
3638
*
3639
* Called when "threaded" is written to the cgroup.type interface file and
3640
* tries to make @cgrp threaded and join the parent's resource domain.
3641
* This function is never called on the root cgroup as cgroup.type doesn't
3642
* exist on it.
3643
*/
3644
static int cgroup_enable_threaded(struct cgroup *cgrp)
3645
{
3646
struct cgroup *parent = cgroup_parent(cgrp);
3647
struct cgroup *dom_cgrp = parent->dom_cgrp;
3648
struct cgroup *dsct;
3649
struct cgroup_subsys_state *d_css;
3650
int ret;
3651
3652
lockdep_assert_held(&cgroup_mutex);
3653
3654
/* noop if already threaded */
3655
if (cgroup_is_threaded(cgrp))
3656
return 0;
3657
3658
/*
3659
* If @cgroup is populated or has domain controllers enabled, it
3660
* can't be switched. While the below cgroup_can_be_thread_root()
3661
* test can catch the same conditions, that's only when @parent is
3662
* not mixable, so let's check it explicitly.
3663
*/
3664
if (cgroup_is_populated(cgrp) ||
3665
cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3666
return -EOPNOTSUPP;
3667
3668
/* we're joining the parent's domain, ensure its validity */
3669
if (!cgroup_is_valid_domain(dom_cgrp) ||
3670
!cgroup_can_be_thread_root(dom_cgrp))
3671
return -EOPNOTSUPP;
3672
3673
/*
3674
* The following shouldn't cause actual migrations and should
3675
* always succeed.
3676
*/
3677
cgroup_save_control(cgrp);
3678
3679
cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3680
if (dsct == cgrp || cgroup_is_threaded(dsct))
3681
dsct->dom_cgrp = dom_cgrp;
3682
3683
ret = cgroup_apply_control(cgrp);
3684
if (!ret)
3685
parent->nr_threaded_children++;
3686
3687
cgroup_finalize_control(cgrp, ret);
3688
return ret;
3689
}
3690
3691
static int cgroup_type_show(struct seq_file *seq, void *v)
3692
{
3693
struct cgroup *cgrp = seq_css(seq)->cgroup;
3694
3695
if (cgroup_is_threaded(cgrp))
3696
seq_puts(seq, "threaded\n");
3697
else if (!cgroup_is_valid_domain(cgrp))
3698
seq_puts(seq, "domain invalid\n");
3699
else if (cgroup_is_thread_root(cgrp))
3700
seq_puts(seq, "domain threaded\n");
3701
else
3702
seq_puts(seq, "domain\n");
3703
3704
return 0;
3705
}
3706
3707
static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3708
size_t nbytes, loff_t off)
3709
{
3710
struct cgroup *cgrp;
3711
int ret;
3712
3713
/* only switching to threaded mode is supported */
3714
if (strcmp(strstrip(buf), "threaded"))
3715
return -EINVAL;
3716
3717
/* drain dying csses before we re-apply (threaded) subtree control */
3718
cgrp = cgroup_kn_lock_live(of->kn, true);
3719
if (!cgrp)
3720
return -ENOENT;
3721
3722
/* threaded can only be enabled */
3723
ret = cgroup_enable_threaded(cgrp);
3724
3725
cgroup_kn_unlock(of->kn);
3726
return ret ?: nbytes;
3727
}
3728
3729
static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3730
{
3731
struct cgroup *cgrp = seq_css(seq)->cgroup;
3732
int descendants = READ_ONCE(cgrp->max_descendants);
3733
3734
if (descendants == INT_MAX)
3735
seq_puts(seq, "max\n");
3736
else
3737
seq_printf(seq, "%d\n", descendants);
3738
3739
return 0;
3740
}
3741
3742
static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3743
char *buf, size_t nbytes, loff_t off)
3744
{
3745
struct cgroup *cgrp;
3746
int descendants;
3747
ssize_t ret;
3748
3749
buf = strstrip(buf);
3750
if (!strcmp(buf, "max")) {
3751
descendants = INT_MAX;
3752
} else {
3753
ret = kstrtoint(buf, 0, &descendants);
3754
if (ret)
3755
return ret;
3756
}
3757
3758
if (descendants < 0)
3759
return -ERANGE;
3760
3761
cgrp = cgroup_kn_lock_live(of->kn, false);
3762
if (!cgrp)
3763
return -ENOENT;
3764
3765
cgrp->max_descendants = descendants;
3766
3767
cgroup_kn_unlock(of->kn);
3768
3769
return nbytes;
3770
}
3771
3772
static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3773
{
3774
struct cgroup *cgrp = seq_css(seq)->cgroup;
3775
int depth = READ_ONCE(cgrp->max_depth);
3776
3777
if (depth == INT_MAX)
3778
seq_puts(seq, "max\n");
3779
else
3780
seq_printf(seq, "%d\n", depth);
3781
3782
return 0;
3783
}
3784
3785
static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3786
char *buf, size_t nbytes, loff_t off)
3787
{
3788
struct cgroup *cgrp;
3789
ssize_t ret;
3790
int depth;
3791
3792
buf = strstrip(buf);
3793
if (!strcmp(buf, "max")) {
3794
depth = INT_MAX;
3795
} else {
3796
ret = kstrtoint(buf, 0, &depth);
3797
if (ret)
3798
return ret;
3799
}
3800
3801
if (depth < 0)
3802
return -ERANGE;
3803
3804
cgrp = cgroup_kn_lock_live(of->kn, false);
3805
if (!cgrp)
3806
return -ENOENT;
3807
3808
cgrp->max_depth = depth;
3809
3810
cgroup_kn_unlock(of->kn);
3811
3812
return nbytes;
3813
}
3814
3815
static int cgroup_events_show(struct seq_file *seq, void *v)
3816
{
3817
struct cgroup *cgrp = seq_css(seq)->cgroup;
3818
3819
seq_printf(seq, "populated %d\n", cgroup_is_populated(cgrp));
3820
seq_printf(seq, "frozen %d\n", test_bit(CGRP_FROZEN, &cgrp->flags));
3821
3822
return 0;
3823
}
3824
3825
static int cgroup_stat_show(struct seq_file *seq, void *v)
3826
{
3827
struct cgroup *cgroup = seq_css(seq)->cgroup;
3828
struct cgroup_subsys_state *css;
3829
int dying_cnt[CGROUP_SUBSYS_COUNT];
3830
int ssid;
3831
3832
seq_printf(seq, "nr_descendants %d\n",
3833
cgroup->nr_descendants);
3834
3835
/*
3836
* Show the number of live and dying csses associated with each of
3837
* non-inhibited cgroup subsystems that is bound to cgroup v2.
3838
*
3839
* Without proper lock protection, racing is possible. So the
3840
* numbers may not be consistent when that happens.
3841
*/
3842
rcu_read_lock();
3843
for (ssid = 0; ssid < CGROUP_SUBSYS_COUNT; ssid++) {
3844
dying_cnt[ssid] = -1;
3845
if ((BIT(ssid) & cgrp_dfl_inhibit_ss_mask) ||
3846
(cgroup_subsys[ssid]->root != &cgrp_dfl_root))
3847
continue;
3848
css = rcu_dereference_raw(cgroup->subsys[ssid]);
3849
dying_cnt[ssid] = cgroup->nr_dying_subsys[ssid];
3850
seq_printf(seq, "nr_subsys_%s %d\n", cgroup_subsys[ssid]->name,
3851
css ? (css->nr_descendants + 1) : 0);
3852
}
3853
3854
seq_printf(seq, "nr_dying_descendants %d\n",
3855
cgroup->nr_dying_descendants);
3856
for (ssid = 0; ssid < CGROUP_SUBSYS_COUNT; ssid++) {
3857
if (dying_cnt[ssid] >= 0)
3858
seq_printf(seq, "nr_dying_subsys_%s %d\n",
3859
cgroup_subsys[ssid]->name, dying_cnt[ssid]);
3860
}
3861
rcu_read_unlock();
3862
return 0;
3863
}
3864
3865
static int cgroup_core_local_stat_show(struct seq_file *seq, void *v)
3866
{
3867
struct cgroup *cgrp = seq_css(seq)->cgroup;
3868
unsigned int sequence;
3869
u64 freeze_time;
3870
3871
do {
3872
sequence = read_seqcount_begin(&cgrp->freezer.freeze_seq);
3873
freeze_time = cgrp->freezer.frozen_nsec;
3874
/* Add in current freezer interval if the cgroup is freezing. */
3875
if (test_bit(CGRP_FREEZE, &cgrp->flags))
3876
freeze_time += (ktime_get_ns() -
3877
cgrp->freezer.freeze_start_nsec);
3878
} while (read_seqcount_retry(&cgrp->freezer.freeze_seq, sequence));
3879
3880
do_div(freeze_time, NSEC_PER_USEC);
3881
seq_printf(seq, "frozen_usec %llu\n", freeze_time);
3882
3883
return 0;
3884
}
3885
3886
#ifdef CONFIG_CGROUP_SCHED
3887
/**
3888
* cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
3889
* @cgrp: the cgroup of interest
3890
* @ss: the subsystem of interest
3891
*
3892
* Find and get @cgrp's css associated with @ss. If the css doesn't exist
3893
* or is offline, %NULL is returned.
3894
*/
3895
static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
3896
struct cgroup_subsys *ss)
3897
{
3898
struct cgroup_subsys_state *css;
3899
3900
rcu_read_lock();
3901
css = cgroup_css(cgrp, ss);
3902
if (css && !css_tryget_online(css))
3903
css = NULL;
3904
rcu_read_unlock();
3905
3906
return css;
3907
}
3908
3909
static int cgroup_extra_stat_show(struct seq_file *seq, int ssid)
3910
{
3911
struct cgroup *cgrp = seq_css(seq)->cgroup;
3912
struct cgroup_subsys *ss = cgroup_subsys[ssid];
3913
struct cgroup_subsys_state *css;
3914
int ret;
3915
3916
if (!ss->css_extra_stat_show)
3917
return 0;
3918
3919
css = cgroup_tryget_css(cgrp, ss);
3920
if (!css)
3921
return 0;
3922
3923
ret = ss->css_extra_stat_show(seq, css);
3924
css_put(css);
3925
return ret;
3926
}
3927
3928
static int cgroup_local_stat_show(struct seq_file *seq,
3929
struct cgroup *cgrp, int ssid)
3930
{
3931
struct cgroup_subsys *ss = cgroup_subsys[ssid];
3932
struct cgroup_subsys_state *css;
3933
int ret;
3934
3935
if (!ss->css_local_stat_show)
3936
return 0;
3937
3938
css = cgroup_tryget_css(cgrp, ss);
3939
if (!css)
3940
return 0;
3941
3942
ret = ss->css_local_stat_show(seq, css);
3943
css_put(css);
3944
return ret;
3945
}
3946
#endif
3947
3948
static int cpu_stat_show(struct seq_file *seq, void *v)
3949
{
3950
int ret = 0;
3951
3952
cgroup_base_stat_cputime_show(seq);
3953
#ifdef CONFIG_CGROUP_SCHED
3954
ret = cgroup_extra_stat_show(seq, cpu_cgrp_id);
3955
#endif
3956
return ret;
3957
}
3958
3959
static int cpu_local_stat_show(struct seq_file *seq, void *v)
3960
{
3961
struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3962
int ret = 0;
3963
3964
#ifdef CONFIG_CGROUP_SCHED
3965
ret = cgroup_local_stat_show(seq, cgrp, cpu_cgrp_id);
3966
#endif
3967
return ret;
3968
}
3969
3970
#ifdef CONFIG_PSI
3971
static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
3972
{
3973
struct cgroup *cgrp = seq_css(seq)->cgroup;
3974
struct psi_group *psi = cgroup_psi(cgrp);
3975
3976
return psi_show(seq, psi, PSI_IO);
3977
}
3978
static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
3979
{
3980
struct cgroup *cgrp = seq_css(seq)->cgroup;
3981
struct psi_group *psi = cgroup_psi(cgrp);
3982
3983
return psi_show(seq, psi, PSI_MEM);
3984
}
3985
static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
3986
{
3987
struct cgroup *cgrp = seq_css(seq)->cgroup;
3988
struct psi_group *psi = cgroup_psi(cgrp);
3989
3990
return psi_show(seq, psi, PSI_CPU);
3991
}
3992
3993
static ssize_t pressure_write(struct kernfs_open_file *of, char *buf,
3994
size_t nbytes, enum psi_res res)
3995
{
3996
struct cgroup_file_ctx *ctx = of->priv;
3997
struct psi_trigger *new;
3998
struct cgroup *cgrp;
3999
struct psi_group *psi;
4000
4001
cgrp = cgroup_kn_lock_live(of->kn, false);
4002
if (!cgrp)
4003
return -ENODEV;
4004
4005
cgroup_get(cgrp);
4006
cgroup_kn_unlock(of->kn);
4007
4008
/* Allow only one trigger per file descriptor */
4009
if (ctx->psi.trigger) {
4010
cgroup_put(cgrp);
4011
return -EBUSY;
4012
}
4013
4014
psi = cgroup_psi(cgrp);
4015
new = psi_trigger_create(psi, buf, res, of->file, of);
4016
if (IS_ERR(new)) {
4017
cgroup_put(cgrp);
4018
return PTR_ERR(new);
4019
}
4020
4021
smp_store_release(&ctx->psi.trigger, new);
4022
cgroup_put(cgrp);
4023
4024
return nbytes;
4025
}
4026
4027
static ssize_t cgroup_io_pressure_write(struct kernfs_open_file *of,
4028
char *buf, size_t nbytes,
4029
loff_t off)
4030
{
4031
return pressure_write(of, buf, nbytes, PSI_IO);
4032
}
4033
4034
static ssize_t cgroup_memory_pressure_write(struct kernfs_open_file *of,
4035
char *buf, size_t nbytes,
4036
loff_t off)
4037
{
4038
return pressure_write(of, buf, nbytes, PSI_MEM);
4039
}
4040
4041
static ssize_t cgroup_cpu_pressure_write(struct kernfs_open_file *of,
4042
char *buf, size_t nbytes,
4043
loff_t off)
4044
{
4045
return pressure_write(of, buf, nbytes, PSI_CPU);
4046
}
4047
4048
#ifdef CONFIG_IRQ_TIME_ACCOUNTING
4049
static int cgroup_irq_pressure_show(struct seq_file *seq, void *v)
4050
{
4051
struct cgroup *cgrp = seq_css(seq)->cgroup;
4052
struct psi_group *psi = cgroup_psi(cgrp);
4053
4054
return psi_show(seq, psi, PSI_IRQ);
4055
}
4056
4057
static ssize_t cgroup_irq_pressure_write(struct kernfs_open_file *of,
4058
char *buf, size_t nbytes,
4059
loff_t off)
4060
{
4061
return pressure_write(of, buf, nbytes, PSI_IRQ);
4062
}
4063
#endif
4064
4065
static int cgroup_pressure_show(struct seq_file *seq, void *v)
4066
{
4067
struct cgroup *cgrp = seq_css(seq)->cgroup;
4068
struct psi_group *psi = cgroup_psi(cgrp);
4069
4070
seq_printf(seq, "%d\n", psi->enabled);
4071
4072
return 0;
4073
}
4074
4075
static ssize_t cgroup_pressure_write(struct kernfs_open_file *of,
4076
char *buf, size_t nbytes,
4077
loff_t off)
4078
{
4079
ssize_t ret;
4080
int enable;
4081
struct cgroup *cgrp;
4082
struct psi_group *psi;
4083
4084
ret = kstrtoint(strstrip(buf), 0, &enable);
4085
if (ret)
4086
return ret;
4087
4088
if (enable < 0 || enable > 1)
4089
return -ERANGE;
4090
4091
cgrp = cgroup_kn_lock_live(of->kn, false);
4092
if (!cgrp)
4093
return -ENOENT;
4094
4095
psi = cgroup_psi(cgrp);
4096
if (psi->enabled != enable) {
4097
int i;
4098
4099
/* show or hide {cpu,memory,io,irq}.pressure files */
4100
for (i = 0; i < NR_PSI_RESOURCES; i++)
4101
cgroup_file_show(&cgrp->psi_files[i], enable);
4102
4103
psi->enabled = enable;
4104
if (enable)
4105
psi_cgroup_restart(psi);
4106
}
4107
4108
cgroup_kn_unlock(of->kn);
4109
4110
return nbytes;
4111
}
4112
4113
static __poll_t cgroup_pressure_poll(struct kernfs_open_file *of,
4114
poll_table *pt)
4115
{
4116
struct cgroup_file_ctx *ctx = of->priv;
4117
4118
return psi_trigger_poll(&ctx->psi.trigger, of->file, pt);
4119
}
4120
4121
static void cgroup_pressure_release(struct kernfs_open_file *of)
4122
{
4123
struct cgroup_file_ctx *ctx = of->priv;
4124
4125
psi_trigger_destroy(ctx->psi.trigger);
4126
}
4127
4128
bool cgroup_psi_enabled(void)
4129
{
4130
if (static_branch_likely(&psi_disabled))
4131
return false;
4132
4133
return (cgroup_feature_disable_mask & (1 << OPT_FEATURE_PRESSURE)) == 0;
4134
}
4135
4136
#else /* CONFIG_PSI */
4137
bool cgroup_psi_enabled(void)
4138
{
4139
return false;
4140
}
4141
4142
#endif /* CONFIG_PSI */
4143
4144
static int cgroup_freeze_show(struct seq_file *seq, void *v)
4145
{
4146
struct cgroup *cgrp = seq_css(seq)->cgroup;
4147
4148
seq_printf(seq, "%d\n", cgrp->freezer.freeze);
4149
4150
return 0;
4151
}
4152
4153
static ssize_t cgroup_freeze_write(struct kernfs_open_file *of,
4154
char *buf, size_t nbytes, loff_t off)
4155
{
4156
struct cgroup *cgrp;
4157
ssize_t ret;
4158
int freeze;
4159
4160
ret = kstrtoint(strstrip(buf), 0, &freeze);
4161
if (ret)
4162
return ret;
4163
4164
if (freeze < 0 || freeze > 1)
4165
return -ERANGE;
4166
4167
cgrp = cgroup_kn_lock_live(of->kn, false);
4168
if (!cgrp)
4169
return -ENOENT;
4170
4171
cgroup_freeze(cgrp, freeze);
4172
4173
cgroup_kn_unlock(of->kn);
4174
4175
return nbytes;
4176
}
4177
4178
static void __cgroup_kill(struct cgroup *cgrp)
4179
{
4180
struct css_task_iter it;
4181
struct task_struct *task;
4182
4183
lockdep_assert_held(&cgroup_mutex);
4184
4185
spin_lock_irq(&css_set_lock);
4186
cgrp->kill_seq++;
4187
spin_unlock_irq(&css_set_lock);
4188
4189
css_task_iter_start(&cgrp->self, CSS_TASK_ITER_PROCS | CSS_TASK_ITER_THREADED, &it);
4190
while ((task = css_task_iter_next(&it))) {
4191
/* Ignore kernel threads here. */
4192
if (task->flags & PF_KTHREAD)
4193
continue;
4194
4195
/* Skip tasks that are already dying. */
4196
if (__fatal_signal_pending(task))
4197
continue;
4198
4199
send_sig(SIGKILL, task, 0);
4200
}
4201
css_task_iter_end(&it);
4202
}
4203
4204
static void cgroup_kill(struct cgroup *cgrp)
4205
{
4206
struct cgroup_subsys_state *css;
4207
struct cgroup *dsct;
4208
4209
lockdep_assert_held(&cgroup_mutex);
4210
4211
cgroup_for_each_live_descendant_pre(dsct, css, cgrp)
4212
__cgroup_kill(dsct);
4213
}
4214
4215
static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf,
4216
size_t nbytes, loff_t off)
4217
{
4218
ssize_t ret = 0;
4219
int kill;
4220
struct cgroup *cgrp;
4221
4222
ret = kstrtoint(strstrip(buf), 0, &kill);
4223
if (ret)
4224
return ret;
4225
4226
if (kill != 1)
4227
return -ERANGE;
4228
4229
cgrp = cgroup_kn_lock_live(of->kn, false);
4230
if (!cgrp)
4231
return -ENOENT;
4232
4233
/*
4234
* Killing is a process directed operation, i.e. the whole thread-group
4235
* is taken down so act like we do for cgroup.procs and only make this
4236
* writable in non-threaded cgroups.
4237
*/
4238
if (cgroup_is_threaded(cgrp))
4239
ret = -EOPNOTSUPP;
4240
else
4241
cgroup_kill(cgrp);
4242
4243
cgroup_kn_unlock(of->kn);
4244
4245
return ret ?: nbytes;
4246
}
4247
4248
static int cgroup_file_open(struct kernfs_open_file *of)
4249
{
4250
struct cftype *cft = of_cft(of);
4251
struct cgroup_file_ctx *ctx;
4252
int ret;
4253
4254
ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
4255
if (!ctx)
4256
return -ENOMEM;
4257
4258
ctx->ns = current->nsproxy->cgroup_ns;
4259
get_cgroup_ns(ctx->ns);
4260
of->priv = ctx;
4261
4262
if (!cft->open)
4263
return 0;
4264
4265
ret = cft->open(of);
4266
if (ret) {
4267
put_cgroup_ns(ctx->ns);
4268
kfree(ctx);
4269
}
4270
return ret;
4271
}
4272
4273
static void cgroup_file_release(struct kernfs_open_file *of)
4274
{
4275
struct cftype *cft = of_cft(of);
4276
struct cgroup_file_ctx *ctx = of->priv;
4277
4278
if (cft->release)
4279
cft->release(of);
4280
put_cgroup_ns(ctx->ns);
4281
kfree(ctx);
4282
of->priv = NULL;
4283
}
4284
4285
static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
4286
size_t nbytes, loff_t off)
4287
{
4288
struct cgroup_file_ctx *ctx = of->priv;
4289
struct cgroup *cgrp = kn_priv(of->kn);
4290
struct cftype *cft = of_cft(of);
4291
struct cgroup_subsys_state *css;
4292
int ret;
4293
4294
if (!nbytes)
4295
return 0;
4296
4297
/*
4298
* If namespaces are delegation boundaries, disallow writes to
4299
* files in an non-init namespace root from inside the namespace
4300
* except for the files explicitly marked delegatable -
4301
* eg. cgroup.procs, cgroup.threads and cgroup.subtree_control.
4302
*/
4303
if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
4304
!(cft->flags & CFTYPE_NS_DELEGATABLE) &&
4305
ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
4306
return -EPERM;
4307
4308
if (cft->write)
4309
return cft->write(of, buf, nbytes, off);
4310
4311
/*
4312
* kernfs guarantees that a file isn't deleted with operations in
4313
* flight, which means that the matching css is and stays alive and
4314
* doesn't need to be pinned. The RCU locking is not necessary
4315
* either. It's just for the convenience of using cgroup_css().
4316
*/
4317
rcu_read_lock();
4318
css = cgroup_css(cgrp, cft->ss);
4319
rcu_read_unlock();
4320
4321
if (cft->write_u64) {
4322
unsigned long long v;
4323
ret = kstrtoull(buf, 0, &v);
4324
if (!ret)
4325
ret = cft->write_u64(css, cft, v);
4326
} else if (cft->write_s64) {
4327
long long v;
4328
ret = kstrtoll(buf, 0, &v);
4329
if (!ret)
4330
ret = cft->write_s64(css, cft, v);
4331
} else {
4332
ret = -EINVAL;
4333
}
4334
4335
return ret ?: nbytes;
4336
}
4337
4338
static __poll_t cgroup_file_poll(struct kernfs_open_file *of, poll_table *pt)
4339
{
4340
struct cftype *cft = of_cft(of);
4341
4342
if (cft->poll)
4343
return cft->poll(of, pt);
4344
4345
return kernfs_generic_poll(of, pt);
4346
}
4347
4348
static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
4349
{
4350
return seq_cft(seq)->seq_start(seq, ppos);
4351
}
4352
4353
static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
4354
{
4355
return seq_cft(seq)->seq_next(seq, v, ppos);
4356
}
4357
4358
static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
4359
{
4360
if (seq_cft(seq)->seq_stop)
4361
seq_cft(seq)->seq_stop(seq, v);
4362
}
4363
4364
static int cgroup_seqfile_show(struct seq_file *m, void *arg)
4365
{
4366
struct cftype *cft = seq_cft(m);
4367
struct cgroup_subsys_state *css = seq_css(m);
4368
4369
if (cft->seq_show)
4370
return cft->seq_show(m, arg);
4371
4372
if (cft->read_u64)
4373
seq_printf(m, "%llu\n", cft->read_u64(css, cft));
4374
else if (cft->read_s64)
4375
seq_printf(m, "%lld\n", cft->read_s64(css, cft));
4376
else
4377
return -EINVAL;
4378
return 0;
4379
}
4380
4381
static struct kernfs_ops cgroup_kf_single_ops = {
4382
.atomic_write_len = PAGE_SIZE,
4383
.open = cgroup_file_open,
4384
.release = cgroup_file_release,
4385
.write = cgroup_file_write,
4386
.poll = cgroup_file_poll,
4387
.seq_show = cgroup_seqfile_show,
4388
};
4389
4390
static struct kernfs_ops cgroup_kf_ops = {
4391
.atomic_write_len = PAGE_SIZE,
4392
.open = cgroup_file_open,
4393
.release = cgroup_file_release,
4394
.write = cgroup_file_write,
4395
.poll = cgroup_file_poll,
4396
.seq_start = cgroup_seqfile_start,
4397
.seq_next = cgroup_seqfile_next,
4398
.seq_stop = cgroup_seqfile_stop,
4399
.seq_show = cgroup_seqfile_show,
4400
};
4401
4402
static void cgroup_file_notify_timer(struct timer_list *timer)
4403
{
4404
cgroup_file_notify(container_of(timer, struct cgroup_file,
4405
notify_timer));
4406
}
4407
4408
static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
4409
struct cftype *cft)
4410
{
4411
char name[CGROUP_FILE_NAME_MAX];
4412
struct kernfs_node *kn;
4413
struct lock_class_key *key = NULL;
4414
4415
#ifdef CONFIG_DEBUG_LOCK_ALLOC
4416
key = &cft->lockdep_key;
4417
#endif
4418
kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
4419
cgroup_file_mode(cft),
4420
current_fsuid(), current_fsgid(),
4421
0, cft->kf_ops, cft,
4422
NULL, key);
4423
if (IS_ERR(kn))
4424
return PTR_ERR(kn);
4425
4426
if (cft->file_offset) {
4427
struct cgroup_file *cfile = (void *)css + cft->file_offset;
4428
4429
timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
4430
4431
spin_lock_irq(&cgroup_file_kn_lock);
4432
cfile->kn = kn;
4433
spin_unlock_irq(&cgroup_file_kn_lock);
4434
}
4435
4436
return 0;
4437
}
4438
4439
/**
4440
* cgroup_addrm_files - add or remove files to a cgroup directory
4441
* @css: the target css
4442
* @cgrp: the target cgroup (usually css->cgroup)
4443
* @cfts: array of cftypes to be added
4444
* @is_add: whether to add or remove
4445
*
4446
* Depending on @is_add, add or remove files defined by @cfts on @cgrp.
4447
* For removals, this function never fails.
4448
*/
4449
static int cgroup_addrm_files(struct cgroup_subsys_state *css,
4450
struct cgroup *cgrp, struct cftype cfts[],
4451
bool is_add)
4452
{
4453
struct cftype *cft, *cft_end = NULL;
4454
int ret = 0;
4455
4456
lockdep_assert_held(&cgroup_mutex);
4457
4458
restart:
4459
for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
4460
/* does cft->flags tell us to skip this file on @cgrp? */
4461
if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
4462
continue;
4463
if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
4464
continue;
4465
if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
4466
continue;
4467
if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
4468
continue;
4469
if ((cft->flags & CFTYPE_DEBUG) && !cgroup_debug)
4470
continue;
4471
if (is_add) {
4472
ret = cgroup_add_file(css, cgrp, cft);
4473
if (ret) {
4474
pr_warn("%s: failed to add %s, err=%d\n",
4475
__func__, cft->name, ret);
4476
cft_end = cft;
4477
is_add = false;
4478
goto restart;
4479
}
4480
} else {
4481
cgroup_rm_file(cgrp, cft);
4482
}
4483
}
4484
return ret;
4485
}
4486
4487
static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
4488
{
4489
struct cgroup_subsys *ss = cfts[0].ss;
4490
struct cgroup *root = &ss->root->cgrp;
4491
struct cgroup_subsys_state *css;
4492
int ret = 0;
4493
4494
lockdep_assert_held(&cgroup_mutex);
4495
4496
/* add/rm files for all cgroups created before */
4497
css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
4498
struct cgroup *cgrp = css->cgroup;
4499
4500
if (!(css->flags & CSS_VISIBLE))
4501
continue;
4502
4503
ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
4504
if (ret)
4505
break;
4506
}
4507
4508
if (is_add && !ret)
4509
kernfs_activate(root->kn);
4510
return ret;
4511
}
4512
4513
static void cgroup_exit_cftypes(struct cftype *cfts)
4514
{
4515
struct cftype *cft;
4516
4517
for (cft = cfts; cft->name[0] != '\0'; cft++) {
4518
/* free copy for custom atomic_write_len, see init_cftypes() */
4519
if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
4520
kfree(cft->kf_ops);
4521
cft->kf_ops = NULL;
4522
cft->ss = NULL;
4523
4524
/* revert flags set by cgroup core while adding @cfts */
4525
cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL |
4526
__CFTYPE_ADDED);
4527
}
4528
}
4529
4530
static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4531
{
4532
struct cftype *cft;
4533
int ret = 0;
4534
4535
for (cft = cfts; cft->name[0] != '\0'; cft++) {
4536
struct kernfs_ops *kf_ops;
4537
4538
WARN_ON(cft->ss || cft->kf_ops);
4539
4540
if (cft->flags & __CFTYPE_ADDED) {
4541
ret = -EBUSY;
4542
break;
4543
}
4544
4545
if (cft->seq_start)
4546
kf_ops = &cgroup_kf_ops;
4547
else
4548
kf_ops = &cgroup_kf_single_ops;
4549
4550
/*
4551
* Ugh... if @cft wants a custom max_write_len, we need to
4552
* make a copy of kf_ops to set its atomic_write_len.
4553
*/
4554
if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
4555
kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
4556
if (!kf_ops) {
4557
ret = -ENOMEM;
4558
break;
4559
}
4560
kf_ops->atomic_write_len = cft->max_write_len;
4561
}
4562
4563
cft->kf_ops = kf_ops;
4564
cft->ss = ss;
4565
cft->flags |= __CFTYPE_ADDED;
4566
}
4567
4568
if (ret)
4569
cgroup_exit_cftypes(cfts);
4570
return ret;
4571
}
4572
4573
static void cgroup_rm_cftypes_locked(struct cftype *cfts)
4574
{
4575
lockdep_assert_held(&cgroup_mutex);
4576
4577
list_del(&cfts->node);
4578
cgroup_apply_cftypes(cfts, false);
4579
cgroup_exit_cftypes(cfts);
4580
}
4581
4582
/**
4583
* cgroup_rm_cftypes - remove an array of cftypes from a subsystem
4584
* @cfts: zero-length name terminated array of cftypes
4585
*
4586
* Unregister @cfts. Files described by @cfts are removed from all
4587
* existing cgroups and all future cgroups won't have them either. This
4588
* function can be called anytime whether @cfts' subsys is attached or not.
4589
*
4590
* Returns 0 on successful unregistration, -ENOENT if @cfts is not
4591
* registered.
4592
*/
4593
int cgroup_rm_cftypes(struct cftype *cfts)
4594
{
4595
if (!cfts || cfts[0].name[0] == '\0')
4596
return 0;
4597
4598
if (!(cfts[0].flags & __CFTYPE_ADDED))
4599
return -ENOENT;
4600
4601
cgroup_lock();
4602
cgroup_rm_cftypes_locked(cfts);
4603
cgroup_unlock();
4604
return 0;
4605
}
4606
4607
/**
4608
* cgroup_add_cftypes - add an array of cftypes to a subsystem
4609
* @ss: target cgroup subsystem
4610
* @cfts: zero-length name terminated array of cftypes
4611
*
4612
* Register @cfts to @ss. Files described by @cfts are created for all
4613
* existing cgroups to which @ss is attached and all future cgroups will
4614
* have them too. This function can be called anytime whether @ss is
4615
* attached or not.
4616
*
4617
* Returns 0 on successful registration, -errno on failure. Note that this
4618
* function currently returns 0 as long as @cfts registration is successful
4619
* even if some file creation attempts on existing cgroups fail.
4620
*/
4621
int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4622
{
4623
int ret;
4624
4625
if (!cgroup_ssid_enabled(ss->id))
4626
return 0;
4627
4628
if (!cfts || cfts[0].name[0] == '\0')
4629
return 0;
4630
4631
ret = cgroup_init_cftypes(ss, cfts);
4632
if (ret)
4633
return ret;
4634
4635
cgroup_lock();
4636
4637
list_add_tail(&cfts->node, &ss->cfts);
4638
ret = cgroup_apply_cftypes(cfts, true);
4639
if (ret)
4640
cgroup_rm_cftypes_locked(cfts);
4641
4642
cgroup_unlock();
4643
return ret;
4644
}
4645
4646
/**
4647
* cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
4648
* @ss: target cgroup subsystem
4649
* @cfts: zero-length name terminated array of cftypes
4650
*
4651
* Similar to cgroup_add_cftypes() but the added files are only used for
4652
* the default hierarchy.
4653
*/
4654
int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4655
{
4656
struct cftype *cft;
4657
4658
for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4659
cft->flags |= __CFTYPE_ONLY_ON_DFL;
4660
return cgroup_add_cftypes(ss, cfts);
4661
}
4662
4663
/**
4664
* cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
4665
* @ss: target cgroup subsystem
4666
* @cfts: zero-length name terminated array of cftypes
4667
*
4668
* Similar to cgroup_add_cftypes() but the added files are only used for
4669
* the legacy hierarchies.
4670
*/
4671
int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4672
{
4673
struct cftype *cft;
4674
4675
for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4676
cft->flags |= __CFTYPE_NOT_ON_DFL;
4677
return cgroup_add_cftypes(ss, cfts);
4678
}
4679
4680
/**
4681
* cgroup_file_notify - generate a file modified event for a cgroup_file
4682
* @cfile: target cgroup_file
4683
*
4684
* @cfile must have been obtained by setting cftype->file_offset.
4685
*/
4686
void cgroup_file_notify(struct cgroup_file *cfile)
4687
{
4688
unsigned long flags;
4689
4690
spin_lock_irqsave(&cgroup_file_kn_lock, flags);
4691
if (cfile->kn) {
4692
unsigned long last = cfile->notified_at;
4693
unsigned long next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
4694
4695
if (time_in_range(jiffies, last, next)) {
4696
timer_reduce(&cfile->notify_timer, next);
4697
} else {
4698
kernfs_notify(cfile->kn);
4699
cfile->notified_at = jiffies;
4700
}
4701
}
4702
spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
4703
}
4704
EXPORT_SYMBOL_GPL(cgroup_file_notify);
4705
4706
/**
4707
* cgroup_file_show - show or hide a hidden cgroup file
4708
* @cfile: target cgroup_file obtained by setting cftype->file_offset
4709
* @show: whether to show or hide
4710
*/
4711
void cgroup_file_show(struct cgroup_file *cfile, bool show)
4712
{
4713
struct kernfs_node *kn;
4714
4715
spin_lock_irq(&cgroup_file_kn_lock);
4716
kn = cfile->kn;
4717
kernfs_get(kn);
4718
spin_unlock_irq(&cgroup_file_kn_lock);
4719
4720
if (kn)
4721
kernfs_show(kn, show);
4722
4723
kernfs_put(kn);
4724
}
4725
4726
/**
4727
* css_next_child - find the next child of a given css
4728
* @pos: the current position (%NULL to initiate traversal)
4729
* @parent: css whose children to walk
4730
*
4731
* This function returns the next child of @parent and should be called
4732
* under either cgroup_mutex or RCU read lock. The only requirement is
4733
* that @parent and @pos are accessible. The next sibling is guaranteed to
4734
* be returned regardless of their states.
4735
*
4736
* If a subsystem synchronizes ->css_online() and the start of iteration, a
4737
* css which finished ->css_online() is guaranteed to be visible in the
4738
* future iterations and will stay visible until the last reference is put.
4739
* A css which hasn't finished ->css_online() or already finished
4740
* ->css_offline() may show up during traversal. It's each subsystem's
4741
* responsibility to synchronize against on/offlining.
4742
*/
4743
struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
4744
struct cgroup_subsys_state *parent)
4745
{
4746
struct cgroup_subsys_state *next;
4747
4748
cgroup_assert_mutex_or_rcu_locked();
4749
4750
/*
4751
* @pos could already have been unlinked from the sibling list.
4752
* Once a cgroup is removed, its ->sibling.next is no longer
4753
* updated when its next sibling changes. CSS_RELEASED is set when
4754
* @pos is taken off list, at which time its next pointer is valid,
4755
* and, as releases are serialized, the one pointed to by the next
4756
* pointer is guaranteed to not have started release yet. This
4757
* implies that if we observe !CSS_RELEASED on @pos in this RCU
4758
* critical section, the one pointed to by its next pointer is
4759
* guaranteed to not have finished its RCU grace period even if we
4760
* have dropped rcu_read_lock() in-between iterations.
4761
*
4762
* If @pos has CSS_RELEASED set, its next pointer can't be
4763
* dereferenced; however, as each css is given a monotonically
4764
* increasing unique serial number and always appended to the
4765
* sibling list, the next one can be found by walking the parent's
4766
* children until the first css with higher serial number than
4767
* @pos's. While this path can be slower, it happens iff iteration
4768
* races against release and the race window is very small.
4769
*/
4770
if (!pos) {
4771
next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
4772
} else if (likely(!(pos->flags & CSS_RELEASED))) {
4773
next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
4774
} else {
4775
list_for_each_entry_rcu(next, &parent->children, sibling,
4776
lockdep_is_held(&cgroup_mutex))
4777
if (next->serial_nr > pos->serial_nr)
4778
break;
4779
}
4780
4781
/*
4782
* @next, if not pointing to the head, can be dereferenced and is
4783
* the next sibling.
4784
*/
4785
if (&next->sibling != &parent->children)
4786
return next;
4787
return NULL;
4788
}
4789
4790
/**
4791
* css_next_descendant_pre - find the next descendant for pre-order walk
4792
* @pos: the current position (%NULL to initiate traversal)
4793
* @root: css whose descendants to walk
4794
*
4795
* To be used by css_for_each_descendant_pre(). Find the next descendant
4796
* to visit for pre-order traversal of @root's descendants. @root is
4797
* included in the iteration and the first node to be visited.
4798
*
4799
* While this function requires cgroup_mutex or RCU read locking, it
4800
* doesn't require the whole traversal to be contained in a single critical
4801
* section. Additionally, it isn't necessary to hold onto a reference to @pos.
4802
* This function will return the correct next descendant as long as both @pos
4803
* and @root are accessible and @pos is a descendant of @root.
4804
*
4805
* If a subsystem synchronizes ->css_online() and the start of iteration, a
4806
* css which finished ->css_online() is guaranteed to be visible in the
4807
* future iterations and will stay visible until the last reference is put.
4808
* A css which hasn't finished ->css_online() or already finished
4809
* ->css_offline() may show up during traversal. It's each subsystem's
4810
* responsibility to synchronize against on/offlining.
4811
*/
4812
struct cgroup_subsys_state *
4813
css_next_descendant_pre(struct cgroup_subsys_state *pos,
4814
struct cgroup_subsys_state *root)
4815
{
4816
struct cgroup_subsys_state *next;
4817
4818
cgroup_assert_mutex_or_rcu_locked();
4819
4820
/* if first iteration, visit @root */
4821
if (!pos)
4822
return root;
4823
4824
/* visit the first child if exists */
4825
next = css_next_child(NULL, pos);
4826
if (next)
4827
return next;
4828
4829
/* no child, visit my or the closest ancestor's next sibling */
4830
while (pos != root) {
4831
next = css_next_child(pos, pos->parent);
4832
if (next)
4833
return next;
4834
pos = pos->parent;
4835
}
4836
4837
return NULL;
4838
}
4839
EXPORT_SYMBOL_GPL(css_next_descendant_pre);
4840
4841
/**
4842
* css_rightmost_descendant - return the rightmost descendant of a css
4843
* @pos: css of interest
4844
*
4845
* Return the rightmost descendant of @pos. If there's no descendant, @pos
4846
* is returned. This can be used during pre-order traversal to skip
4847
* subtree of @pos.
4848
*
4849
* While this function requires cgroup_mutex or RCU read locking, it
4850
* doesn't require the whole traversal to be contained in a single critical
4851
* section. Additionally, it isn't necessary to hold onto a reference to @pos.
4852
* This function will return the correct rightmost descendant as long as @pos
4853
* is accessible.
4854
*/
4855
struct cgroup_subsys_state *
4856
css_rightmost_descendant(struct cgroup_subsys_state *pos)
4857
{
4858
struct cgroup_subsys_state *last, *tmp;
4859
4860
cgroup_assert_mutex_or_rcu_locked();
4861
4862
do {
4863
last = pos;
4864
/* ->prev isn't RCU safe, walk ->next till the end */
4865
pos = NULL;
4866
css_for_each_child(tmp, last)
4867
pos = tmp;
4868
} while (pos);
4869
4870
return last;
4871
}
4872
4873
static struct cgroup_subsys_state *
4874
css_leftmost_descendant(struct cgroup_subsys_state *pos)
4875
{
4876
struct cgroup_subsys_state *last;
4877
4878
do {
4879
last = pos;
4880
pos = css_next_child(NULL, pos);
4881
} while (pos);
4882
4883
return last;
4884
}
4885
4886
/**
4887
* css_next_descendant_post - find the next descendant for post-order walk
4888
* @pos: the current position (%NULL to initiate traversal)
4889
* @root: css whose descendants to walk
4890
*
4891
* To be used by css_for_each_descendant_post(). Find the next descendant
4892
* to visit for post-order traversal of @root's descendants. @root is
4893
* included in the iteration and the last node to be visited.
4894
*
4895
* While this function requires cgroup_mutex or RCU read locking, it
4896
* doesn't require the whole traversal to be contained in a single critical
4897
* section. Additionally, it isn't necessary to hold onto a reference to @pos.
4898
* This function will return the correct next descendant as long as both @pos
4899
* and @cgroup are accessible and @pos is a descendant of @cgroup.
4900
*
4901
* If a subsystem synchronizes ->css_online() and the start of iteration, a
4902
* css which finished ->css_online() is guaranteed to be visible in the
4903
* future iterations and will stay visible until the last reference is put.
4904
* A css which hasn't finished ->css_online() or already finished
4905
* ->css_offline() may show up during traversal. It's each subsystem's
4906
* responsibility to synchronize against on/offlining.
4907
*/
4908
struct cgroup_subsys_state *
4909
css_next_descendant_post(struct cgroup_subsys_state *pos,
4910
struct cgroup_subsys_state *root)
4911
{
4912
struct cgroup_subsys_state *next;
4913
4914
cgroup_assert_mutex_or_rcu_locked();
4915
4916
/* if first iteration, visit leftmost descendant which may be @root */
4917
if (!pos)
4918
return css_leftmost_descendant(root);
4919
4920
/* if we visited @root, we're done */
4921
if (pos == root)
4922
return NULL;
4923
4924
/* if there's an unvisited sibling, visit its leftmost descendant */
4925
next = css_next_child(pos, pos->parent);
4926
if (next)
4927
return css_leftmost_descendant(next);
4928
4929
/* no sibling left, visit parent */
4930
return pos->parent;
4931
}
4932
4933
/**
4934
* css_has_online_children - does a css have online children
4935
* @css: the target css
4936
*
4937
* Returns %true if @css has any online children; otherwise, %false. This
4938
* function can be called from any context but the caller is responsible
4939
* for synchronizing against on/offlining as necessary.
4940
*/
4941
bool css_has_online_children(struct cgroup_subsys_state *css)
4942
{
4943
struct cgroup_subsys_state *child;
4944
bool ret = false;
4945
4946
rcu_read_lock();
4947
css_for_each_child(child, css) {
4948
if (child->flags & CSS_ONLINE) {
4949
ret = true;
4950
break;
4951
}
4952
}
4953
rcu_read_unlock();
4954
return ret;
4955
}
4956
4957
static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4958
{
4959
struct list_head *l;
4960
struct cgrp_cset_link *link;
4961
struct css_set *cset;
4962
4963
lockdep_assert_held(&css_set_lock);
4964
4965
/* find the next threaded cset */
4966
if (it->tcset_pos) {
4967
l = it->tcset_pos->next;
4968
4969
if (l != it->tcset_head) {
4970
it->tcset_pos = l;
4971
return container_of(l, struct css_set,
4972
threaded_csets_node);
4973
}
4974
4975
it->tcset_pos = NULL;
4976
}
4977
4978
/* find the next cset */
4979
l = it->cset_pos;
4980
l = l->next;
4981
if (l == it->cset_head) {
4982
it->cset_pos = NULL;
4983
return NULL;
4984
}
4985
4986
if (it->ss) {
4987
cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4988
} else {
4989
link = list_entry(l, struct cgrp_cset_link, cset_link);
4990
cset = link->cset;
4991
}
4992
4993
it->cset_pos = l;
4994
4995
/* initialize threaded css_set walking */
4996
if (it->flags & CSS_TASK_ITER_THREADED) {
4997
if (it->cur_dcset)
4998
put_css_set_locked(it->cur_dcset);
4999
it->cur_dcset = cset;
5000
get_css_set(cset);
5001
5002
it->tcset_head = &cset->threaded_csets;
5003
it->tcset_pos = &cset->threaded_csets;
5004
}
5005
5006
return cset;
5007
}
5008
5009
/**
5010
* css_task_iter_advance_css_set - advance a task iterator to the next css_set
5011
* @it: the iterator to advance
5012
*
5013
* Advance @it to the next css_set to walk.
5014
*/
5015
static void css_task_iter_advance_css_set(struct css_task_iter *it)
5016
{
5017
struct css_set *cset;
5018
5019
lockdep_assert_held(&css_set_lock);
5020
5021
/* Advance to the next non-empty css_set and find first non-empty tasks list*/
5022
while ((cset = css_task_iter_next_css_set(it))) {
5023
if (!list_empty(&cset->tasks)) {
5024
it->cur_tasks_head = &cset->tasks;
5025
break;
5026
} else if (!list_empty(&cset->mg_tasks)) {
5027
it->cur_tasks_head = &cset->mg_tasks;
5028
break;
5029
} else if (!list_empty(&cset->dying_tasks)) {
5030
it->cur_tasks_head = &cset->dying_tasks;
5031
break;
5032
}
5033
}
5034
if (!cset) {
5035
it->task_pos = NULL;
5036
return;
5037
}
5038
it->task_pos = it->cur_tasks_head->next;
5039
5040
/*
5041
* We don't keep css_sets locked across iteration steps and thus
5042
* need to take steps to ensure that iteration can be resumed after
5043
* the lock is re-acquired. Iteration is performed at two levels -
5044
* css_sets and tasks in them.
5045
*
5046
* Once created, a css_set never leaves its cgroup lists, so a
5047
* pinned css_set is guaranteed to stay put and we can resume
5048
* iteration afterwards.
5049
*
5050
* Tasks may leave @cset across iteration steps. This is resolved
5051
* by registering each iterator with the css_set currently being
5052
* walked and making css_set_move_task() advance iterators whose
5053
* next task is leaving.
5054
*/
5055
if (it->cur_cset) {
5056
list_del(&it->iters_node);
5057
put_css_set_locked(it->cur_cset);
5058
}
5059
get_css_set(cset);
5060
it->cur_cset = cset;
5061
list_add(&it->iters_node, &cset->task_iters);
5062
}
5063
5064
static void css_task_iter_skip(struct css_task_iter *it,
5065
struct task_struct *task)
5066
{
5067
lockdep_assert_held(&css_set_lock);
5068
5069
if (it->task_pos == &task->cg_list) {
5070
it->task_pos = it->task_pos->next;
5071
it->flags |= CSS_TASK_ITER_SKIPPED;
5072
}
5073
}
5074
5075
static void css_task_iter_advance(struct css_task_iter *it)
5076
{
5077
struct task_struct *task;
5078
5079
lockdep_assert_held(&css_set_lock);
5080
repeat:
5081
if (it->task_pos) {
5082
/*
5083
* Advance iterator to find next entry. We go through cset
5084
* tasks, mg_tasks and dying_tasks, when consumed we move onto
5085
* the next cset.
5086
*/
5087
if (it->flags & CSS_TASK_ITER_SKIPPED)
5088
it->flags &= ~CSS_TASK_ITER_SKIPPED;
5089
else
5090
it->task_pos = it->task_pos->next;
5091
5092
if (it->task_pos == &it->cur_cset->tasks) {
5093
it->cur_tasks_head = &it->cur_cset->mg_tasks;
5094
it->task_pos = it->cur_tasks_head->next;
5095
}
5096
if (it->task_pos == &it->cur_cset->mg_tasks) {
5097
it->cur_tasks_head = &it->cur_cset->dying_tasks;
5098
it->task_pos = it->cur_tasks_head->next;
5099
}
5100
if (it->task_pos == &it->cur_cset->dying_tasks)
5101
css_task_iter_advance_css_set(it);
5102
} else {
5103
/* called from start, proceed to the first cset */
5104
css_task_iter_advance_css_set(it);
5105
}
5106
5107
if (!it->task_pos)
5108
return;
5109
5110
task = list_entry(it->task_pos, struct task_struct, cg_list);
5111
5112
if (it->flags & CSS_TASK_ITER_PROCS) {
5113
/* if PROCS, skip over tasks which aren't group leaders */
5114
if (!thread_group_leader(task))
5115
goto repeat;
5116
5117
/* and dying leaders w/o live member threads */
5118
if (it->cur_tasks_head == &it->cur_cset->dying_tasks &&
5119
!atomic_read(&task->signal->live))
5120
goto repeat;
5121
} else {
5122
/* skip all dying ones */
5123
if (it->cur_tasks_head == &it->cur_cset->dying_tasks)
5124
goto repeat;
5125
}
5126
}
5127
5128
/**
5129
* css_task_iter_start - initiate task iteration
5130
* @css: the css to walk tasks of
5131
* @flags: CSS_TASK_ITER_* flags
5132
* @it: the task iterator to use
5133
*
5134
* Initiate iteration through the tasks of @css. The caller can call
5135
* css_task_iter_next() to walk through the tasks until the function
5136
* returns NULL. On completion of iteration, css_task_iter_end() must be
5137
* called.
5138
*/
5139
void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
5140
struct css_task_iter *it)
5141
{
5142
unsigned long irqflags;
5143
5144
memset(it, 0, sizeof(*it));
5145
5146
spin_lock_irqsave(&css_set_lock, irqflags);
5147
5148
it->ss = css->ss;
5149
it->flags = flags;
5150
5151
if (CGROUP_HAS_SUBSYS_CONFIG && it->ss)
5152
it->cset_pos = &css->cgroup->e_csets[css->ss->id];
5153
else
5154
it->cset_pos = &css->cgroup->cset_links;
5155
5156
it->cset_head = it->cset_pos;
5157
5158
css_task_iter_advance(it);
5159
5160
spin_unlock_irqrestore(&css_set_lock, irqflags);
5161
}
5162
5163
/**
5164
* css_task_iter_next - return the next task for the iterator
5165
* @it: the task iterator being iterated
5166
*
5167
* The "next" function for task iteration. @it should have been
5168
* initialized via css_task_iter_start(). Returns NULL when the iteration
5169
* reaches the end.
5170
*/
5171
struct task_struct *css_task_iter_next(struct css_task_iter *it)
5172
{
5173
unsigned long irqflags;
5174
5175
if (it->cur_task) {
5176
put_task_struct(it->cur_task);
5177
it->cur_task = NULL;
5178
}
5179
5180
spin_lock_irqsave(&css_set_lock, irqflags);
5181
5182
/* @it may be half-advanced by skips, finish advancing */
5183
if (it->flags & CSS_TASK_ITER_SKIPPED)
5184
css_task_iter_advance(it);
5185
5186
if (it->task_pos) {
5187
it->cur_task = list_entry(it->task_pos, struct task_struct,
5188
cg_list);
5189
get_task_struct(it->cur_task);
5190
css_task_iter_advance(it);
5191
}
5192
5193
spin_unlock_irqrestore(&css_set_lock, irqflags);
5194
5195
return it->cur_task;
5196
}
5197
5198
/**
5199
* css_task_iter_end - finish task iteration
5200
* @it: the task iterator to finish
5201
*
5202
* Finish task iteration started by css_task_iter_start().
5203
*/
5204
void css_task_iter_end(struct css_task_iter *it)
5205
{
5206
unsigned long irqflags;
5207
5208
if (it->cur_cset) {
5209
spin_lock_irqsave(&css_set_lock, irqflags);
5210
list_del(&it->iters_node);
5211
put_css_set_locked(it->cur_cset);
5212
spin_unlock_irqrestore(&css_set_lock, irqflags);
5213
}
5214
5215
if (it->cur_dcset)
5216
put_css_set(it->cur_dcset);
5217
5218
if (it->cur_task)
5219
put_task_struct(it->cur_task);
5220
}
5221
5222
static void cgroup_procs_release(struct kernfs_open_file *of)
5223
{
5224
struct cgroup_file_ctx *ctx = of->priv;
5225
5226
if (ctx->procs.started)
5227
css_task_iter_end(&ctx->procs.iter);
5228
}
5229
5230
static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
5231
{
5232
struct kernfs_open_file *of = s->private;
5233
struct cgroup_file_ctx *ctx = of->priv;
5234
5235
if (pos)
5236
(*pos)++;
5237
5238
return css_task_iter_next(&ctx->procs.iter);
5239
}
5240
5241
static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
5242
unsigned int iter_flags)
5243
{
5244
struct kernfs_open_file *of = s->private;
5245
struct cgroup *cgrp = seq_css(s)->cgroup;
5246
struct cgroup_file_ctx *ctx = of->priv;
5247
struct css_task_iter *it = &ctx->procs.iter;
5248
5249
/*
5250
* When a seq_file is seeked, it's always traversed sequentially
5251
* from position 0, so we can simply keep iterating on !0 *pos.
5252
*/
5253
if (!ctx->procs.started) {
5254
if (WARN_ON_ONCE((*pos)))
5255
return ERR_PTR(-EINVAL);
5256
css_task_iter_start(&cgrp->self, iter_flags, it);
5257
ctx->procs.started = true;
5258
} else if (!(*pos)) {
5259
css_task_iter_end(it);
5260
css_task_iter_start(&cgrp->self, iter_flags, it);
5261
} else
5262
return it->cur_task;
5263
5264
return cgroup_procs_next(s, NULL, NULL);
5265
}
5266
5267
static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
5268
{
5269
struct cgroup *cgrp = seq_css(s)->cgroup;
5270
5271
/*
5272
* All processes of a threaded subtree belong to the domain cgroup
5273
* of the subtree. Only threads can be distributed across the
5274
* subtree. Reject reads on cgroup.procs in the subtree proper.
5275
* They're always empty anyway.
5276
*/
5277
if (cgroup_is_threaded(cgrp))
5278
return ERR_PTR(-EOPNOTSUPP);
5279
5280
return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
5281
CSS_TASK_ITER_THREADED);
5282
}
5283
5284
static int cgroup_procs_show(struct seq_file *s, void *v)
5285
{
5286
seq_printf(s, "%d\n", task_pid_vnr(v));
5287
return 0;
5288
}
5289
5290
static int cgroup_may_write(const struct cgroup *cgrp, struct super_block *sb)
5291
{
5292
int ret;
5293
struct inode *inode;
5294
5295
lockdep_assert_held(&cgroup_mutex);
5296
5297
inode = kernfs_get_inode(sb, cgrp->procs_file.kn);
5298
if (!inode)
5299
return -ENOMEM;
5300
5301
ret = inode_permission(&nop_mnt_idmap, inode, MAY_WRITE);
5302
iput(inode);
5303
return ret;
5304
}
5305
5306
static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
5307
struct cgroup *dst_cgrp,
5308
struct super_block *sb,
5309
struct cgroup_namespace *ns)
5310
{
5311
struct cgroup *com_cgrp = src_cgrp;
5312
int ret;
5313
5314
lockdep_assert_held(&cgroup_mutex);
5315
5316
/* find the common ancestor */
5317
while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
5318
com_cgrp = cgroup_parent(com_cgrp);
5319
5320
/* %current should be authorized to migrate to the common ancestor */
5321
ret = cgroup_may_write(com_cgrp, sb);
5322
if (ret)
5323
return ret;
5324
5325
/*
5326
* If namespaces are delegation boundaries, %current must be able
5327
* to see both source and destination cgroups from its namespace.
5328
*/
5329
if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
5330
(!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
5331
!cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
5332
return -ENOENT;
5333
5334
return 0;
5335
}
5336
5337
static int cgroup_attach_permissions(struct cgroup *src_cgrp,
5338
struct cgroup *dst_cgrp,
5339
struct super_block *sb, bool threadgroup,
5340
struct cgroup_namespace *ns)
5341
{
5342
int ret = 0;
5343
5344
ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp, sb, ns);
5345
if (ret)
5346
return ret;
5347
5348
ret = cgroup_migrate_vet_dst(dst_cgrp);
5349
if (ret)
5350
return ret;
5351
5352
if (!threadgroup && (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp))
5353
ret = -EOPNOTSUPP;
5354
5355
return ret;
5356
}
5357
5358
static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
5359
bool threadgroup)
5360
{
5361
struct cgroup_file_ctx *ctx = of->priv;
5362
struct cgroup *src_cgrp, *dst_cgrp;
5363
struct task_struct *task;
5364
ssize_t ret;
5365
enum cgroup_attach_lock_mode lock_mode;
5366
5367
dst_cgrp = cgroup_kn_lock_live(of->kn, false);
5368
if (!dst_cgrp)
5369
return -ENODEV;
5370
5371
task = cgroup_procs_write_start(buf, threadgroup, &lock_mode);
5372
ret = PTR_ERR_OR_ZERO(task);
5373
if (ret)
5374
goto out_unlock;
5375
5376
/* find the source cgroup */
5377
spin_lock_irq(&css_set_lock);
5378
src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
5379
spin_unlock_irq(&css_set_lock);
5380
5381
/*
5382
* Process and thread migrations follow same delegation rule. Check
5383
* permissions using the credentials from file open to protect against
5384
* inherited fd attacks.
5385
*/
5386
scoped_with_creds(of->file->f_cred)
5387
ret = cgroup_attach_permissions(src_cgrp, dst_cgrp,
5388
of->file->f_path.dentry->d_sb,
5389
threadgroup, ctx->ns);
5390
if (ret)
5391
goto out_finish;
5392
5393
ret = cgroup_attach_task(dst_cgrp, task, threadgroup);
5394
5395
out_finish:
5396
cgroup_procs_write_finish(task, lock_mode);
5397
out_unlock:
5398
cgroup_kn_unlock(of->kn);
5399
5400
return ret;
5401
}
5402
5403
static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
5404
char *buf, size_t nbytes, loff_t off)
5405
{
5406
return __cgroup_procs_write(of, buf, true) ?: nbytes;
5407
}
5408
5409
static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
5410
{
5411
return __cgroup_procs_start(s, pos, 0);
5412
}
5413
5414
static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
5415
char *buf, size_t nbytes, loff_t off)
5416
{
5417
return __cgroup_procs_write(of, buf, false) ?: nbytes;
5418
}
5419
5420
/* cgroup core interface files for the default hierarchy */
5421
static struct cftype cgroup_base_files[] = {
5422
{
5423
.name = "cgroup.type",
5424
.flags = CFTYPE_NOT_ON_ROOT,
5425
.seq_show = cgroup_type_show,
5426
.write = cgroup_type_write,
5427
},
5428
{
5429
.name = "cgroup.procs",
5430
.flags = CFTYPE_NS_DELEGATABLE,
5431
.file_offset = offsetof(struct cgroup, procs_file),
5432
.release = cgroup_procs_release,
5433
.seq_start = cgroup_procs_start,
5434
.seq_next = cgroup_procs_next,
5435
.seq_show = cgroup_procs_show,
5436
.write = cgroup_procs_write,
5437
},
5438
{
5439
.name = "cgroup.threads",
5440
.flags = CFTYPE_NS_DELEGATABLE,
5441
.release = cgroup_procs_release,
5442
.seq_start = cgroup_threads_start,
5443
.seq_next = cgroup_procs_next,
5444
.seq_show = cgroup_procs_show,
5445
.write = cgroup_threads_write,
5446
},
5447
{
5448
.name = "cgroup.controllers",
5449
.seq_show = cgroup_controllers_show,
5450
},
5451
{
5452
.name = "cgroup.subtree_control",
5453
.flags = CFTYPE_NS_DELEGATABLE,
5454
.seq_show = cgroup_subtree_control_show,
5455
.write = cgroup_subtree_control_write,
5456
},
5457
{
5458
.name = "cgroup.events",
5459
.flags = CFTYPE_NOT_ON_ROOT,
5460
.file_offset = offsetof(struct cgroup, events_file),
5461
.seq_show = cgroup_events_show,
5462
},
5463
{
5464
.name = "cgroup.max.descendants",
5465
.seq_show = cgroup_max_descendants_show,
5466
.write = cgroup_max_descendants_write,
5467
},
5468
{
5469
.name = "cgroup.max.depth",
5470
.seq_show = cgroup_max_depth_show,
5471
.write = cgroup_max_depth_write,
5472
},
5473
{
5474
.name = "cgroup.stat",
5475
.seq_show = cgroup_stat_show,
5476
},
5477
{
5478
.name = "cgroup.stat.local",
5479
.flags = CFTYPE_NOT_ON_ROOT,
5480
.seq_show = cgroup_core_local_stat_show,
5481
},
5482
{
5483
.name = "cgroup.freeze",
5484
.flags = CFTYPE_NOT_ON_ROOT,
5485
.seq_show = cgroup_freeze_show,
5486
.write = cgroup_freeze_write,
5487
},
5488
{
5489
.name = "cgroup.kill",
5490
.flags = CFTYPE_NOT_ON_ROOT,
5491
.write = cgroup_kill_write,
5492
},
5493
{
5494
.name = "cpu.stat",
5495
.seq_show = cpu_stat_show,
5496
},
5497
{
5498
.name = "cpu.stat.local",
5499
.seq_show = cpu_local_stat_show,
5500
},
5501
{ } /* terminate */
5502
};
5503
5504
static struct cftype cgroup_psi_files[] = {
5505
#ifdef CONFIG_PSI
5506
{
5507
.name = "io.pressure",
5508
.file_offset = offsetof(struct cgroup, psi_files[PSI_IO]),
5509
.seq_show = cgroup_io_pressure_show,
5510
.write = cgroup_io_pressure_write,
5511
.poll = cgroup_pressure_poll,
5512
.release = cgroup_pressure_release,
5513
},
5514
{
5515
.name = "memory.pressure",
5516
.file_offset = offsetof(struct cgroup, psi_files[PSI_MEM]),
5517
.seq_show = cgroup_memory_pressure_show,
5518
.write = cgroup_memory_pressure_write,
5519
.poll = cgroup_pressure_poll,
5520
.release = cgroup_pressure_release,
5521
},
5522
{
5523
.name = "cpu.pressure",
5524
.file_offset = offsetof(struct cgroup, psi_files[PSI_CPU]),
5525
.seq_show = cgroup_cpu_pressure_show,
5526
.write = cgroup_cpu_pressure_write,
5527
.poll = cgroup_pressure_poll,
5528
.release = cgroup_pressure_release,
5529
},
5530
#ifdef CONFIG_IRQ_TIME_ACCOUNTING
5531
{
5532
.name = "irq.pressure",
5533
.file_offset = offsetof(struct cgroup, psi_files[PSI_IRQ]),
5534
.seq_show = cgroup_irq_pressure_show,
5535
.write = cgroup_irq_pressure_write,
5536
.poll = cgroup_pressure_poll,
5537
.release = cgroup_pressure_release,
5538
},
5539
#endif
5540
{
5541
.name = "cgroup.pressure",
5542
.seq_show = cgroup_pressure_show,
5543
.write = cgroup_pressure_write,
5544
},
5545
#endif /* CONFIG_PSI */
5546
{ } /* terminate */
5547
};
5548
5549
/*
5550
* css destruction is four-stage process.
5551
*
5552
* 1. Destruction starts. Killing of the percpu_ref is initiated.
5553
* Implemented in kill_css().
5554
*
5555
* 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
5556
* and thus css_tryget_online() is guaranteed to fail, the css can be
5557
* offlined by invoking offline_css(). After offlining, the base ref is
5558
* put. Implemented in css_killed_work_fn().
5559
*
5560
* 3. When the percpu_ref reaches zero, the only possible remaining
5561
* accessors are inside RCU read sections. css_release() schedules the
5562
* RCU callback.
5563
*
5564
* 4. After the grace period, the css can be freed. Implemented in
5565
* css_free_rwork_fn().
5566
*
5567
* It is actually hairier because both step 2 and 4 require process context
5568
* and thus involve punting to css->destroy_work adding two additional
5569
* steps to the already complex sequence.
5570
*/
5571
static void css_free_rwork_fn(struct work_struct *work)
5572
{
5573
struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
5574
struct cgroup_subsys_state, destroy_rwork);
5575
struct cgroup_subsys *ss = css->ss;
5576
struct cgroup *cgrp = css->cgroup;
5577
5578
percpu_ref_exit(&css->refcnt);
5579
css_rstat_exit(css);
5580
5581
if (!css_is_self(css)) {
5582
/* css free path */
5583
struct cgroup_subsys_state *parent = css->parent;
5584
int id = css->id;
5585
5586
ss->css_free(css);
5587
cgroup_idr_remove(&ss->css_idr, id);
5588
cgroup_put(cgrp);
5589
5590
if (parent)
5591
css_put(parent);
5592
} else {
5593
/* cgroup free path */
5594
atomic_dec(&cgrp->root->nr_cgrps);
5595
if (!cgroup_on_dfl(cgrp))
5596
cgroup1_pidlist_destroy_all(cgrp);
5597
cancel_work_sync(&cgrp->release_agent_work);
5598
bpf_cgrp_storage_free(cgrp);
5599
5600
if (cgroup_parent(cgrp)) {
5601
/*
5602
* We get a ref to the parent, and put the ref when
5603
* this cgroup is being freed, so it's guaranteed
5604
* that the parent won't be destroyed before its
5605
* children.
5606
*/
5607
cgroup_put(cgroup_parent(cgrp));
5608
kernfs_put(cgrp->kn);
5609
psi_cgroup_free(cgrp);
5610
kfree(cgrp);
5611
} else {
5612
/*
5613
* This is root cgroup's refcnt reaching zero,
5614
* which indicates that the root should be
5615
* released.
5616
*/
5617
cgroup_destroy_root(cgrp->root);
5618
}
5619
}
5620
}
5621
5622
static void css_release_work_fn(struct work_struct *work)
5623
{
5624
struct cgroup_subsys_state *css =
5625
container_of(work, struct cgroup_subsys_state, destroy_work);
5626
struct cgroup_subsys *ss = css->ss;
5627
struct cgroup *cgrp = css->cgroup;
5628
5629
cgroup_lock();
5630
5631
css->flags |= CSS_RELEASED;
5632
list_del_rcu(&css->sibling);
5633
5634
if (!css_is_self(css)) {
5635
struct cgroup *parent_cgrp;
5636
5637
css_rstat_flush(css);
5638
5639
cgroup_idr_replace(&ss->css_idr, NULL, css->id);
5640
if (ss->css_released)
5641
ss->css_released(css);
5642
5643
cgrp->nr_dying_subsys[ss->id]--;
5644
/*
5645
* When a css is released and ready to be freed, its
5646
* nr_descendants must be zero. However, the corresponding
5647
* cgrp->nr_dying_subsys[ss->id] may not be 0 if a subsystem
5648
* is activated and deactivated multiple times with one or
5649
* more of its previous activation leaving behind dying csses.
5650
*/
5651
WARN_ON_ONCE(css->nr_descendants);
5652
parent_cgrp = cgroup_parent(cgrp);
5653
while (parent_cgrp) {
5654
parent_cgrp->nr_dying_subsys[ss->id]--;
5655
parent_cgrp = cgroup_parent(parent_cgrp);
5656
}
5657
} else {
5658
struct cgroup *tcgrp;
5659
5660
/* cgroup release path */
5661
TRACE_CGROUP_PATH(release, cgrp);
5662
5663
css_rstat_flush(&cgrp->self);
5664
5665
spin_lock_irq(&css_set_lock);
5666
for (tcgrp = cgroup_parent(cgrp); tcgrp;
5667
tcgrp = cgroup_parent(tcgrp))
5668
tcgrp->nr_dying_descendants--;
5669
spin_unlock_irq(&css_set_lock);
5670
5671
/*
5672
* There are two control paths which try to determine
5673
* cgroup from dentry without going through kernfs -
5674
* cgroupstats_build() and css_tryget_online_from_dir().
5675
* Those are supported by RCU protecting clearing of
5676
* cgrp->kn->priv backpointer.
5677
*/
5678
if (cgrp->kn)
5679
RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
5680
NULL);
5681
}
5682
5683
cgroup_unlock();
5684
5685
INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5686
queue_rcu_work(cgroup_free_wq, &css->destroy_rwork);
5687
}
5688
5689
static void css_release(struct percpu_ref *ref)
5690
{
5691
struct cgroup_subsys_state *css =
5692
container_of(ref, struct cgroup_subsys_state, refcnt);
5693
5694
INIT_WORK(&css->destroy_work, css_release_work_fn);
5695
queue_work(cgroup_release_wq, &css->destroy_work);
5696
}
5697
5698
static void init_and_link_css(struct cgroup_subsys_state *css,
5699
struct cgroup_subsys *ss, struct cgroup *cgrp)
5700
{
5701
lockdep_assert_held(&cgroup_mutex);
5702
5703
cgroup_get_live(cgrp);
5704
5705
memset(css, 0, sizeof(*css));
5706
css->cgroup = cgrp;
5707
css->ss = ss;
5708
css->id = -1;
5709
INIT_LIST_HEAD(&css->sibling);
5710
INIT_LIST_HEAD(&css->children);
5711
css->serial_nr = css_serial_nr_next++;
5712
atomic_set(&css->online_cnt, 0);
5713
5714
if (cgroup_parent(cgrp)) {
5715
css->parent = cgroup_css(cgroup_parent(cgrp), ss);
5716
css_get(css->parent);
5717
}
5718
5719
BUG_ON(cgroup_css(cgrp, ss));
5720
}
5721
5722
/* invoke ->css_online() on a new CSS and mark it online if successful */
5723
static int online_css(struct cgroup_subsys_state *css)
5724
{
5725
struct cgroup_subsys *ss = css->ss;
5726
int ret = 0;
5727
5728
lockdep_assert_held(&cgroup_mutex);
5729
5730
if (ss->css_online)
5731
ret = ss->css_online(css);
5732
if (!ret) {
5733
css->flags |= CSS_ONLINE;
5734
rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
5735
5736
atomic_inc(&css->online_cnt);
5737
if (css->parent) {
5738
atomic_inc(&css->parent->online_cnt);
5739
while ((css = css->parent))
5740
css->nr_descendants++;
5741
}
5742
}
5743
return ret;
5744
}
5745
5746
/* if the CSS is online, invoke ->css_offline() on it and mark it offline */
5747
static void offline_css(struct cgroup_subsys_state *css)
5748
{
5749
struct cgroup_subsys *ss = css->ss;
5750
5751
lockdep_assert_held(&cgroup_mutex);
5752
5753
if (!(css->flags & CSS_ONLINE))
5754
return;
5755
5756
if (ss->css_offline)
5757
ss->css_offline(css);
5758
5759
css->flags &= ~CSS_ONLINE;
5760
RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
5761
5762
wake_up_all(&css->cgroup->offline_waitq);
5763
5764
css->cgroup->nr_dying_subsys[ss->id]++;
5765
/*
5766
* Parent css and cgroup cannot be freed until after the freeing
5767
* of child css, see css_free_rwork_fn().
5768
*/
5769
while ((css = css->parent)) {
5770
css->nr_descendants--;
5771
css->cgroup->nr_dying_subsys[ss->id]++;
5772
}
5773
}
5774
5775
/**
5776
* css_create - create a cgroup_subsys_state
5777
* @cgrp: the cgroup new css will be associated with
5778
* @ss: the subsys of new css
5779
*
5780
* Create a new css associated with @cgrp - @ss pair. On success, the new
5781
* css is online and installed in @cgrp. This function doesn't create the
5782
* interface files. Returns 0 on success, -errno on failure.
5783
*/
5784
static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
5785
struct cgroup_subsys *ss)
5786
{
5787
struct cgroup *parent = cgroup_parent(cgrp);
5788
struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
5789
struct cgroup_subsys_state *css;
5790
int err;
5791
5792
lockdep_assert_held(&cgroup_mutex);
5793
5794
css = ss->css_alloc(parent_css);
5795
if (!css)
5796
css = ERR_PTR(-ENOMEM);
5797
if (IS_ERR(css))
5798
return css;
5799
5800
init_and_link_css(css, ss, cgrp);
5801
5802
err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
5803
if (err)
5804
goto err_free_css;
5805
5806
err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
5807
if (err < 0)
5808
goto err_free_css;
5809
css->id = err;
5810
5811
err = css_rstat_init(css);
5812
if (err)
5813
goto err_free_css;
5814
5815
/* @css is ready to be brought online now, make it visible */
5816
list_add_tail_rcu(&css->sibling, &parent_css->children);
5817
cgroup_idr_replace(&ss->css_idr, css, css->id);
5818
5819
err = online_css(css);
5820
if (err)
5821
goto err_list_del;
5822
5823
return css;
5824
5825
err_list_del:
5826
list_del_rcu(&css->sibling);
5827
err_free_css:
5828
INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5829
queue_rcu_work(cgroup_free_wq, &css->destroy_rwork);
5830
return ERR_PTR(err);
5831
}
5832
5833
/*
5834
* The returned cgroup is fully initialized including its control mask, but
5835
* it doesn't have the control mask applied.
5836
*/
5837
static struct cgroup *cgroup_create(struct cgroup *parent, const char *name,
5838
umode_t mode)
5839
{
5840
struct cgroup_root *root = parent->root;
5841
struct cgroup *cgrp, *tcgrp;
5842
struct kernfs_node *kn;
5843
int i, level = parent->level + 1;
5844
int ret;
5845
5846
/* allocate the cgroup and its ID, 0 is reserved for the root */
5847
cgrp = kzalloc(struct_size(cgrp, _low_ancestors, level), GFP_KERNEL);
5848
if (!cgrp)
5849
return ERR_PTR(-ENOMEM);
5850
5851
ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
5852
if (ret)
5853
goto out_free_cgrp;
5854
5855
/* create the directory */
5856
kn = kernfs_create_dir_ns(parent->kn, name, mode,
5857
current_fsuid(), current_fsgid(),
5858
cgrp, NULL);
5859
if (IS_ERR(kn)) {
5860
ret = PTR_ERR(kn);
5861
goto out_cancel_ref;
5862
}
5863
cgrp->kn = kn;
5864
5865
init_cgroup_housekeeping(cgrp);
5866
5867
cgrp->self.parent = &parent->self;
5868
cgrp->root = root;
5869
cgrp->level = level;
5870
5871
/*
5872
* Now that init_cgroup_housekeeping() has been called and cgrp->self
5873
* is setup, it is safe to perform rstat initialization on it.
5874
*/
5875
ret = css_rstat_init(&cgrp->self);
5876
if (ret)
5877
goto out_kernfs_remove;
5878
5879
ret = psi_cgroup_alloc(cgrp);
5880
if (ret)
5881
goto out_stat_exit;
5882
5883
for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp))
5884
cgrp->ancestors[tcgrp->level] = tcgrp;
5885
5886
/*
5887
* New cgroup inherits effective freeze counter, and
5888
* if the parent has to be frozen, the child has too.
5889
*/
5890
cgrp->freezer.e_freeze = parent->freezer.e_freeze;
5891
seqcount_spinlock_init(&cgrp->freezer.freeze_seq, &css_set_lock);
5892
if (cgrp->freezer.e_freeze) {
5893
/*
5894
* Set the CGRP_FREEZE flag, so when a process will be
5895
* attached to the child cgroup, it will become frozen.
5896
* At this point the new cgroup is unpopulated, so we can
5897
* consider it frozen immediately.
5898
*/
5899
set_bit(CGRP_FREEZE, &cgrp->flags);
5900
cgrp->freezer.freeze_start_nsec = ktime_get_ns();
5901
set_bit(CGRP_FROZEN, &cgrp->flags);
5902
}
5903
5904
if (notify_on_release(parent))
5905
set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
5906
5907
if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
5908
set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
5909
5910
cgrp->self.serial_nr = css_serial_nr_next++;
5911
5912
ret = blocking_notifier_call_chain_robust(&cgroup_lifetime_notifier,
5913
CGROUP_LIFETIME_ONLINE,
5914
CGROUP_LIFETIME_OFFLINE, cgrp);
5915
ret = notifier_to_errno(ret);
5916
if (ret)
5917
goto out_psi_free;
5918
5919
/* allocation complete, commit to creation */
5920
spin_lock_irq(&css_set_lock);
5921
for (i = 0; i < level; i++) {
5922
tcgrp = cgrp->ancestors[i];
5923
tcgrp->nr_descendants++;
5924
5925
/*
5926
* If the new cgroup is frozen, all ancestor cgroups get a new
5927
* frozen descendant, but their state can't change because of
5928
* this.
5929
*/
5930
if (cgrp->freezer.e_freeze)
5931
tcgrp->freezer.nr_frozen_descendants++;
5932
}
5933
spin_unlock_irq(&css_set_lock);
5934
5935
list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
5936
atomic_inc(&root->nr_cgrps);
5937
cgroup_get_live(parent);
5938
5939
/*
5940
* On the default hierarchy, a child doesn't automatically inherit
5941
* subtree_control from the parent. Each is configured manually.
5942
*/
5943
if (!cgroup_on_dfl(cgrp))
5944
cgrp->subtree_control = cgroup_control(cgrp);
5945
5946
cgroup_propagate_control(cgrp);
5947
5948
return cgrp;
5949
5950
out_psi_free:
5951
psi_cgroup_free(cgrp);
5952
out_stat_exit:
5953
css_rstat_exit(&cgrp->self);
5954
out_kernfs_remove:
5955
kernfs_remove(cgrp->kn);
5956
out_cancel_ref:
5957
percpu_ref_exit(&cgrp->self.refcnt);
5958
out_free_cgrp:
5959
kfree(cgrp);
5960
return ERR_PTR(ret);
5961
}
5962
5963
static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
5964
{
5965
struct cgroup *cgroup;
5966
int ret = false;
5967
int level = 0;
5968
5969
lockdep_assert_held(&cgroup_mutex);
5970
5971
for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
5972
if (cgroup->nr_descendants >= cgroup->max_descendants)
5973
goto fail;
5974
5975
if (level >= cgroup->max_depth)
5976
goto fail;
5977
5978
level++;
5979
}
5980
5981
ret = true;
5982
fail:
5983
return ret;
5984
}
5985
5986
int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
5987
{
5988
struct cgroup *parent, *cgrp;
5989
int ret;
5990
5991
/* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
5992
if (strchr(name, '\n'))
5993
return -EINVAL;
5994
5995
parent = cgroup_kn_lock_live(parent_kn, false);
5996
if (!parent)
5997
return -ENODEV;
5998
5999
if (!cgroup_check_hierarchy_limits(parent)) {
6000
ret = -EAGAIN;
6001
goto out_unlock;
6002
}
6003
6004
cgrp = cgroup_create(parent, name, mode);
6005
if (IS_ERR(cgrp)) {
6006
ret = PTR_ERR(cgrp);
6007
goto out_unlock;
6008
}
6009
6010
/*
6011
* This extra ref will be put in css_free_rwork_fn() and guarantees
6012
* that @cgrp->kn is always accessible.
6013
*/
6014
kernfs_get(cgrp->kn);
6015
6016
ret = css_populate_dir(&cgrp->self);
6017
if (ret)
6018
goto out_destroy;
6019
6020
ret = cgroup_apply_control_enable(cgrp);
6021
if (ret)
6022
goto out_destroy;
6023
6024
TRACE_CGROUP_PATH(mkdir, cgrp);
6025
6026
/* let's create and online css's */
6027
kernfs_activate(cgrp->kn);
6028
6029
ret = 0;
6030
goto out_unlock;
6031
6032
out_destroy:
6033
cgroup_destroy_locked(cgrp);
6034
out_unlock:
6035
cgroup_kn_unlock(parent_kn);
6036
return ret;
6037
}
6038
6039
/*
6040
* This is called when the refcnt of a css is confirmed to be killed.
6041
* css_tryget_online() is now guaranteed to fail. Tell the subsystem to
6042
* initiate destruction and put the css ref from kill_css().
6043
*/
6044
static void css_killed_work_fn(struct work_struct *work)
6045
{
6046
struct cgroup_subsys_state *css =
6047
container_of(work, struct cgroup_subsys_state, destroy_work);
6048
6049
cgroup_lock();
6050
6051
do {
6052
offline_css(css);
6053
css_put(css);
6054
/* @css can't go away while we're holding cgroup_mutex */
6055
css = css->parent;
6056
} while (css && atomic_dec_and_test(&css->online_cnt));
6057
6058
cgroup_unlock();
6059
}
6060
6061
/* css kill confirmation processing requires process context, bounce */
6062
static void css_killed_ref_fn(struct percpu_ref *ref)
6063
{
6064
struct cgroup_subsys_state *css =
6065
container_of(ref, struct cgroup_subsys_state, refcnt);
6066
6067
if (atomic_dec_and_test(&css->online_cnt)) {
6068
INIT_WORK(&css->destroy_work, css_killed_work_fn);
6069
queue_work(cgroup_offline_wq, &css->destroy_work);
6070
}
6071
}
6072
6073
/**
6074
* kill_css - destroy a css
6075
* @css: css to destroy
6076
*
6077
* This function initiates destruction of @css by removing cgroup interface
6078
* files and putting its base reference. ->css_offline() will be invoked
6079
* asynchronously once css_tryget_online() is guaranteed to fail and when
6080
* the reference count reaches zero, @css will be released.
6081
*/
6082
static void kill_css(struct cgroup_subsys_state *css)
6083
{
6084
lockdep_assert_held(&cgroup_mutex);
6085
6086
if (css->flags & CSS_DYING)
6087
return;
6088
6089
/*
6090
* Call css_killed(), if defined, before setting the CSS_DYING flag
6091
*/
6092
if (css->ss->css_killed)
6093
css->ss->css_killed(css);
6094
6095
css->flags |= CSS_DYING;
6096
6097
/*
6098
* This must happen before css is disassociated with its cgroup.
6099
* See seq_css() for details.
6100
*/
6101
css_clear_dir(css);
6102
6103
/*
6104
* Killing would put the base ref, but we need to keep it alive
6105
* until after ->css_offline().
6106
*/
6107
css_get(css);
6108
6109
/*
6110
* cgroup core guarantees that, by the time ->css_offline() is
6111
* invoked, no new css reference will be given out via
6112
* css_tryget_online(). We can't simply call percpu_ref_kill() and
6113
* proceed to offlining css's because percpu_ref_kill() doesn't
6114
* guarantee that the ref is seen as killed on all CPUs on return.
6115
*
6116
* Use percpu_ref_kill_and_confirm() to get notifications as each
6117
* css is confirmed to be seen as killed on all CPUs.
6118
*/
6119
percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
6120
}
6121
6122
/**
6123
* cgroup_destroy_locked - the first stage of cgroup destruction
6124
* @cgrp: cgroup to be destroyed
6125
*
6126
* css's make use of percpu refcnts whose killing latency shouldn't be
6127
* exposed to userland and are RCU protected. Also, cgroup core needs to
6128
* guarantee that css_tryget_online() won't succeed by the time
6129
* ->css_offline() is invoked. To satisfy all the requirements,
6130
* destruction is implemented in the following two steps.
6131
*
6132
* s1. Verify @cgrp can be destroyed and mark it dying. Remove all
6133
* userland visible parts and start killing the percpu refcnts of
6134
* css's. Set up so that the next stage will be kicked off once all
6135
* the percpu refcnts are confirmed to be killed.
6136
*
6137
* s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
6138
* rest of destruction. Once all cgroup references are gone, the
6139
* cgroup is RCU-freed.
6140
*
6141
* This function implements s1. After this step, @cgrp is gone as far as
6142
* the userland is concerned and a new cgroup with the same name may be
6143
* created. As cgroup doesn't care about the names internally, this
6144
* doesn't cause any problem.
6145
*/
6146
static int cgroup_destroy_locked(struct cgroup *cgrp)
6147
__releases(&cgroup_mutex) __acquires(&cgroup_mutex)
6148
{
6149
struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
6150
struct cgroup_subsys_state *css;
6151
struct cgrp_cset_link *link;
6152
int ssid, ret;
6153
6154
lockdep_assert_held(&cgroup_mutex);
6155
6156
/*
6157
* Only migration can raise populated from zero and we're already
6158
* holding cgroup_mutex.
6159
*/
6160
if (cgroup_is_populated(cgrp))
6161
return -EBUSY;
6162
6163
/*
6164
* Make sure there's no live children. We can't test emptiness of
6165
* ->self.children as dead children linger on it while being
6166
* drained; otherwise, "rmdir parent/child parent" may fail.
6167
*/
6168
if (css_has_online_children(&cgrp->self))
6169
return -EBUSY;
6170
6171
/*
6172
* Mark @cgrp and the associated csets dead. The former prevents
6173
* further task migration and child creation by disabling
6174
* cgroup_kn_lock_live(). The latter makes the csets ignored by
6175
* the migration path.
6176
*/
6177
cgrp->self.flags &= ~CSS_ONLINE;
6178
6179
spin_lock_irq(&css_set_lock);
6180
list_for_each_entry(link, &cgrp->cset_links, cset_link)
6181
link->cset->dead = true;
6182
spin_unlock_irq(&css_set_lock);
6183
6184
/* initiate massacre of all css's */
6185
for_each_css(css, ssid, cgrp)
6186
kill_css(css);
6187
6188
/* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
6189
css_clear_dir(&cgrp->self);
6190
kernfs_remove(cgrp->kn);
6191
6192
if (cgroup_is_threaded(cgrp))
6193
parent->nr_threaded_children--;
6194
6195
spin_lock_irq(&css_set_lock);
6196
for (tcgrp = parent; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
6197
tcgrp->nr_descendants--;
6198
tcgrp->nr_dying_descendants++;
6199
/*
6200
* If the dying cgroup is frozen, decrease frozen descendants
6201
* counters of ancestor cgroups.
6202
*/
6203
if (test_bit(CGRP_FROZEN, &cgrp->flags))
6204
tcgrp->freezer.nr_frozen_descendants--;
6205
}
6206
spin_unlock_irq(&css_set_lock);
6207
6208
cgroup1_check_for_release(parent);
6209
6210
ret = blocking_notifier_call_chain(&cgroup_lifetime_notifier,
6211
CGROUP_LIFETIME_OFFLINE, cgrp);
6212
WARN_ON_ONCE(notifier_to_errno(ret));
6213
6214
/* put the base reference */
6215
percpu_ref_kill(&cgrp->self.refcnt);
6216
6217
return 0;
6218
};
6219
6220
int cgroup_rmdir(struct kernfs_node *kn)
6221
{
6222
struct cgroup *cgrp;
6223
int ret = 0;
6224
6225
cgrp = cgroup_kn_lock_live(kn, false);
6226
if (!cgrp)
6227
return 0;
6228
6229
ret = cgroup_destroy_locked(cgrp);
6230
if (!ret)
6231
TRACE_CGROUP_PATH(rmdir, cgrp);
6232
6233
cgroup_kn_unlock(kn);
6234
return ret;
6235
}
6236
6237
static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
6238
.show_options = cgroup_show_options,
6239
.mkdir = cgroup_mkdir,
6240
.rmdir = cgroup_rmdir,
6241
.show_path = cgroup_show_path,
6242
};
6243
6244
static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
6245
{
6246
struct cgroup_subsys_state *css;
6247
6248
pr_debug("Initializing cgroup subsys %s\n", ss->name);
6249
6250
cgroup_lock();
6251
6252
idr_init(&ss->css_idr);
6253
INIT_LIST_HEAD(&ss->cfts);
6254
6255
/* Create the root cgroup state for this subsystem */
6256
ss->root = &cgrp_dfl_root;
6257
css = ss->css_alloc(NULL);
6258
/* We don't handle early failures gracefully */
6259
BUG_ON(IS_ERR(css));
6260
init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
6261
6262
/*
6263
* Root csses are never destroyed and we can't initialize
6264
* percpu_ref during early init. Disable refcnting.
6265
*/
6266
css->flags |= CSS_NO_REF;
6267
6268
if (early) {
6269
/* allocation can't be done safely during early init */
6270
css->id = 1;
6271
} else {
6272
css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
6273
BUG_ON(css->id < 0);
6274
6275
BUG_ON(ss_rstat_init(ss));
6276
BUG_ON(css_rstat_init(css));
6277
}
6278
6279
/* Update the init_css_set to contain a subsys
6280
* pointer to this state - since the subsystem is
6281
* newly registered, all tasks and hence the
6282
* init_css_set is in the subsystem's root cgroup. */
6283
init_css_set.subsys[ss->id] = css;
6284
6285
have_fork_callback |= (bool)ss->fork << ss->id;
6286
have_exit_callback |= (bool)ss->exit << ss->id;
6287
have_release_callback |= (bool)ss->release << ss->id;
6288
have_canfork_callback |= (bool)ss->can_fork << ss->id;
6289
6290
/* At system boot, before all subsystems have been
6291
* registered, no tasks have been forked, so we don't
6292
* need to invoke fork callbacks here. */
6293
BUG_ON(!list_empty(&init_task.tasks));
6294
6295
BUG_ON(online_css(css));
6296
6297
cgroup_unlock();
6298
}
6299
6300
/**
6301
* cgroup_init_early - cgroup initialization at system boot
6302
*
6303
* Initialize cgroups at system boot, and initialize any
6304
* subsystems that request early init.
6305
*/
6306
int __init cgroup_init_early(void)
6307
{
6308
static struct cgroup_fs_context __initdata ctx;
6309
struct cgroup_subsys *ss;
6310
int i;
6311
6312
ctx.root = &cgrp_dfl_root;
6313
init_cgroup_root(&ctx);
6314
cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
6315
6316
RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
6317
6318
for_each_subsys(ss, i) {
6319
WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
6320
"invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
6321
i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
6322
ss->id, ss->name);
6323
WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
6324
"cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
6325
WARN(ss->early_init && ss->css_rstat_flush,
6326
"cgroup rstat cannot be used with early init subsystem\n");
6327
6328
ss->id = i;
6329
ss->name = cgroup_subsys_name[i];
6330
if (!ss->legacy_name)
6331
ss->legacy_name = cgroup_subsys_name[i];
6332
6333
if (ss->early_init)
6334
cgroup_init_subsys(ss, true);
6335
}
6336
return 0;
6337
}
6338
6339
/**
6340
* cgroup_init - cgroup initialization
6341
*
6342
* Register cgroup filesystem and /proc file, and initialize
6343
* any subsystems that didn't request early init.
6344
*/
6345
int __init cgroup_init(void)
6346
{
6347
struct cgroup_subsys *ss;
6348
int ssid;
6349
6350
BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
6351
BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
6352
BUG_ON(cgroup_init_cftypes(NULL, cgroup_psi_files));
6353
BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
6354
6355
BUG_ON(ss_rstat_init(NULL));
6356
6357
get_user_ns(init_cgroup_ns.user_ns);
6358
cgroup_rt_init();
6359
6360
cgroup_lock();
6361
6362
/*
6363
* Add init_css_set to the hash table so that dfl_root can link to
6364
* it during init.
6365
*/
6366
hash_add(css_set_table, &init_css_set.hlist,
6367
css_set_hash(init_css_set.subsys));
6368
6369
cgroup_bpf_lifetime_notifier_init();
6370
6371
BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
6372
6373
cgroup_unlock();
6374
6375
for_each_subsys(ss, ssid) {
6376
if (ss->early_init) {
6377
struct cgroup_subsys_state *css =
6378
init_css_set.subsys[ss->id];
6379
6380
css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
6381
GFP_KERNEL);
6382
BUG_ON(css->id < 0);
6383
} else {
6384
cgroup_init_subsys(ss, false);
6385
}
6386
6387
list_add_tail(&init_css_set.e_cset_node[ssid],
6388
&cgrp_dfl_root.cgrp.e_csets[ssid]);
6389
6390
/*
6391
* Setting dfl_root subsys_mask needs to consider the
6392
* disabled flag and cftype registration needs kmalloc,
6393
* both of which aren't available during early_init.
6394
*/
6395
if (!cgroup_ssid_enabled(ssid))
6396
continue;
6397
6398
if (cgroup1_ssid_disabled(ssid))
6399
pr_info("Disabling %s control group subsystem in v1 mounts\n",
6400
ss->legacy_name);
6401
6402
cgrp_dfl_root.subsys_mask |= 1 << ss->id;
6403
6404
/* implicit controllers must be threaded too */
6405
WARN_ON(ss->implicit_on_dfl && !ss->threaded);
6406
6407
if (ss->implicit_on_dfl)
6408
cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
6409
else if (!ss->dfl_cftypes)
6410
cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
6411
6412
if (ss->threaded)
6413
cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
6414
6415
if (ss->dfl_cftypes == ss->legacy_cftypes) {
6416
WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
6417
} else {
6418
WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
6419
WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
6420
}
6421
6422
if (ss->bind)
6423
ss->bind(init_css_set.subsys[ssid]);
6424
6425
cgroup_lock();
6426
css_populate_dir(init_css_set.subsys[ssid]);
6427
cgroup_unlock();
6428
}
6429
6430
/* init_css_set.subsys[] has been updated, re-hash */
6431
hash_del(&init_css_set.hlist);
6432
hash_add(css_set_table, &init_css_set.hlist,
6433
css_set_hash(init_css_set.subsys));
6434
6435
WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
6436
WARN_ON(register_filesystem(&cgroup_fs_type));
6437
WARN_ON(register_filesystem(&cgroup2_fs_type));
6438
WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show));
6439
#ifdef CONFIG_CPUSETS_V1
6440
WARN_ON(register_filesystem(&cpuset_fs_type));
6441
#endif
6442
6443
ns_tree_add(&init_cgroup_ns);
6444
return 0;
6445
}
6446
6447
static int __init cgroup_wq_init(void)
6448
{
6449
/*
6450
* There isn't much point in executing destruction path in
6451
* parallel. Good chunk is serialized with cgroup_mutex anyway.
6452
* Use 1 for @max_active.
6453
*
6454
* We would prefer to do this in cgroup_init() above, but that
6455
* is called before init_workqueues(): so leave this until after.
6456
*/
6457
cgroup_offline_wq = alloc_workqueue("cgroup_offline", WQ_PERCPU, 1);
6458
BUG_ON(!cgroup_offline_wq);
6459
6460
cgroup_release_wq = alloc_workqueue("cgroup_release", WQ_PERCPU, 1);
6461
BUG_ON(!cgroup_release_wq);
6462
6463
cgroup_free_wq = alloc_workqueue("cgroup_free", WQ_PERCPU, 1);
6464
BUG_ON(!cgroup_free_wq);
6465
return 0;
6466
}
6467
core_initcall(cgroup_wq_init);
6468
6469
void cgroup_path_from_kernfs_id(u64 id, char *buf, size_t buflen)
6470
{
6471
struct kernfs_node *kn;
6472
6473
kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6474
if (!kn)
6475
return;
6476
kernfs_path(kn, buf, buflen);
6477
kernfs_put(kn);
6478
}
6479
6480
/*
6481
* __cgroup_get_from_id : get the cgroup associated with cgroup id
6482
* @id: cgroup id
6483
* On success return the cgrp or ERR_PTR on failure
6484
* There are no cgroup NS restrictions.
6485
*/
6486
struct cgroup *__cgroup_get_from_id(u64 id)
6487
{
6488
struct kernfs_node *kn;
6489
struct cgroup *cgrp;
6490
6491
kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6492
if (!kn)
6493
return ERR_PTR(-ENOENT);
6494
6495
if (kernfs_type(kn) != KERNFS_DIR) {
6496
kernfs_put(kn);
6497
return ERR_PTR(-ENOENT);
6498
}
6499
6500
rcu_read_lock();
6501
6502
cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6503
if (cgrp && !cgroup_tryget(cgrp))
6504
cgrp = NULL;
6505
6506
rcu_read_unlock();
6507
kernfs_put(kn);
6508
6509
if (!cgrp)
6510
return ERR_PTR(-ENOENT);
6511
return cgrp;
6512
}
6513
6514
/*
6515
* cgroup_get_from_id : get the cgroup associated with cgroup id
6516
* @id: cgroup id
6517
* On success return the cgrp or ERR_PTR on failure
6518
* Only cgroups within current task's cgroup NS are valid.
6519
*/
6520
struct cgroup *cgroup_get_from_id(u64 id)
6521
{
6522
struct cgroup *cgrp, *root_cgrp;
6523
6524
cgrp = __cgroup_get_from_id(id);
6525
if (IS_ERR(cgrp))
6526
return cgrp;
6527
6528
root_cgrp = current_cgns_cgroup_dfl();
6529
if (!cgroup_is_descendant(cgrp, root_cgrp)) {
6530
cgroup_put(cgrp);
6531
return ERR_PTR(-ENOENT);
6532
}
6533
6534
return cgrp;
6535
}
6536
EXPORT_SYMBOL_GPL(cgroup_get_from_id);
6537
6538
/*
6539
* proc_cgroup_show()
6540
* - Print task's cgroup paths into seq_file, one line for each hierarchy
6541
* - Used for /proc/<pid>/cgroup.
6542
*/
6543
int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
6544
struct pid *pid, struct task_struct *tsk)
6545
{
6546
char *buf;
6547
int retval;
6548
struct cgroup_root *root;
6549
6550
retval = -ENOMEM;
6551
buf = kmalloc(PATH_MAX, GFP_KERNEL);
6552
if (!buf)
6553
goto out;
6554
6555
rcu_read_lock();
6556
spin_lock_irq(&css_set_lock);
6557
6558
for_each_root(root) {
6559
struct cgroup_subsys *ss;
6560
struct cgroup *cgrp;
6561
int ssid, count = 0;
6562
6563
if (root == &cgrp_dfl_root && !READ_ONCE(cgrp_dfl_visible))
6564
continue;
6565
6566
cgrp = task_cgroup_from_root(tsk, root);
6567
/* The root has already been unmounted. */
6568
if (!cgrp)
6569
continue;
6570
6571
seq_printf(m, "%d:", root->hierarchy_id);
6572
if (root != &cgrp_dfl_root)
6573
for_each_subsys(ss, ssid)
6574
if (root->subsys_mask & (1 << ssid))
6575
seq_printf(m, "%s%s", count++ ? "," : "",
6576
ss->legacy_name);
6577
if (strlen(root->name))
6578
seq_printf(m, "%sname=%s", count ? "," : "",
6579
root->name);
6580
seq_putc(m, ':');
6581
/*
6582
* On traditional hierarchies, all zombie tasks show up as
6583
* belonging to the root cgroup. On the default hierarchy,
6584
* while a zombie doesn't show up in "cgroup.procs" and
6585
* thus can't be migrated, its /proc/PID/cgroup keeps
6586
* reporting the cgroup it belonged to before exiting. If
6587
* the cgroup is removed before the zombie is reaped,
6588
* " (deleted)" is appended to the cgroup path.
6589
*/
6590
if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
6591
retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
6592
current->nsproxy->cgroup_ns);
6593
if (retval == -E2BIG)
6594
retval = -ENAMETOOLONG;
6595
if (retval < 0)
6596
goto out_unlock;
6597
6598
seq_puts(m, buf);
6599
} else {
6600
seq_puts(m, "/");
6601
}
6602
6603
if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
6604
seq_puts(m, " (deleted)\n");
6605
else
6606
seq_putc(m, '\n');
6607
}
6608
6609
retval = 0;
6610
out_unlock:
6611
spin_unlock_irq(&css_set_lock);
6612
rcu_read_unlock();
6613
kfree(buf);
6614
out:
6615
return retval;
6616
}
6617
6618
/**
6619
* cgroup_fork - initialize cgroup related fields during copy_process()
6620
* @child: pointer to task_struct of forking parent process.
6621
*
6622
* A task is associated with the init_css_set until cgroup_post_fork()
6623
* attaches it to the target css_set.
6624
*/
6625
void cgroup_fork(struct task_struct *child)
6626
{
6627
RCU_INIT_POINTER(child->cgroups, &init_css_set);
6628
INIT_LIST_HEAD(&child->cg_list);
6629
}
6630
6631
/**
6632
* cgroup_v1v2_get_from_file - get a cgroup pointer from a file pointer
6633
* @f: file corresponding to cgroup_dir
6634
*
6635
* Find the cgroup from a file pointer associated with a cgroup directory.
6636
* Returns a pointer to the cgroup on success. ERR_PTR is returned if the
6637
* cgroup cannot be found.
6638
*/
6639
static struct cgroup *cgroup_v1v2_get_from_file(struct file *f)
6640
{
6641
struct cgroup_subsys_state *css;
6642
6643
css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
6644
if (IS_ERR(css))
6645
return ERR_CAST(css);
6646
6647
return css->cgroup;
6648
}
6649
6650
/**
6651
* cgroup_get_from_file - same as cgroup_v1v2_get_from_file, but only supports
6652
* cgroup2.
6653
* @f: file corresponding to cgroup2_dir
6654
*/
6655
static struct cgroup *cgroup_get_from_file(struct file *f)
6656
{
6657
struct cgroup *cgrp = cgroup_v1v2_get_from_file(f);
6658
6659
if (IS_ERR(cgrp))
6660
return ERR_CAST(cgrp);
6661
6662
if (!cgroup_on_dfl(cgrp)) {
6663
cgroup_put(cgrp);
6664
return ERR_PTR(-EBADF);
6665
}
6666
6667
return cgrp;
6668
}
6669
6670
/**
6671
* cgroup_css_set_fork - find or create a css_set for a child process
6672
* @kargs: the arguments passed to create the child process
6673
*
6674
* This functions finds or creates a new css_set which the child
6675
* process will be attached to in cgroup_post_fork(). By default,
6676
* the child process will be given the same css_set as its parent.
6677
*
6678
* If CLONE_INTO_CGROUP is specified this function will try to find an
6679
* existing css_set which includes the requested cgroup and if not create
6680
* a new css_set that the child will be attached to later. If this function
6681
* succeeds it will hold cgroup_threadgroup_rwsem on return. If
6682
* CLONE_INTO_CGROUP is requested this function will grab cgroup mutex
6683
* before grabbing cgroup_threadgroup_rwsem and will hold a reference
6684
* to the target cgroup.
6685
*/
6686
static int cgroup_css_set_fork(struct kernel_clone_args *kargs)
6687
__acquires(&cgroup_mutex) __acquires(&cgroup_threadgroup_rwsem)
6688
{
6689
int ret;
6690
struct cgroup *dst_cgrp = NULL;
6691
struct css_set *cset;
6692
struct super_block *sb;
6693
6694
if (kargs->flags & CLONE_INTO_CGROUP)
6695
cgroup_lock();
6696
6697
cgroup_threadgroup_change_begin(current);
6698
6699
spin_lock_irq(&css_set_lock);
6700
cset = task_css_set(current);
6701
get_css_set(cset);
6702
if (kargs->cgrp)
6703
kargs->kill_seq = kargs->cgrp->kill_seq;
6704
else
6705
kargs->kill_seq = cset->dfl_cgrp->kill_seq;
6706
spin_unlock_irq(&css_set_lock);
6707
6708
if (!(kargs->flags & CLONE_INTO_CGROUP)) {
6709
kargs->cset = cset;
6710
return 0;
6711
}
6712
6713
CLASS(fd_raw, f)(kargs->cgroup);
6714
if (fd_empty(f)) {
6715
ret = -EBADF;
6716
goto err;
6717
}
6718
sb = fd_file(f)->f_path.dentry->d_sb;
6719
6720
dst_cgrp = cgroup_get_from_file(fd_file(f));
6721
if (IS_ERR(dst_cgrp)) {
6722
ret = PTR_ERR(dst_cgrp);
6723
dst_cgrp = NULL;
6724
goto err;
6725
}
6726
6727
if (cgroup_is_dead(dst_cgrp)) {
6728
ret = -ENODEV;
6729
goto err;
6730
}
6731
6732
/*
6733
* Verify that we the target cgroup is writable for us. This is
6734
* usually done by the vfs layer but since we're not going through
6735
* the vfs layer here we need to do it "manually".
6736
*/
6737
ret = cgroup_may_write(dst_cgrp, sb);
6738
if (ret)
6739
goto err;
6740
6741
/*
6742
* Spawning a task directly into a cgroup works by passing a file
6743
* descriptor to the target cgroup directory. This can even be an O_PATH
6744
* file descriptor. But it can never be a cgroup.procs file descriptor.
6745
* This was done on purpose so spawning into a cgroup could be
6746
* conceptualized as an atomic
6747
*
6748
* fd = openat(dfd_cgroup, "cgroup.procs", ...);
6749
* write(fd, <child-pid>, ...);
6750
*
6751
* sequence, i.e. it's a shorthand for the caller opening and writing
6752
* cgroup.procs of the cgroup indicated by @dfd_cgroup. This allows us
6753
* to always use the caller's credentials.
6754
*/
6755
ret = cgroup_attach_permissions(cset->dfl_cgrp, dst_cgrp, sb,
6756
!(kargs->flags & CLONE_THREAD),
6757
current->nsproxy->cgroup_ns);
6758
if (ret)
6759
goto err;
6760
6761
kargs->cset = find_css_set(cset, dst_cgrp);
6762
if (!kargs->cset) {
6763
ret = -ENOMEM;
6764
goto err;
6765
}
6766
6767
put_css_set(cset);
6768
kargs->cgrp = dst_cgrp;
6769
return ret;
6770
6771
err:
6772
cgroup_threadgroup_change_end(current);
6773
cgroup_unlock();
6774
if (dst_cgrp)
6775
cgroup_put(dst_cgrp);
6776
put_css_set(cset);
6777
if (kargs->cset)
6778
put_css_set(kargs->cset);
6779
return ret;
6780
}
6781
6782
/**
6783
* cgroup_css_set_put_fork - drop references we took during fork
6784
* @kargs: the arguments passed to create the child process
6785
*
6786
* Drop references to the prepared css_set and target cgroup if
6787
* CLONE_INTO_CGROUP was requested.
6788
*/
6789
static void cgroup_css_set_put_fork(struct kernel_clone_args *kargs)
6790
__releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6791
{
6792
struct cgroup *cgrp = kargs->cgrp;
6793
struct css_set *cset = kargs->cset;
6794
6795
cgroup_threadgroup_change_end(current);
6796
6797
if (cset) {
6798
put_css_set(cset);
6799
kargs->cset = NULL;
6800
}
6801
6802
if (kargs->flags & CLONE_INTO_CGROUP) {
6803
cgroup_unlock();
6804
if (cgrp) {
6805
cgroup_put(cgrp);
6806
kargs->cgrp = NULL;
6807
}
6808
}
6809
}
6810
6811
/**
6812
* cgroup_can_fork - called on a new task before the process is exposed
6813
* @child: the child process
6814
* @kargs: the arguments passed to create the child process
6815
*
6816
* This prepares a new css_set for the child process which the child will
6817
* be attached to in cgroup_post_fork().
6818
* This calls the subsystem can_fork() callbacks. If the cgroup_can_fork()
6819
* callback returns an error, the fork aborts with that error code. This
6820
* allows for a cgroup subsystem to conditionally allow or deny new forks.
6821
*/
6822
int cgroup_can_fork(struct task_struct *child, struct kernel_clone_args *kargs)
6823
{
6824
struct cgroup_subsys *ss;
6825
int i, j, ret;
6826
6827
ret = cgroup_css_set_fork(kargs);
6828
if (ret)
6829
return ret;
6830
6831
do_each_subsys_mask(ss, i, have_canfork_callback) {
6832
ret = ss->can_fork(child, kargs->cset);
6833
if (ret)
6834
goto out_revert;
6835
} while_each_subsys_mask();
6836
6837
return 0;
6838
6839
out_revert:
6840
for_each_subsys(ss, j) {
6841
if (j >= i)
6842
break;
6843
if (ss->cancel_fork)
6844
ss->cancel_fork(child, kargs->cset);
6845
}
6846
6847
cgroup_css_set_put_fork(kargs);
6848
6849
return ret;
6850
}
6851
6852
/**
6853
* cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
6854
* @child: the child process
6855
* @kargs: the arguments passed to create the child process
6856
*
6857
* This calls the cancel_fork() callbacks if a fork failed *after*
6858
* cgroup_can_fork() succeeded and cleans up references we took to
6859
* prepare a new css_set for the child process in cgroup_can_fork().
6860
*/
6861
void cgroup_cancel_fork(struct task_struct *child,
6862
struct kernel_clone_args *kargs)
6863
{
6864
struct cgroup_subsys *ss;
6865
int i;
6866
6867
for_each_subsys(ss, i)
6868
if (ss->cancel_fork)
6869
ss->cancel_fork(child, kargs->cset);
6870
6871
cgroup_css_set_put_fork(kargs);
6872
}
6873
6874
/**
6875
* cgroup_post_fork - finalize cgroup setup for the child process
6876
* @child: the child process
6877
* @kargs: the arguments passed to create the child process
6878
*
6879
* Attach the child process to its css_set calling the subsystem fork()
6880
* callbacks.
6881
*/
6882
void cgroup_post_fork(struct task_struct *child,
6883
struct kernel_clone_args *kargs)
6884
__releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6885
{
6886
unsigned int cgrp_kill_seq = 0;
6887
unsigned long cgrp_flags = 0;
6888
bool kill = false;
6889
struct cgroup_subsys *ss;
6890
struct css_set *cset;
6891
int i;
6892
6893
cset = kargs->cset;
6894
kargs->cset = NULL;
6895
6896
spin_lock_irq(&css_set_lock);
6897
6898
/* init tasks are special, only link regular threads */
6899
if (likely(child->pid)) {
6900
if (kargs->cgrp) {
6901
cgrp_flags = kargs->cgrp->flags;
6902
cgrp_kill_seq = kargs->cgrp->kill_seq;
6903
} else {
6904
cgrp_flags = cset->dfl_cgrp->flags;
6905
cgrp_kill_seq = cset->dfl_cgrp->kill_seq;
6906
}
6907
6908
WARN_ON_ONCE(!list_empty(&child->cg_list));
6909
cset->nr_tasks++;
6910
css_set_move_task(child, NULL, cset, false);
6911
} else {
6912
put_css_set(cset);
6913
cset = NULL;
6914
}
6915
6916
if (!(child->flags & PF_KTHREAD)) {
6917
if (unlikely(test_bit(CGRP_FREEZE, &cgrp_flags))) {
6918
/*
6919
* If the cgroup has to be frozen, the new task has
6920
* too. Let's set the JOBCTL_TRAP_FREEZE jobctl bit to
6921
* get the task into the frozen state.
6922
*/
6923
spin_lock(&child->sighand->siglock);
6924
WARN_ON_ONCE(child->frozen);
6925
child->jobctl |= JOBCTL_TRAP_FREEZE;
6926
spin_unlock(&child->sighand->siglock);
6927
6928
/*
6929
* Calling cgroup_update_frozen() isn't required here,
6930
* because it will be called anyway a bit later from
6931
* do_freezer_trap(). So we avoid cgroup's transient
6932
* switch from the frozen state and back.
6933
*/
6934
}
6935
6936
/*
6937
* If the cgroup is to be killed notice it now and take the
6938
* child down right after we finished preparing it for
6939
* userspace.
6940
*/
6941
kill = kargs->kill_seq != cgrp_kill_seq;
6942
}
6943
6944
spin_unlock_irq(&css_set_lock);
6945
6946
/*
6947
* Call ss->fork(). This must happen after @child is linked on
6948
* css_set; otherwise, @child might change state between ->fork()
6949
* and addition to css_set.
6950
*/
6951
do_each_subsys_mask(ss, i, have_fork_callback) {
6952
ss->fork(child);
6953
} while_each_subsys_mask();
6954
6955
/* Make the new cset the root_cset of the new cgroup namespace. */
6956
if (kargs->flags & CLONE_NEWCGROUP) {
6957
struct css_set *rcset = child->nsproxy->cgroup_ns->root_cset;
6958
6959
get_css_set(cset);
6960
child->nsproxy->cgroup_ns->root_cset = cset;
6961
put_css_set(rcset);
6962
}
6963
6964
/* Cgroup has to be killed so take down child immediately. */
6965
if (unlikely(kill))
6966
do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, child, PIDTYPE_TGID);
6967
6968
cgroup_css_set_put_fork(kargs);
6969
}
6970
6971
/**
6972
* cgroup_task_exit - detach cgroup from exiting task
6973
* @tsk: pointer to task_struct of exiting process
6974
*
6975
* Description: Detach cgroup from @tsk.
6976
*
6977
*/
6978
void cgroup_task_exit(struct task_struct *tsk)
6979
{
6980
struct cgroup_subsys *ss;
6981
int i;
6982
6983
/* see cgroup_post_fork() for details */
6984
do_each_subsys_mask(ss, i, have_exit_callback) {
6985
ss->exit(tsk);
6986
} while_each_subsys_mask();
6987
}
6988
6989
static void do_cgroup_task_dead(struct task_struct *tsk)
6990
{
6991
struct css_set *cset;
6992
unsigned long flags;
6993
6994
spin_lock_irqsave(&css_set_lock, flags);
6995
6996
WARN_ON_ONCE(list_empty(&tsk->cg_list));
6997
cset = task_css_set(tsk);
6998
css_set_move_task(tsk, cset, NULL, false);
6999
cset->nr_tasks--;
7000
/* matches the signal->live check in css_task_iter_advance() */
7001
if (thread_group_leader(tsk) && atomic_read(&tsk->signal->live))
7002
list_add_tail(&tsk->cg_list, &cset->dying_tasks);
7003
7004
if (dl_task(tsk))
7005
dec_dl_tasks_cs(tsk);
7006
7007
WARN_ON_ONCE(cgroup_task_frozen(tsk));
7008
if (unlikely(!(tsk->flags & PF_KTHREAD) &&
7009
test_bit(CGRP_FREEZE, &task_dfl_cgroup(tsk)->flags)))
7010
cgroup_update_frozen(task_dfl_cgroup(tsk));
7011
7012
spin_unlock_irqrestore(&css_set_lock, flags);
7013
}
7014
7015
#ifdef CONFIG_PREEMPT_RT
7016
/*
7017
* cgroup_task_dead() is called from finish_task_switch() which doesn't allow
7018
* scheduling even in RT. As the task_dead path requires grabbing css_set_lock,
7019
* this lead to sleeping in the invalid context warning bug. css_set_lock is too
7020
* big to become a raw_spinlock. The task_dead path doesn't need to run
7021
* synchronously but can't be delayed indefinitely either as the dead task pins
7022
* the cgroup and task_struct can be pinned indefinitely. Bounce through lazy
7023
* irq_work to allow batching while ensuring timely completion.
7024
*/
7025
static DEFINE_PER_CPU(struct llist_head, cgrp_dead_tasks);
7026
static DEFINE_PER_CPU(struct irq_work, cgrp_dead_tasks_iwork);
7027
7028
static void cgrp_dead_tasks_iwork_fn(struct irq_work *iwork)
7029
{
7030
struct llist_node *lnode;
7031
struct task_struct *task, *next;
7032
7033
lnode = llist_del_all(this_cpu_ptr(&cgrp_dead_tasks));
7034
llist_for_each_entry_safe(task, next, lnode, cg_dead_lnode) {
7035
do_cgroup_task_dead(task);
7036
put_task_struct(task);
7037
}
7038
}
7039
7040
static void __init cgroup_rt_init(void)
7041
{
7042
int cpu;
7043
7044
for_each_possible_cpu(cpu) {
7045
init_llist_head(per_cpu_ptr(&cgrp_dead_tasks, cpu));
7046
per_cpu(cgrp_dead_tasks_iwork, cpu) =
7047
IRQ_WORK_INIT_LAZY(cgrp_dead_tasks_iwork_fn);
7048
}
7049
}
7050
7051
void cgroup_task_dead(struct task_struct *task)
7052
{
7053
get_task_struct(task);
7054
llist_add(&task->cg_dead_lnode, this_cpu_ptr(&cgrp_dead_tasks));
7055
irq_work_queue(this_cpu_ptr(&cgrp_dead_tasks_iwork));
7056
}
7057
#else /* CONFIG_PREEMPT_RT */
7058
static void __init cgroup_rt_init(void) {}
7059
7060
void cgroup_task_dead(struct task_struct *task)
7061
{
7062
do_cgroup_task_dead(task);
7063
}
7064
#endif /* CONFIG_PREEMPT_RT */
7065
7066
void cgroup_task_release(struct task_struct *task)
7067
{
7068
struct cgroup_subsys *ss;
7069
int ssid;
7070
7071
do_each_subsys_mask(ss, ssid, have_release_callback) {
7072
ss->release(task);
7073
} while_each_subsys_mask();
7074
}
7075
7076
void cgroup_task_free(struct task_struct *task)
7077
{
7078
struct css_set *cset = task_css_set(task);
7079
7080
if (!list_empty(&task->cg_list)) {
7081
spin_lock_irq(&css_set_lock);
7082
css_set_skip_task_iters(task_css_set(task), task);
7083
list_del_init(&task->cg_list);
7084
spin_unlock_irq(&css_set_lock);
7085
}
7086
7087
put_css_set(cset);
7088
}
7089
7090
static int __init cgroup_disable(char *str)
7091
{
7092
struct cgroup_subsys *ss;
7093
char *token;
7094
int i;
7095
7096
while ((token = strsep(&str, ",")) != NULL) {
7097
if (!*token)
7098
continue;
7099
7100
for_each_subsys(ss, i) {
7101
if (strcmp(token, ss->name) &&
7102
strcmp(token, ss->legacy_name))
7103
continue;
7104
7105
static_branch_disable(cgroup_subsys_enabled_key[i]);
7106
pr_info("Disabling %s control group subsystem\n",
7107
ss->name);
7108
}
7109
7110
for (i = 0; i < OPT_FEATURE_COUNT; i++) {
7111
if (strcmp(token, cgroup_opt_feature_names[i]))
7112
continue;
7113
cgroup_feature_disable_mask |= 1 << i;
7114
pr_info("Disabling %s control group feature\n",
7115
cgroup_opt_feature_names[i]);
7116
break;
7117
}
7118
}
7119
return 1;
7120
}
7121
__setup("cgroup_disable=", cgroup_disable);
7122
7123
void __init __weak enable_debug_cgroup(void) { }
7124
7125
static int __init enable_cgroup_debug(char *str)
7126
{
7127
cgroup_debug = true;
7128
enable_debug_cgroup();
7129
return 1;
7130
}
7131
__setup("cgroup_debug", enable_cgroup_debug);
7132
7133
static int __init cgroup_favordynmods_setup(char *str)
7134
{
7135
return (kstrtobool(str, &have_favordynmods) == 0);
7136
}
7137
__setup("cgroup_favordynmods=", cgroup_favordynmods_setup);
7138
7139
/**
7140
* css_tryget_online_from_dir - get corresponding css from a cgroup dentry
7141
* @dentry: directory dentry of interest
7142
* @ss: subsystem of interest
7143
*
7144
* If @dentry is a directory for a cgroup which has @ss enabled on it, try
7145
* to get the corresponding css and return it. If such css doesn't exist
7146
* or can't be pinned, an ERR_PTR value is returned.
7147
*/
7148
struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
7149
struct cgroup_subsys *ss)
7150
{
7151
struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
7152
struct file_system_type *s_type = dentry->d_sb->s_type;
7153
struct cgroup_subsys_state *css = NULL;
7154
struct cgroup *cgrp;
7155
7156
/* is @dentry a cgroup dir? */
7157
if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
7158
!kn || kernfs_type(kn) != KERNFS_DIR)
7159
return ERR_PTR(-EBADF);
7160
7161
rcu_read_lock();
7162
7163
/*
7164
* This path doesn't originate from kernfs and @kn could already
7165
* have been or be removed at any point. @kn->priv is RCU
7166
* protected for this access. See css_release_work_fn() for details.
7167
*/
7168
cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
7169
if (cgrp)
7170
css = cgroup_css(cgrp, ss);
7171
7172
if (!css || !css_tryget_online(css))
7173
css = ERR_PTR(-ENOENT);
7174
7175
rcu_read_unlock();
7176
return css;
7177
}
7178
7179
/**
7180
* css_from_id - lookup css by id
7181
* @id: the cgroup id
7182
* @ss: cgroup subsys to be looked into
7183
*
7184
* Returns the css if there's valid one with @id, otherwise returns NULL.
7185
* Should be called under rcu_read_lock().
7186
*/
7187
struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
7188
{
7189
WARN_ON_ONCE(!rcu_read_lock_held());
7190
return idr_find(&ss->css_idr, id);
7191
}
7192
7193
/**
7194
* cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
7195
* @path: path on the default hierarchy
7196
*
7197
* Find the cgroup at @path on the default hierarchy, increment its
7198
* reference count and return it. Returns pointer to the found cgroup on
7199
* success, ERR_PTR(-ENOENT) if @path doesn't exist or if the cgroup has already
7200
* been released and ERR_PTR(-ENOTDIR) if @path points to a non-directory.
7201
*/
7202
struct cgroup *cgroup_get_from_path(const char *path)
7203
{
7204
struct kernfs_node *kn;
7205
struct cgroup *cgrp = ERR_PTR(-ENOENT);
7206
struct cgroup *root_cgrp;
7207
7208
root_cgrp = current_cgns_cgroup_dfl();
7209
kn = kernfs_walk_and_get(root_cgrp->kn, path);
7210
if (!kn)
7211
goto out;
7212
7213
if (kernfs_type(kn) != KERNFS_DIR) {
7214
cgrp = ERR_PTR(-ENOTDIR);
7215
goto out_kernfs;
7216
}
7217
7218
rcu_read_lock();
7219
7220
cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
7221
if (!cgrp || !cgroup_tryget(cgrp))
7222
cgrp = ERR_PTR(-ENOENT);
7223
7224
rcu_read_unlock();
7225
7226
out_kernfs:
7227
kernfs_put(kn);
7228
out:
7229
return cgrp;
7230
}
7231
EXPORT_SYMBOL_GPL(cgroup_get_from_path);
7232
7233
/**
7234
* cgroup_v1v2_get_from_fd - get a cgroup pointer from a fd
7235
* @fd: fd obtained by open(cgroup_dir)
7236
*
7237
* Find the cgroup from a fd which should be obtained
7238
* by opening a cgroup directory. Returns a pointer to the
7239
* cgroup on success. ERR_PTR is returned if the cgroup
7240
* cannot be found.
7241
*/
7242
struct cgroup *cgroup_v1v2_get_from_fd(int fd)
7243
{
7244
CLASS(fd_raw, f)(fd);
7245
if (fd_empty(f))
7246
return ERR_PTR(-EBADF);
7247
7248
return cgroup_v1v2_get_from_file(fd_file(f));
7249
}
7250
7251
/**
7252
* cgroup_get_from_fd - same as cgroup_v1v2_get_from_fd, but only supports
7253
* cgroup2.
7254
* @fd: fd obtained by open(cgroup2_dir)
7255
*/
7256
struct cgroup *cgroup_get_from_fd(int fd)
7257
{
7258
struct cgroup *cgrp = cgroup_v1v2_get_from_fd(fd);
7259
7260
if (IS_ERR(cgrp))
7261
return ERR_CAST(cgrp);
7262
7263
if (!cgroup_on_dfl(cgrp)) {
7264
cgroup_put(cgrp);
7265
return ERR_PTR(-EBADF);
7266
}
7267
return cgrp;
7268
}
7269
EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
7270
7271
static u64 power_of_ten(int power)
7272
{
7273
u64 v = 1;
7274
while (power--)
7275
v *= 10;
7276
return v;
7277
}
7278
7279
/**
7280
* cgroup_parse_float - parse a floating number
7281
* @input: input string
7282
* @dec_shift: number of decimal digits to shift
7283
* @v: output
7284
*
7285
* Parse a decimal floating point number in @input and store the result in
7286
* @v with decimal point right shifted @dec_shift times. For example, if
7287
* @input is "12.3456" and @dec_shift is 3, *@v will be set to 12345.
7288
* Returns 0 on success, -errno otherwise.
7289
*
7290
* There's nothing cgroup specific about this function except that it's
7291
* currently the only user.
7292
*/
7293
int cgroup_parse_float(const char *input, unsigned dec_shift, s64 *v)
7294
{
7295
s64 whole, frac = 0;
7296
int fstart = 0, fend = 0, flen;
7297
7298
if (!sscanf(input, "%lld.%n%lld%n", &whole, &fstart, &frac, &fend))
7299
return -EINVAL;
7300
if (frac < 0)
7301
return -EINVAL;
7302
7303
flen = fend > fstart ? fend - fstart : 0;
7304
if (flen < dec_shift)
7305
frac *= power_of_ten(dec_shift - flen);
7306
else
7307
frac = DIV_ROUND_CLOSEST_ULL(frac, power_of_ten(flen - dec_shift));
7308
7309
*v = whole * power_of_ten(dec_shift) + frac;
7310
return 0;
7311
}
7312
7313
/*
7314
* sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
7315
* definition in cgroup-defs.h.
7316
*/
7317
#ifdef CONFIG_SOCK_CGROUP_DATA
7318
7319
void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
7320
{
7321
struct cgroup *cgroup;
7322
7323
rcu_read_lock();
7324
/* Don't associate the sock with unrelated interrupted task's cgroup. */
7325
if (in_interrupt()) {
7326
cgroup = &cgrp_dfl_root.cgrp;
7327
cgroup_get(cgroup);
7328
goto out;
7329
}
7330
7331
while (true) {
7332
struct css_set *cset;
7333
7334
cset = task_css_set(current);
7335
if (likely(cgroup_tryget(cset->dfl_cgrp))) {
7336
cgroup = cset->dfl_cgrp;
7337
break;
7338
}
7339
cpu_relax();
7340
}
7341
out:
7342
skcd->cgroup = cgroup;
7343
cgroup_bpf_get(cgroup);
7344
rcu_read_unlock();
7345
}
7346
7347
void cgroup_sk_clone(struct sock_cgroup_data *skcd)
7348
{
7349
struct cgroup *cgrp = sock_cgroup_ptr(skcd);
7350
7351
/*
7352
* We might be cloning a socket which is left in an empty
7353
* cgroup and the cgroup might have already been rmdir'd.
7354
* Don't use cgroup_get_live().
7355
*/
7356
cgroup_get(cgrp);
7357
cgroup_bpf_get(cgrp);
7358
}
7359
7360
void cgroup_sk_free(struct sock_cgroup_data *skcd)
7361
{
7362
struct cgroup *cgrp = sock_cgroup_ptr(skcd);
7363
7364
cgroup_bpf_put(cgrp);
7365
cgroup_put(cgrp);
7366
}
7367
7368
#endif /* CONFIG_SOCK_CGROUP_DATA */
7369
7370
#ifdef CONFIG_SYSFS
7371
static ssize_t show_delegatable_files(struct cftype *files, char *buf,
7372
ssize_t size, const char *prefix)
7373
{
7374
struct cftype *cft;
7375
ssize_t ret = 0;
7376
7377
for (cft = files; cft && cft->name[0] != '\0'; cft++) {
7378
if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
7379
continue;
7380
7381
if (prefix)
7382
ret += snprintf(buf + ret, size - ret, "%s.", prefix);
7383
7384
ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
7385
7386
if (WARN_ON(ret >= size))
7387
break;
7388
}
7389
7390
return ret;
7391
}
7392
7393
static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
7394
char *buf)
7395
{
7396
struct cgroup_subsys *ss;
7397
int ssid;
7398
ssize_t ret = 0;
7399
7400
ret = show_delegatable_files(cgroup_base_files, buf + ret,
7401
PAGE_SIZE - ret, NULL);
7402
if (cgroup_psi_enabled())
7403
ret += show_delegatable_files(cgroup_psi_files, buf + ret,
7404
PAGE_SIZE - ret, NULL);
7405
7406
for_each_subsys(ss, ssid)
7407
ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
7408
PAGE_SIZE - ret,
7409
cgroup_subsys_name[ssid]);
7410
7411
return ret;
7412
}
7413
static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
7414
7415
static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
7416
char *buf)
7417
{
7418
return snprintf(buf, PAGE_SIZE,
7419
"nsdelegate\n"
7420
"favordynmods\n"
7421
"memory_localevents\n"
7422
"memory_recursiveprot\n"
7423
"memory_hugetlb_accounting\n"
7424
"pids_localevents\n");
7425
}
7426
static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
7427
7428
static struct attribute *cgroup_sysfs_attrs[] = {
7429
&cgroup_delegate_attr.attr,
7430
&cgroup_features_attr.attr,
7431
NULL,
7432
};
7433
7434
static const struct attribute_group cgroup_sysfs_attr_group = {
7435
.attrs = cgroup_sysfs_attrs,
7436
.name = "cgroup",
7437
};
7438
7439
static int __init cgroup_sysfs_init(void)
7440
{
7441
return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
7442
}
7443
subsys_initcall(cgroup_sysfs_init);
7444
7445
#endif /* CONFIG_SYSFS */
7446
7447