xref: /linux/kernel/cgroup/cgroup-v1.c (revision 6aee5aed2edd0a156bf060abce1bdbbc38171c10)
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include "cgroup-internal.h"
3 
4 #include <linux/ctype.h>
5 #include <linux/kmod.h>
6 #include <linux/sort.h>
7 #include <linux/delay.h>
8 #include <linux/mm.h>
9 #include <linux/sched/signal.h>
10 #include <linux/sched/task.h>
11 #include <linux/magic.h>
12 #include <linux/slab.h>
13 #include <linux/vmalloc.h>
14 #include <linux/delayacct.h>
15 #include <linux/pid_namespace.h>
16 #include <linux/cgroupstats.h>
17 #include <linux/fs_parser.h>
18 
19 #include <trace/events/cgroup.h>
20 
21 /*
22  * pidlists linger the following amount before being destroyed.  The goal
23  * is avoiding frequent destruction in the middle of consecutive read calls
24  * Expiring in the middle is a performance problem not a correctness one.
25  * 1 sec should be enough.
26  */
27 #define CGROUP_PIDLIST_DESTROY_DELAY	HZ
28 
29 /* Controllers blocked by the commandline in v1 */
30 static u16 cgroup_no_v1_mask;
31 
32 /* disable named v1 mounts */
33 static bool cgroup_no_v1_named;
34 
35 /* Show unavailable controllers in /proc/cgroups */
36 static bool proc_show_all;
37 
38 /*
39  * pidlist destructions need to be flushed on cgroup destruction.  Use a
40  * separate workqueue as flush domain.
41  */
42 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
43 
44 /* protects cgroup_subsys->release_agent_path */
45 static DEFINE_SPINLOCK(release_agent_path_lock);
46 
cgroup1_ssid_disabled(int ssid)47 bool cgroup1_ssid_disabled(int ssid)
48 {
49 	return cgroup_no_v1_mask & (1 << ssid);
50 }
51 
cgroup1_subsys_absent(struct cgroup_subsys * ss)52 static bool cgroup1_subsys_absent(struct cgroup_subsys *ss)
53 {
54 	/* Check also dfl_cftypes for file-less controllers, i.e. perf_event */
55 	return ss->legacy_cftypes == NULL && ss->dfl_cftypes;
56 }
57 
58 /**
59  * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
60  * @from: attach to all cgroups of a given task
61  * @tsk: the task to be attached
62  *
63  * Return: %0 on success or a negative errno code on failure
64  */
cgroup_attach_task_all(struct task_struct * from,struct task_struct * tsk)65 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
66 {
67 	struct cgroup_root *root;
68 	int retval = 0;
69 
70 	cgroup_lock();
71 	cgroup_attach_lock(true);
72 	for_each_root(root) {
73 		struct cgroup *from_cgrp;
74 
75 		spin_lock_irq(&css_set_lock);
76 		from_cgrp = task_cgroup_from_root(from, root);
77 		spin_unlock_irq(&css_set_lock);
78 
79 		retval = cgroup_attach_task(from_cgrp, tsk, false);
80 		if (retval)
81 			break;
82 	}
83 	cgroup_attach_unlock(true);
84 	cgroup_unlock();
85 
86 	return retval;
87 }
88 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
89 
90 /**
91  * cgroup_transfer_tasks - move tasks from one cgroup to another
92  * @to: cgroup to which the tasks will be moved
93  * @from: cgroup in which the tasks currently reside
94  *
95  * Locking rules between cgroup_post_fork() and the migration path
96  * guarantee that, if a task is forking while being migrated, the new child
97  * is guaranteed to be either visible in the source cgroup after the
98  * parent's migration is complete or put into the target cgroup.  No task
99  * can slip out of migration through forking.
100  *
101  * Return: %0 on success or a negative errno code on failure
102  */
cgroup_transfer_tasks(struct cgroup * to,struct cgroup * from)103 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
104 {
105 	DEFINE_CGROUP_MGCTX(mgctx);
106 	struct cgrp_cset_link *link;
107 	struct css_task_iter it;
108 	struct task_struct *task;
109 	int ret;
110 
111 	if (cgroup_on_dfl(to))
112 		return -EINVAL;
113 
114 	ret = cgroup_migrate_vet_dst(to);
115 	if (ret)
116 		return ret;
117 
118 	cgroup_lock();
119 
120 	cgroup_attach_lock(true);
121 
122 	/* all tasks in @from are being moved, all csets are source */
123 	spin_lock_irq(&css_set_lock);
124 	list_for_each_entry(link, &from->cset_links, cset_link)
125 		cgroup_migrate_add_src(link->cset, to, &mgctx);
126 	spin_unlock_irq(&css_set_lock);
127 
128 	ret = cgroup_migrate_prepare_dst(&mgctx);
129 	if (ret)
130 		goto out_err;
131 
132 	/*
133 	 * Migrate tasks one-by-one until @from is empty.  This fails iff
134 	 * ->can_attach() fails.
135 	 */
136 	do {
137 		css_task_iter_start(&from->self, 0, &it);
138 
139 		do {
140 			task = css_task_iter_next(&it);
141 		} while (task && (task->flags & PF_EXITING));
142 
143 		if (task)
144 			get_task_struct(task);
145 		css_task_iter_end(&it);
146 
147 		if (task) {
148 			ret = cgroup_migrate(task, false, &mgctx);
149 			if (!ret)
150 				TRACE_CGROUP_PATH(transfer_tasks, to, task, false);
151 			put_task_struct(task);
152 		}
153 	} while (task && !ret);
154 out_err:
155 	cgroup_migrate_finish(&mgctx);
156 	cgroup_attach_unlock(true);
157 	cgroup_unlock();
158 	return ret;
159 }
160 
161 /*
162  * Stuff for reading the 'tasks'/'procs' files.
163  *
164  * Reading this file can return large amounts of data if a cgroup has
165  * *lots* of attached tasks. So it may need several calls to read(),
166  * but we cannot guarantee that the information we produce is correct
167  * unless we produce it entirely atomically.
168  *
169  */
170 
171 /* which pidlist file are we talking about? */
172 enum cgroup_filetype {
173 	CGROUP_FILE_PROCS,
174 	CGROUP_FILE_TASKS,
175 };
176 
177 /*
178  * A pidlist is a list of pids that virtually represents the contents of one
179  * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
180  * a pair (one each for procs, tasks) for each pid namespace that's relevant
181  * to the cgroup.
182  */
183 struct cgroup_pidlist {
184 	/*
185 	 * used to find which pidlist is wanted. doesn't change as long as
186 	 * this particular list stays in the list.
187 	*/
188 	struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
189 	/* array of xids */
190 	pid_t *list;
191 	/* how many elements the above list has */
192 	int length;
193 	/* each of these stored in a list by its cgroup */
194 	struct list_head links;
195 	/* pointer to the cgroup we belong to, for list removal purposes */
196 	struct cgroup *owner;
197 	/* for delayed destruction */
198 	struct delayed_work destroy_dwork;
199 };
200 
201 /*
202  * Used to destroy all pidlists lingering waiting for destroy timer.  None
203  * should be left afterwards.
204  */
cgroup1_pidlist_destroy_all(struct cgroup * cgrp)205 void cgroup1_pidlist_destroy_all(struct cgroup *cgrp)
206 {
207 	struct cgroup_pidlist *l, *tmp_l;
208 
209 	mutex_lock(&cgrp->pidlist_mutex);
210 	list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
211 		mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
212 	mutex_unlock(&cgrp->pidlist_mutex);
213 
214 	flush_workqueue(cgroup_pidlist_destroy_wq);
215 	BUG_ON(!list_empty(&cgrp->pidlists));
216 }
217 
cgroup_pidlist_destroy_work_fn(struct work_struct * work)218 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
219 {
220 	struct delayed_work *dwork = to_delayed_work(work);
221 	struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
222 						destroy_dwork);
223 	struct cgroup_pidlist *tofree = NULL;
224 
225 	mutex_lock(&l->owner->pidlist_mutex);
226 
227 	/*
228 	 * Destroy iff we didn't get queued again.  The state won't change
229 	 * as destroy_dwork can only be queued while locked.
230 	 */
231 	if (!delayed_work_pending(dwork)) {
232 		list_del(&l->links);
233 		kvfree(l->list);
234 		put_pid_ns(l->key.ns);
235 		tofree = l;
236 	}
237 
238 	mutex_unlock(&l->owner->pidlist_mutex);
239 	kfree(tofree);
240 }
241 
242 /*
243  * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
244  * Returns the number of unique elements.
245  */
pidlist_uniq(pid_t * list,int length)246 static int pidlist_uniq(pid_t *list, int length)
247 {
248 	int src, dest = 1;
249 
250 	/*
251 	 * we presume the 0th element is unique, so i starts at 1. trivial
252 	 * edge cases first; no work needs to be done for either
253 	 */
254 	if (length == 0 || length == 1)
255 		return length;
256 	/* src and dest walk down the list; dest counts unique elements */
257 	for (src = 1; src < length; src++) {
258 		/* find next unique element */
259 		while (list[src] == list[src-1]) {
260 			src++;
261 			if (src == length)
262 				goto after;
263 		}
264 		/* dest always points to where the next unique element goes */
265 		list[dest] = list[src];
266 		dest++;
267 	}
268 after:
269 	return dest;
270 }
271 
272 /*
273  * The two pid files - task and cgroup.procs - guaranteed that the result
274  * is sorted, which forced this whole pidlist fiasco.  As pid order is
275  * different per namespace, each namespace needs differently sorted list,
276  * making it impossible to use, for example, single rbtree of member tasks
277  * sorted by task pointer.  As pidlists can be fairly large, allocating one
278  * per open file is dangerous, so cgroup had to implement shared pool of
279  * pidlists keyed by cgroup and namespace.
280  */
cmppid(const void * a,const void * b)281 static int cmppid(const void *a, const void *b)
282 {
283 	return *(pid_t *)a - *(pid_t *)b;
284 }
285 
cgroup_pidlist_find(struct cgroup * cgrp,enum cgroup_filetype type)286 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
287 						  enum cgroup_filetype type)
288 {
289 	struct cgroup_pidlist *l;
290 	/* don't need task_nsproxy() if we're looking at ourself */
291 	struct pid_namespace *ns = task_active_pid_ns(current);
292 
293 	lockdep_assert_held(&cgrp->pidlist_mutex);
294 
295 	list_for_each_entry(l, &cgrp->pidlists, links)
296 		if (l->key.type == type && l->key.ns == ns)
297 			return l;
298 	return NULL;
299 }
300 
301 /*
302  * find the appropriate pidlist for our purpose (given procs vs tasks)
303  * returns with the lock on that pidlist already held, and takes care
304  * of the use count, or returns NULL with no locks held if we're out of
305  * memory.
306  */
cgroup_pidlist_find_create(struct cgroup * cgrp,enum cgroup_filetype type)307 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
308 						enum cgroup_filetype type)
309 {
310 	struct cgroup_pidlist *l;
311 
312 	lockdep_assert_held(&cgrp->pidlist_mutex);
313 
314 	l = cgroup_pidlist_find(cgrp, type);
315 	if (l)
316 		return l;
317 
318 	/* entry not found; create a new one */
319 	l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
320 	if (!l)
321 		return l;
322 
323 	INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
324 	l->key.type = type;
325 	/* don't need task_nsproxy() if we're looking at ourself */
326 	l->key.ns = get_pid_ns(task_active_pid_ns(current));
327 	l->owner = cgrp;
328 	list_add(&l->links, &cgrp->pidlists);
329 	return l;
330 }
331 
332 /*
333  * Load a cgroup's pidarray with either procs' tgids or tasks' pids
334  */
pidlist_array_load(struct cgroup * cgrp,enum cgroup_filetype type,struct cgroup_pidlist ** lp)335 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
336 			      struct cgroup_pidlist **lp)
337 {
338 	pid_t *array;
339 	int length;
340 	int pid, n = 0; /* used for populating the array */
341 	struct css_task_iter it;
342 	struct task_struct *tsk;
343 	struct cgroup_pidlist *l;
344 
345 	lockdep_assert_held(&cgrp->pidlist_mutex);
346 
347 	/*
348 	 * If cgroup gets more users after we read count, we won't have
349 	 * enough space - tough.  This race is indistinguishable to the
350 	 * caller from the case that the additional cgroup users didn't
351 	 * show up until sometime later on.
352 	 */
353 	length = cgroup_task_count(cgrp);
354 	array = kvmalloc_array(length, sizeof(pid_t), GFP_KERNEL);
355 	if (!array)
356 		return -ENOMEM;
357 	/* now, populate the array */
358 	css_task_iter_start(&cgrp->self, 0, &it);
359 	while ((tsk = css_task_iter_next(&it))) {
360 		if (unlikely(n == length))
361 			break;
362 		/* get tgid or pid for procs or tasks file respectively */
363 		if (type == CGROUP_FILE_PROCS)
364 			pid = task_tgid_vnr(tsk);
365 		else
366 			pid = task_pid_vnr(tsk);
367 		if (pid > 0) /* make sure to only use valid results */
368 			array[n++] = pid;
369 	}
370 	css_task_iter_end(&it);
371 	length = n;
372 	/* now sort & strip out duplicates (tgids or recycled thread PIDs) */
373 	sort(array, length, sizeof(pid_t), cmppid, NULL);
374 	length = pidlist_uniq(array, length);
375 
376 	l = cgroup_pidlist_find_create(cgrp, type);
377 	if (!l) {
378 		kvfree(array);
379 		return -ENOMEM;
380 	}
381 
382 	/* store array, freeing old if necessary */
383 	kvfree(l->list);
384 	l->list = array;
385 	l->length = length;
386 	*lp = l;
387 	return 0;
388 }
389 
390 /*
391  * seq_file methods for the tasks/procs files. The seq_file position is the
392  * next pid to display; the seq_file iterator is a pointer to the pid
393  * in the cgroup->l->list array.
394  */
395 
cgroup_pidlist_start(struct seq_file * s,loff_t * pos)396 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
397 {
398 	/*
399 	 * Initially we receive a position value that corresponds to
400 	 * one more than the last pid shown (or 0 on the first call or
401 	 * after a seek to the start). Use a binary-search to find the
402 	 * next pid to display, if any
403 	 */
404 	struct kernfs_open_file *of = s->private;
405 	struct cgroup_file_ctx *ctx = of->priv;
406 	struct cgroup *cgrp = seq_css(s)->cgroup;
407 	struct cgroup_pidlist *l;
408 	enum cgroup_filetype type = seq_cft(s)->private;
409 	int index = 0, pid = *pos;
410 	int *iter, ret;
411 
412 	mutex_lock(&cgrp->pidlist_mutex);
413 
414 	/*
415 	 * !NULL @ctx->procs1.pidlist indicates that this isn't the first
416 	 * start() after open. If the matching pidlist is around, we can use
417 	 * that. Look for it. Note that @ctx->procs1.pidlist can't be used
418 	 * directly. It could already have been destroyed.
419 	 */
420 	if (ctx->procs1.pidlist)
421 		ctx->procs1.pidlist = cgroup_pidlist_find(cgrp, type);
422 
423 	/*
424 	 * Either this is the first start() after open or the matching
425 	 * pidlist has been destroyed inbetween.  Create a new one.
426 	 */
427 	if (!ctx->procs1.pidlist) {
428 		ret = pidlist_array_load(cgrp, type, &ctx->procs1.pidlist);
429 		if (ret)
430 			return ERR_PTR(ret);
431 	}
432 	l = ctx->procs1.pidlist;
433 
434 	if (pid) {
435 		int end = l->length;
436 
437 		while (index < end) {
438 			int mid = (index + end) / 2;
439 			if (l->list[mid] == pid) {
440 				index = mid;
441 				break;
442 			} else if (l->list[mid] < pid)
443 				index = mid + 1;
444 			else
445 				end = mid;
446 		}
447 	}
448 	/* If we're off the end of the array, we're done */
449 	if (index >= l->length)
450 		return NULL;
451 	/* Update the abstract position to be the actual pid that we found */
452 	iter = l->list + index;
453 	*pos = *iter;
454 	return iter;
455 }
456 
cgroup_pidlist_stop(struct seq_file * s,void * v)457 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
458 {
459 	struct kernfs_open_file *of = s->private;
460 	struct cgroup_file_ctx *ctx = of->priv;
461 	struct cgroup_pidlist *l = ctx->procs1.pidlist;
462 
463 	if (l)
464 		mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
465 				 CGROUP_PIDLIST_DESTROY_DELAY);
466 	mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
467 }
468 
cgroup_pidlist_next(struct seq_file * s,void * v,loff_t * pos)469 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
470 {
471 	struct kernfs_open_file *of = s->private;
472 	struct cgroup_file_ctx *ctx = of->priv;
473 	struct cgroup_pidlist *l = ctx->procs1.pidlist;
474 	pid_t *p = v;
475 	pid_t *end = l->list + l->length;
476 	/*
477 	 * Advance to the next pid in the array. If this goes off the
478 	 * end, we're done
479 	 */
480 	p++;
481 	if (p >= end) {
482 		(*pos)++;
483 		return NULL;
484 	} else {
485 		*pos = *p;
486 		return p;
487 	}
488 }
489 
cgroup_pidlist_show(struct seq_file * s,void * v)490 static int cgroup_pidlist_show(struct seq_file *s, void *v)
491 {
492 	seq_printf(s, "%d\n", *(int *)v);
493 
494 	return 0;
495 }
496 
__cgroup1_procs_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off,bool threadgroup)497 static ssize_t __cgroup1_procs_write(struct kernfs_open_file *of,
498 				     char *buf, size_t nbytes, loff_t off,
499 				     bool threadgroup)
500 {
501 	struct cgroup *cgrp;
502 	struct task_struct *task;
503 	const struct cred *cred, *tcred;
504 	ssize_t ret;
505 	bool locked;
506 
507 	cgrp = cgroup_kn_lock_live(of->kn, false);
508 	if (!cgrp)
509 		return -ENODEV;
510 
511 	task = cgroup_procs_write_start(buf, threadgroup, &locked);
512 	ret = PTR_ERR_OR_ZERO(task);
513 	if (ret)
514 		goto out_unlock;
515 
516 	/*
517 	 * Even if we're attaching all tasks in the thread group, we only need
518 	 * to check permissions on one of them. Check permissions using the
519 	 * credentials from file open to protect against inherited fd attacks.
520 	 */
521 	cred = of->file->f_cred;
522 	tcred = get_task_cred(task);
523 	if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
524 	    !uid_eq(cred->euid, tcred->uid) &&
525 	    !uid_eq(cred->euid, tcred->suid))
526 		ret = -EACCES;
527 	put_cred(tcred);
528 	if (ret)
529 		goto out_finish;
530 
531 	ret = cgroup_attach_task(cgrp, task, threadgroup);
532 
533 out_finish:
534 	cgroup_procs_write_finish(task, locked);
535 out_unlock:
536 	cgroup_kn_unlock(of->kn);
537 
538 	return ret ?: nbytes;
539 }
540 
cgroup1_procs_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)541 static ssize_t cgroup1_procs_write(struct kernfs_open_file *of,
542 				   char *buf, size_t nbytes, loff_t off)
543 {
544 	return __cgroup1_procs_write(of, buf, nbytes, off, true);
545 }
546 
cgroup1_tasks_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)547 static ssize_t cgroup1_tasks_write(struct kernfs_open_file *of,
548 				   char *buf, size_t nbytes, loff_t off)
549 {
550 	return __cgroup1_procs_write(of, buf, nbytes, off, false);
551 }
552 
cgroup_release_agent_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)553 static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
554 					  char *buf, size_t nbytes, loff_t off)
555 {
556 	struct cgroup *cgrp;
557 	struct cgroup_file_ctx *ctx;
558 
559 	BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
560 
561 	/*
562 	 * Release agent gets called with all capabilities,
563 	 * require capabilities to set release agent.
564 	 */
565 	ctx = of->priv;
566 	if ((ctx->ns->user_ns != &init_user_ns) ||
567 	    !file_ns_capable(of->file, &init_user_ns, CAP_SYS_ADMIN))
568 		return -EPERM;
569 
570 	cgrp = cgroup_kn_lock_live(of->kn, false);
571 	if (!cgrp)
572 		return -ENODEV;
573 	spin_lock(&release_agent_path_lock);
574 	strscpy(cgrp->root->release_agent_path, strstrip(buf),
575 		sizeof(cgrp->root->release_agent_path));
576 	spin_unlock(&release_agent_path_lock);
577 	cgroup_kn_unlock(of->kn);
578 	return nbytes;
579 }
580 
cgroup_release_agent_show(struct seq_file * seq,void * v)581 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
582 {
583 	struct cgroup *cgrp = seq_css(seq)->cgroup;
584 
585 	spin_lock(&release_agent_path_lock);
586 	seq_puts(seq, cgrp->root->release_agent_path);
587 	spin_unlock(&release_agent_path_lock);
588 	seq_putc(seq, '\n');
589 	return 0;
590 }
591 
cgroup_sane_behavior_show(struct seq_file * seq,void * v)592 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
593 {
594 	seq_puts(seq, "0\n");
595 	return 0;
596 }
597 
cgroup_read_notify_on_release(struct cgroup_subsys_state * css,struct cftype * cft)598 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
599 					 struct cftype *cft)
600 {
601 	return notify_on_release(css->cgroup);
602 }
603 
cgroup_write_notify_on_release(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)604 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
605 					  struct cftype *cft, u64 val)
606 {
607 	if (val)
608 		set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
609 	else
610 		clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
611 	return 0;
612 }
613 
cgroup_clone_children_read(struct cgroup_subsys_state * css,struct cftype * cft)614 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
615 				      struct cftype *cft)
616 {
617 	return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
618 }
619 
cgroup_clone_children_write(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)620 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
621 				       struct cftype *cft, u64 val)
622 {
623 	if (val)
624 		set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
625 	else
626 		clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
627 	return 0;
628 }
629 
630 /* cgroup core interface files for the legacy hierarchies */
631 struct cftype cgroup1_base_files[] = {
632 	{
633 		.name = "cgroup.procs",
634 		.seq_start = cgroup_pidlist_start,
635 		.seq_next = cgroup_pidlist_next,
636 		.seq_stop = cgroup_pidlist_stop,
637 		.seq_show = cgroup_pidlist_show,
638 		.private = CGROUP_FILE_PROCS,
639 		.write = cgroup1_procs_write,
640 	},
641 	{
642 		.name = "cgroup.clone_children",
643 		.read_u64 = cgroup_clone_children_read,
644 		.write_u64 = cgroup_clone_children_write,
645 	},
646 	{
647 		.name = "cgroup.sane_behavior",
648 		.flags = CFTYPE_ONLY_ON_ROOT,
649 		.seq_show = cgroup_sane_behavior_show,
650 	},
651 	{
652 		.name = "tasks",
653 		.seq_start = cgroup_pidlist_start,
654 		.seq_next = cgroup_pidlist_next,
655 		.seq_stop = cgroup_pidlist_stop,
656 		.seq_show = cgroup_pidlist_show,
657 		.private = CGROUP_FILE_TASKS,
658 		.write = cgroup1_tasks_write,
659 	},
660 	{
661 		.name = "notify_on_release",
662 		.read_u64 = cgroup_read_notify_on_release,
663 		.write_u64 = cgroup_write_notify_on_release,
664 	},
665 	{
666 		.name = "release_agent",
667 		.flags = CFTYPE_ONLY_ON_ROOT,
668 		.seq_show = cgroup_release_agent_show,
669 		.write = cgroup_release_agent_write,
670 		.max_write_len = PATH_MAX - 1,
671 	},
672 	{ }	/* terminate */
673 };
674 
675 /* Display information about each subsystem and each hierarchy */
proc_cgroupstats_show(struct seq_file * m,void * v)676 int proc_cgroupstats_show(struct seq_file *m, void *v)
677 {
678 	struct cgroup_subsys *ss;
679 	bool cgrp_v1_visible = false;
680 	int i;
681 
682 	seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
683 	/*
684 	 * Grab the subsystems state racily. No need to add avenue to
685 	 * cgroup_mutex contention.
686 	 */
687 
688 	for_each_subsys(ss, i) {
689 		cgrp_v1_visible |= ss->root != &cgrp_dfl_root;
690 
691 		if (!proc_show_all && cgroup1_subsys_absent(ss))
692 			continue;
693 
694 		seq_printf(m, "%s\t%d\t%d\t%d\n",
695 			   ss->legacy_name, ss->root->hierarchy_id,
696 			   atomic_read(&ss->root->nr_cgrps),
697 			   cgroup_ssid_enabled(i));
698 	}
699 
700 	if (cgrp_dfl_visible && !cgrp_v1_visible)
701 		pr_info_once("/proc/cgroups lists only v1 controllers, use cgroup.controllers of root cgroup for v2 info\n");
702 
703 
704 	return 0;
705 }
706 
707 /**
708  * cgroupstats_build - build and fill cgroupstats
709  * @stats: cgroupstats to fill information into
710  * @dentry: A dentry entry belonging to the cgroup for which stats have
711  * been requested.
712  *
713  * Build and fill cgroupstats so that taskstats can export it to user
714  * space.
715  *
716  * Return: %0 on success or a negative errno code on failure
717  */
cgroupstats_build(struct cgroupstats * stats,struct dentry * dentry)718 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
719 {
720 	struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
721 	struct cgroup *cgrp;
722 	struct css_task_iter it;
723 	struct task_struct *tsk;
724 
725 	/* it should be kernfs_node belonging to cgroupfs and is a directory */
726 	if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
727 	    kernfs_type(kn) != KERNFS_DIR)
728 		return -EINVAL;
729 
730 	/*
731 	 * We aren't being called from kernfs and there's no guarantee on
732 	 * @kn->priv's validity.  For this and css_tryget_online_from_dir(),
733 	 * @kn->priv is RCU safe.  Let's do the RCU dancing.
734 	 */
735 	rcu_read_lock();
736 	cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
737 	if (!cgrp || !cgroup_tryget(cgrp)) {
738 		rcu_read_unlock();
739 		return -ENOENT;
740 	}
741 	rcu_read_unlock();
742 
743 	css_task_iter_start(&cgrp->self, 0, &it);
744 	while ((tsk = css_task_iter_next(&it))) {
745 		switch (READ_ONCE(tsk->__state)) {
746 		case TASK_RUNNING:
747 			stats->nr_running++;
748 			break;
749 		case TASK_INTERRUPTIBLE:
750 			stats->nr_sleeping++;
751 			break;
752 		case TASK_UNINTERRUPTIBLE:
753 			stats->nr_uninterruptible++;
754 			break;
755 		case TASK_STOPPED:
756 			stats->nr_stopped++;
757 			break;
758 		default:
759 			if (tsk->in_iowait)
760 				stats->nr_io_wait++;
761 			break;
762 		}
763 	}
764 	css_task_iter_end(&it);
765 
766 	cgroup_put(cgrp);
767 	return 0;
768 }
769 
cgroup1_check_for_release(struct cgroup * cgrp)770 void cgroup1_check_for_release(struct cgroup *cgrp)
771 {
772 	if (notify_on_release(cgrp) && !cgroup_is_populated(cgrp) &&
773 	    !css_has_online_children(&cgrp->self) && !cgroup_is_dead(cgrp))
774 		schedule_work(&cgrp->release_agent_work);
775 }
776 
777 /*
778  * Notify userspace when a cgroup is released, by running the
779  * configured release agent with the name of the cgroup (path
780  * relative to the root of cgroup file system) as the argument.
781  *
782  * Most likely, this user command will try to rmdir this cgroup.
783  *
784  * This races with the possibility that some other task will be
785  * attached to this cgroup before it is removed, or that some other
786  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
787  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
788  * unused, and this cgroup will be reprieved from its death sentence,
789  * to continue to serve a useful existence.  Next time it's released,
790  * we will get notified again, if it still has 'notify_on_release' set.
791  *
792  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
793  * means only wait until the task is successfully execve()'d.  The
794  * separate release agent task is forked by call_usermodehelper(),
795  * then control in this thread returns here, without waiting for the
796  * release agent task.  We don't bother to wait because the caller of
797  * this routine has no use for the exit status of the release agent
798  * task, so no sense holding our caller up for that.
799  */
cgroup1_release_agent(struct work_struct * work)800 void cgroup1_release_agent(struct work_struct *work)
801 {
802 	struct cgroup *cgrp =
803 		container_of(work, struct cgroup, release_agent_work);
804 	char *pathbuf, *agentbuf;
805 	char *argv[3], *envp[3];
806 	int ret;
807 
808 	/* snoop agent path and exit early if empty */
809 	if (!cgrp->root->release_agent_path[0])
810 		return;
811 
812 	/* prepare argument buffers */
813 	pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
814 	agentbuf = kmalloc(PATH_MAX, GFP_KERNEL);
815 	if (!pathbuf || !agentbuf)
816 		goto out_free;
817 
818 	spin_lock(&release_agent_path_lock);
819 	strscpy(agentbuf, cgrp->root->release_agent_path, PATH_MAX);
820 	spin_unlock(&release_agent_path_lock);
821 	if (!agentbuf[0])
822 		goto out_free;
823 
824 	ret = cgroup_path_ns(cgrp, pathbuf, PATH_MAX, &init_cgroup_ns);
825 	if (ret < 0)
826 		goto out_free;
827 
828 	argv[0] = agentbuf;
829 	argv[1] = pathbuf;
830 	argv[2] = NULL;
831 
832 	/* minimal command environment */
833 	envp[0] = "HOME=/";
834 	envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
835 	envp[2] = NULL;
836 
837 	call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
838 out_free:
839 	kfree(agentbuf);
840 	kfree(pathbuf);
841 }
842 
843 /*
844  * cgroup_rename - Only allow simple rename of directories in place.
845  */
cgroup1_rename(struct kernfs_node * kn,struct kernfs_node * new_parent,const char * new_name_str)846 static int cgroup1_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
847 			  const char *new_name_str)
848 {
849 	struct cgroup *cgrp = kn->priv;
850 	int ret;
851 
852 	/* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
853 	if (strchr(new_name_str, '\n'))
854 		return -EINVAL;
855 
856 	if (kernfs_type(kn) != KERNFS_DIR)
857 		return -ENOTDIR;
858 	if (rcu_access_pointer(kn->__parent) != new_parent)
859 		return -EIO;
860 
861 	/*
862 	 * We're gonna grab cgroup_mutex which nests outside kernfs
863 	 * active_ref.  kernfs_rename() doesn't require active_ref
864 	 * protection.  Break them before grabbing cgroup_mutex.
865 	 */
866 	kernfs_break_active_protection(new_parent);
867 	kernfs_break_active_protection(kn);
868 
869 	cgroup_lock();
870 
871 	ret = kernfs_rename(kn, new_parent, new_name_str);
872 	if (!ret)
873 		TRACE_CGROUP_PATH(rename, cgrp);
874 
875 	cgroup_unlock();
876 
877 	kernfs_unbreak_active_protection(kn);
878 	kernfs_unbreak_active_protection(new_parent);
879 	return ret;
880 }
881 
cgroup1_show_options(struct seq_file * seq,struct kernfs_root * kf_root)882 static int cgroup1_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
883 {
884 	struct cgroup_root *root = cgroup_root_from_kf(kf_root);
885 	struct cgroup_subsys *ss;
886 	int ssid;
887 
888 	for_each_subsys(ss, ssid)
889 		if (root->subsys_mask & (1 << ssid))
890 			seq_show_option(seq, ss->legacy_name, NULL);
891 	if (root->flags & CGRP_ROOT_NOPREFIX)
892 		seq_puts(seq, ",noprefix");
893 	if (root->flags & CGRP_ROOT_XATTR)
894 		seq_puts(seq, ",xattr");
895 	if (root->flags & CGRP_ROOT_CPUSET_V2_MODE)
896 		seq_puts(seq, ",cpuset_v2_mode");
897 	if (root->flags & CGRP_ROOT_FAVOR_DYNMODS)
898 		seq_puts(seq, ",favordynmods");
899 
900 	spin_lock(&release_agent_path_lock);
901 	if (strlen(root->release_agent_path))
902 		seq_show_option(seq, "release_agent",
903 				root->release_agent_path);
904 	spin_unlock(&release_agent_path_lock);
905 
906 	if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
907 		seq_puts(seq, ",clone_children");
908 	if (strlen(root->name))
909 		seq_show_option(seq, "name", root->name);
910 	return 0;
911 }
912 
913 enum cgroup1_param {
914 	Opt_all,
915 	Opt_clone_children,
916 	Opt_cpuset_v2_mode,
917 	Opt_name,
918 	Opt_none,
919 	Opt_noprefix,
920 	Opt_release_agent,
921 	Opt_xattr,
922 	Opt_favordynmods,
923 	Opt_nofavordynmods,
924 };
925 
926 const struct fs_parameter_spec cgroup1_fs_parameters[] = {
927 	fsparam_flag  ("all",		Opt_all),
928 	fsparam_flag  ("clone_children", Opt_clone_children),
929 	fsparam_flag  ("cpuset_v2_mode", Opt_cpuset_v2_mode),
930 	fsparam_string("name",		Opt_name),
931 	fsparam_flag  ("none",		Opt_none),
932 	fsparam_flag  ("noprefix",	Opt_noprefix),
933 	fsparam_string("release_agent",	Opt_release_agent),
934 	fsparam_flag  ("xattr",		Opt_xattr),
935 	fsparam_flag  ("favordynmods",	Opt_favordynmods),
936 	fsparam_flag  ("nofavordynmods", Opt_nofavordynmods),
937 	{}
938 };
939 
cgroup1_parse_param(struct fs_context * fc,struct fs_parameter * param)940 int cgroup1_parse_param(struct fs_context *fc, struct fs_parameter *param)
941 {
942 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
943 	struct cgroup_subsys *ss;
944 	struct fs_parse_result result;
945 	int opt, i;
946 
947 	opt = fs_parse(fc, cgroup1_fs_parameters, param, &result);
948 	if (opt == -ENOPARAM) {
949 		int ret;
950 
951 		ret = vfs_parse_fs_param_source(fc, param);
952 		if (ret != -ENOPARAM)
953 			return ret;
954 		for_each_subsys(ss, i) {
955 			if (strcmp(param->key, ss->legacy_name) ||
956 			    cgroup1_subsys_absent(ss))
957 				continue;
958 			if (!cgroup_ssid_enabled(i) || cgroup1_ssid_disabled(i))
959 				return invalfc(fc, "Disabled controller '%s'",
960 					       param->key);
961 			ctx->subsys_mask |= (1 << i);
962 			return 0;
963 		}
964 		return invalfc(fc, "Unknown subsys name '%s'", param->key);
965 	}
966 	if (opt < 0)
967 		return opt;
968 
969 	switch (opt) {
970 	case Opt_none:
971 		/* Explicitly have no subsystems */
972 		ctx->none = true;
973 		break;
974 	case Opt_all:
975 		ctx->all_ss = true;
976 		break;
977 	case Opt_noprefix:
978 		ctx->flags |= CGRP_ROOT_NOPREFIX;
979 		break;
980 	case Opt_clone_children:
981 		ctx->cpuset_clone_children = true;
982 		break;
983 	case Opt_cpuset_v2_mode:
984 		ctx->flags |= CGRP_ROOT_CPUSET_V2_MODE;
985 		break;
986 	case Opt_xattr:
987 		ctx->flags |= CGRP_ROOT_XATTR;
988 		break;
989 	case Opt_favordynmods:
990 		ctx->flags |= CGRP_ROOT_FAVOR_DYNMODS;
991 		break;
992 	case Opt_nofavordynmods:
993 		ctx->flags &= ~CGRP_ROOT_FAVOR_DYNMODS;
994 		break;
995 	case Opt_release_agent:
996 		/* Specifying two release agents is forbidden */
997 		if (ctx->release_agent)
998 			return invalfc(fc, "release_agent respecified");
999 		/*
1000 		 * Release agent gets called with all capabilities,
1001 		 * require capabilities to set release agent.
1002 		 */
1003 		if ((fc->user_ns != &init_user_ns) || !capable(CAP_SYS_ADMIN))
1004 			return invalfc(fc, "Setting release_agent not allowed");
1005 		ctx->release_agent = param->string;
1006 		param->string = NULL;
1007 		break;
1008 	case Opt_name:
1009 		/* blocked by boot param? */
1010 		if (cgroup_no_v1_named)
1011 			return -ENOENT;
1012 		/* Can't specify an empty name */
1013 		if (!param->size)
1014 			return invalfc(fc, "Empty name");
1015 		if (param->size > MAX_CGROUP_ROOT_NAMELEN - 1)
1016 			return invalfc(fc, "Name too long");
1017 		/* Must match [\w.-]+ */
1018 		for (i = 0; i < param->size; i++) {
1019 			char c = param->string[i];
1020 			if (isalnum(c))
1021 				continue;
1022 			if ((c == '.') || (c == '-') || (c == '_'))
1023 				continue;
1024 			return invalfc(fc, "Invalid name");
1025 		}
1026 		/* Specifying two names is forbidden */
1027 		if (ctx->name)
1028 			return invalfc(fc, "name respecified");
1029 		ctx->name = param->string;
1030 		param->string = NULL;
1031 		break;
1032 	}
1033 	return 0;
1034 }
1035 
check_cgroupfs_options(struct fs_context * fc)1036 static int check_cgroupfs_options(struct fs_context *fc)
1037 {
1038 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1039 	u16 mask = U16_MAX;
1040 	u16 enabled = 0;
1041 	struct cgroup_subsys *ss;
1042 	int i;
1043 
1044 #ifdef CONFIG_CPUSETS
1045 	mask = ~((u16)1 << cpuset_cgrp_id);
1046 #endif
1047 	for_each_subsys(ss, i)
1048 		if (cgroup_ssid_enabled(i) && !cgroup1_ssid_disabled(i) &&
1049 		    !cgroup1_subsys_absent(ss))
1050 			enabled |= 1 << i;
1051 
1052 	ctx->subsys_mask &= enabled;
1053 
1054 	/*
1055 	 * In absence of 'none', 'name=' and subsystem name options,
1056 	 * let's default to 'all'.
1057 	 */
1058 	if (!ctx->subsys_mask && !ctx->none && !ctx->name)
1059 		ctx->all_ss = true;
1060 
1061 	if (ctx->all_ss) {
1062 		/* Mutually exclusive option 'all' + subsystem name */
1063 		if (ctx->subsys_mask)
1064 			return invalfc(fc, "subsys name conflicts with all");
1065 		/* 'all' => select all the subsystems */
1066 		ctx->subsys_mask = enabled;
1067 	}
1068 
1069 	/*
1070 	 * We either have to specify by name or by subsystems. (So all
1071 	 * empty hierarchies must have a name).
1072 	 */
1073 	if (!ctx->subsys_mask && !ctx->name)
1074 		return invalfc(fc, "Need name or subsystem set");
1075 
1076 	/*
1077 	 * Option noprefix was introduced just for backward compatibility
1078 	 * with the old cpuset, so we allow noprefix only if mounting just
1079 	 * the cpuset subsystem.
1080 	 */
1081 	if ((ctx->flags & CGRP_ROOT_NOPREFIX) && (ctx->subsys_mask & mask))
1082 		return invalfc(fc, "noprefix used incorrectly");
1083 
1084 	/* Can't specify "none" and some subsystems */
1085 	if (ctx->subsys_mask && ctx->none)
1086 		return invalfc(fc, "none used incorrectly");
1087 
1088 	return 0;
1089 }
1090 
cgroup1_reconfigure(struct fs_context * fc)1091 int cgroup1_reconfigure(struct fs_context *fc)
1092 {
1093 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1094 	struct kernfs_root *kf_root = kernfs_root_from_sb(fc->root->d_sb);
1095 	struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1096 	int ret = 0;
1097 	u16 added_mask, removed_mask;
1098 
1099 	cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1100 
1101 	/* See what subsystems are wanted */
1102 	ret = check_cgroupfs_options(fc);
1103 	if (ret)
1104 		goto out_unlock;
1105 
1106 	if (ctx->subsys_mask != root->subsys_mask || ctx->release_agent)
1107 		pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1108 			task_tgid_nr(current), current->comm);
1109 
1110 	added_mask = ctx->subsys_mask & ~root->subsys_mask;
1111 	removed_mask = root->subsys_mask & ~ctx->subsys_mask;
1112 
1113 	/* Don't allow flags or name to change at remount */
1114 	if ((ctx->flags ^ root->flags) ||
1115 	    (ctx->name && strcmp(ctx->name, root->name))) {
1116 		errorfc(fc, "option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"",
1117 		       ctx->flags, ctx->name ?: "", root->flags, root->name);
1118 		ret = -EINVAL;
1119 		goto out_unlock;
1120 	}
1121 
1122 	/* remounting is not allowed for populated hierarchies */
1123 	if (!list_empty(&root->cgrp.self.children)) {
1124 		ret = -EBUSY;
1125 		goto out_unlock;
1126 	}
1127 
1128 	ret = rebind_subsystems(root, added_mask);
1129 	if (ret)
1130 		goto out_unlock;
1131 
1132 	WARN_ON(rebind_subsystems(&cgrp_dfl_root, removed_mask));
1133 
1134 	if (ctx->release_agent) {
1135 		spin_lock(&release_agent_path_lock);
1136 		strcpy(root->release_agent_path, ctx->release_agent);
1137 		spin_unlock(&release_agent_path_lock);
1138 	}
1139 
1140 	trace_cgroup_remount(root);
1141 
1142  out_unlock:
1143 	cgroup_unlock();
1144 	return ret;
1145 }
1146 
1147 struct kernfs_syscall_ops cgroup1_kf_syscall_ops = {
1148 	.rename			= cgroup1_rename,
1149 	.show_options		= cgroup1_show_options,
1150 	.mkdir			= cgroup_mkdir,
1151 	.rmdir			= cgroup_rmdir,
1152 	.show_path		= cgroup_show_path,
1153 };
1154 
1155 /*
1156  * The guts of cgroup1 mount - find or create cgroup_root to use.
1157  * Called with cgroup_mutex held; returns 0 on success, -E... on
1158  * error and positive - in case when the candidate is busy dying.
1159  * On success it stashes a reference to cgroup_root into given
1160  * cgroup_fs_context; that reference is *NOT* counting towards the
1161  * cgroup_root refcount.
1162  */
cgroup1_root_to_use(struct fs_context * fc)1163 static int cgroup1_root_to_use(struct fs_context *fc)
1164 {
1165 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1166 	struct cgroup_root *root;
1167 	struct cgroup_subsys *ss;
1168 	int i, ret;
1169 
1170 	/* First find the desired set of subsystems */
1171 	ret = check_cgroupfs_options(fc);
1172 	if (ret)
1173 		return ret;
1174 
1175 	/*
1176 	 * Destruction of cgroup root is asynchronous, so subsystems may
1177 	 * still be dying after the previous unmount.  Let's drain the
1178 	 * dying subsystems.  We just need to ensure that the ones
1179 	 * unmounted previously finish dying and don't care about new ones
1180 	 * starting.  Testing ref liveliness is good enough.
1181 	 */
1182 	for_each_subsys(ss, i) {
1183 		if (!(ctx->subsys_mask & (1 << i)) ||
1184 		    ss->root == &cgrp_dfl_root)
1185 			continue;
1186 
1187 		if (!percpu_ref_tryget_live(&ss->root->cgrp.self.refcnt))
1188 			return 1;	/* restart */
1189 		cgroup_put(&ss->root->cgrp);
1190 	}
1191 
1192 	for_each_root(root) {
1193 		bool name_match = false;
1194 
1195 		if (root == &cgrp_dfl_root)
1196 			continue;
1197 
1198 		/*
1199 		 * If we asked for a name then it must match.  Also, if
1200 		 * name matches but sybsys_mask doesn't, we should fail.
1201 		 * Remember whether name matched.
1202 		 */
1203 		if (ctx->name) {
1204 			if (strcmp(ctx->name, root->name))
1205 				continue;
1206 			name_match = true;
1207 		}
1208 
1209 		/*
1210 		 * If we asked for subsystems (or explicitly for no
1211 		 * subsystems) then they must match.
1212 		 */
1213 		if ((ctx->subsys_mask || ctx->none) &&
1214 		    (ctx->subsys_mask != root->subsys_mask)) {
1215 			if (!name_match)
1216 				continue;
1217 			return -EBUSY;
1218 		}
1219 
1220 		if (root->flags ^ ctx->flags)
1221 			pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1222 
1223 		ctx->root = root;
1224 		return 0;
1225 	}
1226 
1227 	/*
1228 	 * No such thing, create a new one.  name= matching without subsys
1229 	 * specification is allowed for already existing hierarchies but we
1230 	 * can't create new one without subsys specification.
1231 	 */
1232 	if (!ctx->subsys_mask && !ctx->none)
1233 		return invalfc(fc, "No subsys list or none specified");
1234 
1235 	/* Hierarchies may only be created in the initial cgroup namespace. */
1236 	if (ctx->ns != &init_cgroup_ns)
1237 		return -EPERM;
1238 
1239 	root = kzalloc(sizeof(*root), GFP_KERNEL);
1240 	if (!root)
1241 		return -ENOMEM;
1242 
1243 	ctx->root = root;
1244 	init_cgroup_root(ctx);
1245 
1246 	ret = cgroup_setup_root(root, ctx->subsys_mask);
1247 	if (!ret)
1248 		cgroup_favor_dynmods(root, ctx->flags & CGRP_ROOT_FAVOR_DYNMODS);
1249 	else
1250 		cgroup_free_root(root);
1251 
1252 	return ret;
1253 }
1254 
cgroup1_get_tree(struct fs_context * fc)1255 int cgroup1_get_tree(struct fs_context *fc)
1256 {
1257 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1258 	int ret;
1259 
1260 	/* Check if the caller has permission to mount. */
1261 	if (!ns_capable(ctx->ns->user_ns, CAP_SYS_ADMIN))
1262 		return -EPERM;
1263 
1264 	cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1265 
1266 	ret = cgroup1_root_to_use(fc);
1267 	if (!ret && !percpu_ref_tryget_live(&ctx->root->cgrp.self.refcnt))
1268 		ret = 1;	/* restart */
1269 
1270 	cgroup_unlock();
1271 
1272 	if (!ret)
1273 		ret = cgroup_do_get_tree(fc);
1274 
1275 	if (!ret && percpu_ref_is_dying(&ctx->root->cgrp.self.refcnt)) {
1276 		fc_drop_locked(fc);
1277 		ret = 1;
1278 	}
1279 
1280 	if (unlikely(ret > 0)) {
1281 		msleep(10);
1282 		return restart_syscall();
1283 	}
1284 	return ret;
1285 }
1286 
1287 /**
1288  * task_get_cgroup1 - Acquires the associated cgroup of a task within a
1289  * specific cgroup1 hierarchy. The cgroup1 hierarchy is identified by its
1290  * hierarchy ID.
1291  * @tsk: The target task
1292  * @hierarchy_id: The ID of a cgroup1 hierarchy
1293  *
1294  * On success, the cgroup is returned. On failure, ERR_PTR is returned.
1295  * We limit it to cgroup1 only.
1296  */
task_get_cgroup1(struct task_struct * tsk,int hierarchy_id)1297 struct cgroup *task_get_cgroup1(struct task_struct *tsk, int hierarchy_id)
1298 {
1299 	struct cgroup *cgrp = ERR_PTR(-ENOENT);
1300 	struct cgroup_root *root;
1301 	unsigned long flags;
1302 
1303 	rcu_read_lock();
1304 	for_each_root(root) {
1305 		/* cgroup1 only*/
1306 		if (root == &cgrp_dfl_root)
1307 			continue;
1308 		if (root->hierarchy_id != hierarchy_id)
1309 			continue;
1310 		spin_lock_irqsave(&css_set_lock, flags);
1311 		cgrp = task_cgroup_from_root(tsk, root);
1312 		if (!cgrp || !cgroup_tryget(cgrp))
1313 			cgrp = ERR_PTR(-ENOENT);
1314 		spin_unlock_irqrestore(&css_set_lock, flags);
1315 		break;
1316 	}
1317 	rcu_read_unlock();
1318 	return cgrp;
1319 }
1320 
cgroup1_wq_init(void)1321 static int __init cgroup1_wq_init(void)
1322 {
1323 	/*
1324 	 * Used to destroy pidlists and separate to serve as flush domain.
1325 	 * Cap @max_active to 1 too.
1326 	 */
1327 	cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
1328 						    0, 1);
1329 	BUG_ON(!cgroup_pidlist_destroy_wq);
1330 	return 0;
1331 }
1332 core_initcall(cgroup1_wq_init);
1333 
cgroup_no_v1(char * str)1334 static int __init cgroup_no_v1(char *str)
1335 {
1336 	struct cgroup_subsys *ss;
1337 	char *token;
1338 	int i;
1339 
1340 	while ((token = strsep(&str, ",")) != NULL) {
1341 		if (!*token)
1342 			continue;
1343 
1344 		if (!strcmp(token, "all")) {
1345 			cgroup_no_v1_mask = U16_MAX;
1346 			continue;
1347 		}
1348 
1349 		if (!strcmp(token, "named")) {
1350 			cgroup_no_v1_named = true;
1351 			continue;
1352 		}
1353 
1354 		for_each_subsys(ss, i) {
1355 			if (strcmp(token, ss->name) &&
1356 			    strcmp(token, ss->legacy_name))
1357 				continue;
1358 
1359 			cgroup_no_v1_mask |= 1 << i;
1360 			break;
1361 		}
1362 	}
1363 	return 1;
1364 }
1365 __setup("cgroup_no_v1=", cgroup_no_v1);
1366 
cgroup_v1_proc(char * str)1367 static int __init cgroup_v1_proc(char *str)
1368 {
1369 	return (kstrtobool(str, &proc_show_all) == 0);
1370 }
1371 __setup("cgroup_v1_proc=", cgroup_v1_proc);
1372