xref: /linux/kernel/cgroup/pids.c (revision e467705a9fb37f51595aa6deaca085ccb4005454)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Process number limiting controller for cgroups.
4  *
5  * Used to allow a cgroup hierarchy to stop any new processes from fork()ing
6  * after a certain limit is reached.
7  *
8  * Since it is trivial to hit the task limit without hitting any kmemcg limits
9  * in place, PIDs are a fundamental resource. As such, PID exhaustion must be
10  * preventable in the scope of a cgroup hierarchy by allowing resource limiting
11  * of the number of tasks in a cgroup.
12  *
13  * In order to use the `pids` controller, set the maximum number of tasks in
14  * pids.max (this is not available in the root cgroup for obvious reasons). The
15  * number of processes currently in the cgroup is given by pids.current.
16  * Organisational operations are not blocked by cgroup policies, so it is
17  * possible to have pids.current > pids.max. However, it is not possible to
18  * violate a cgroup policy through fork(). fork() will return -EAGAIN if forking
19  * would cause a cgroup policy to be violated.
20  *
21  * To set a cgroup to have no limit, set pids.max to "max". This is the default
22  * for all new cgroups (N.B. that PID limits are hierarchical, so the most
23  * stringent limit in the hierarchy is followed).
24  *
25  * pids.current tracks all child cgroup hierarchies, so parent/pids.current is
26  * a superset of parent/child/pids.current.
27  *
28  * Copyright (C) 2015 Aleksa Sarai <cyphar@cyphar.com>
29  */
30 
31 #include <linux/kernel.h>
32 #include <linux/threads.h>
33 #include <linux/atomic.h>
34 #include <linux/cgroup.h>
35 #include <linux/slab.h>
36 #include <linux/sched/task.h>
37 
38 #define PIDS_MAX (PID_MAX_LIMIT + 1ULL)
39 #define PIDS_MAX_STR "max"
40 
41 struct pids_cgroup {
42 	struct cgroup_subsys_state	css;
43 
44 	/*
45 	 * Use 64-bit types so that we can safely represent "max" as
46 	 * %PIDS_MAX = (%PID_MAX_LIMIT + 1).
47 	 */
48 	atomic64_t			counter;
49 	atomic64_t			limit;
50 	int64_t				watermark;
51 
52 	/* Handle for "pids.events" */
53 	struct cgroup_file		events_file;
54 
55 	/* Number of times fork failed because limit was hit. */
56 	atomic64_t			events_limit;
57 };
58 
59 static struct pids_cgroup *css_pids(struct cgroup_subsys_state *css)
60 {
61 	return container_of(css, struct pids_cgroup, css);
62 }
63 
64 static struct pids_cgroup *parent_pids(struct pids_cgroup *pids)
65 {
66 	return css_pids(pids->css.parent);
67 }
68 
69 static struct cgroup_subsys_state *
70 pids_css_alloc(struct cgroup_subsys_state *parent)
71 {
72 	struct pids_cgroup *pids;
73 
74 	pids = kzalloc(sizeof(struct pids_cgroup), GFP_KERNEL);
75 	if (!pids)
76 		return ERR_PTR(-ENOMEM);
77 
78 	atomic64_set(&pids->limit, PIDS_MAX);
79 	return &pids->css;
80 }
81 
82 static void pids_css_free(struct cgroup_subsys_state *css)
83 {
84 	kfree(css_pids(css));
85 }
86 
87 static void pids_update_watermark(struct pids_cgroup *p, int64_t nr_pids)
88 {
89 	/*
90 	 * This is racy, but we don't need perfectly accurate tallying of
91 	 * the watermark, and this lets us avoid extra atomic overhead.
92 	 */
93 	if (nr_pids > READ_ONCE(p->watermark))
94 		WRITE_ONCE(p->watermark, nr_pids);
95 }
96 
97 /**
98  * pids_cancel - uncharge the local pid count
99  * @pids: the pid cgroup state
100  * @num: the number of pids to cancel
101  *
102  * This function will WARN if the pid count goes under 0, because such a case is
103  * a bug in the pids controller proper.
104  */
105 static void pids_cancel(struct pids_cgroup *pids, int num)
106 {
107 	/*
108 	 * A negative count (or overflow for that matter) is invalid,
109 	 * and indicates a bug in the `pids` controller proper.
110 	 */
111 	WARN_ON_ONCE(atomic64_add_negative(-num, &pids->counter));
112 }
113 
114 /**
115  * pids_uncharge - hierarchically uncharge the pid count
116  * @pids: the pid cgroup state
117  * @num: the number of pids to uncharge
118  */
119 static void pids_uncharge(struct pids_cgroup *pids, int num)
120 {
121 	struct pids_cgroup *p;
122 
123 	for (p = pids; parent_pids(p); p = parent_pids(p))
124 		pids_cancel(p, num);
125 }
126 
127 /**
128  * pids_charge - hierarchically charge the pid count
129  * @pids: the pid cgroup state
130  * @num: the number of pids to charge
131  *
132  * This function does *not* follow the pid limit set. It cannot fail and the new
133  * pid count may exceed the limit. This is only used for reverting failed
134  * attaches, where there is no other way out than violating the limit.
135  */
136 static void pids_charge(struct pids_cgroup *pids, int num)
137 {
138 	struct pids_cgroup *p;
139 
140 	for (p = pids; parent_pids(p); p = parent_pids(p)) {
141 		int64_t new = atomic64_add_return(num, &p->counter);
142 
143 		pids_update_watermark(p, new);
144 	}
145 }
146 
147 /**
148  * pids_try_charge - hierarchically try to charge the pid count
149  * @pids: the pid cgroup state
150  * @num: the number of pids to charge
151  *
152  * This function follows the set limit. It will fail if the charge would cause
153  * the new value to exceed the hierarchical limit. Returns 0 if the charge
154  * succeeded, otherwise -EAGAIN.
155  */
156 static int pids_try_charge(struct pids_cgroup *pids, int num)
157 {
158 	struct pids_cgroup *p, *q;
159 
160 	for (p = pids; parent_pids(p); p = parent_pids(p)) {
161 		int64_t new = atomic64_add_return(num, &p->counter);
162 		int64_t limit = atomic64_read(&p->limit);
163 
164 		/*
165 		 * Since new is capped to the maximum number of pid_t, if
166 		 * p->limit is %PIDS_MAX then we know that this test will never
167 		 * fail.
168 		 */
169 		if (new > limit)
170 			goto revert;
171 
172 		/*
173 		 * Not technically accurate if we go over limit somewhere up
174 		 * the hierarchy, but that's tolerable for the watermark.
175 		 */
176 		pids_update_watermark(p, new);
177 	}
178 
179 	return 0;
180 
181 revert:
182 	for (q = pids; q != p; q = parent_pids(q))
183 		pids_cancel(q, num);
184 	pids_cancel(p, num);
185 
186 	return -EAGAIN;
187 }
188 
189 static int pids_can_attach(struct cgroup_taskset *tset)
190 {
191 	struct task_struct *task;
192 	struct cgroup_subsys_state *dst_css;
193 
194 	cgroup_taskset_for_each(task, dst_css, tset) {
195 		struct pids_cgroup *pids = css_pids(dst_css);
196 		struct cgroup_subsys_state *old_css;
197 		struct pids_cgroup *old_pids;
198 
199 		/*
200 		 * No need to pin @old_css between here and cancel_attach()
201 		 * because cgroup core protects it from being freed before
202 		 * the migration completes or fails.
203 		 */
204 		old_css = task_css(task, pids_cgrp_id);
205 		old_pids = css_pids(old_css);
206 
207 		pids_charge(pids, 1);
208 		pids_uncharge(old_pids, 1);
209 	}
210 
211 	return 0;
212 }
213 
214 static void pids_cancel_attach(struct cgroup_taskset *tset)
215 {
216 	struct task_struct *task;
217 	struct cgroup_subsys_state *dst_css;
218 
219 	cgroup_taskset_for_each(task, dst_css, tset) {
220 		struct pids_cgroup *pids = css_pids(dst_css);
221 		struct cgroup_subsys_state *old_css;
222 		struct pids_cgroup *old_pids;
223 
224 		old_css = task_css(task, pids_cgrp_id);
225 		old_pids = css_pids(old_css);
226 
227 		pids_charge(old_pids, 1);
228 		pids_uncharge(pids, 1);
229 	}
230 }
231 
232 /*
233  * task_css_check(true) in pids_can_fork() and pids_cancel_fork() relies
234  * on cgroup_threadgroup_change_begin() held by the copy_process().
235  */
236 static int pids_can_fork(struct task_struct *task, struct css_set *cset)
237 {
238 	struct cgroup_subsys_state *css;
239 	struct pids_cgroup *pids;
240 	int err;
241 
242 	if (cset)
243 		css = cset->subsys[pids_cgrp_id];
244 	else
245 		css = task_css_check(current, pids_cgrp_id, true);
246 	pids = css_pids(css);
247 	err = pids_try_charge(pids, 1);
248 	if (err) {
249 		/* Only log the first time events_limit is incremented. */
250 		if (atomic64_inc_return(&pids->events_limit) == 1) {
251 			pr_info("cgroup: fork rejected by pids controller in ");
252 			pr_cont_cgroup_path(css->cgroup);
253 			pr_cont("\n");
254 		}
255 		cgroup_file_notify(&pids->events_file);
256 	}
257 	return err;
258 }
259 
260 static void pids_cancel_fork(struct task_struct *task, struct css_set *cset)
261 {
262 	struct cgroup_subsys_state *css;
263 	struct pids_cgroup *pids;
264 
265 	if (cset)
266 		css = cset->subsys[pids_cgrp_id];
267 	else
268 		css = task_css_check(current, pids_cgrp_id, true);
269 	pids = css_pids(css);
270 	pids_uncharge(pids, 1);
271 }
272 
273 static void pids_release(struct task_struct *task)
274 {
275 	struct pids_cgroup *pids = css_pids(task_css(task, pids_cgrp_id));
276 
277 	pids_uncharge(pids, 1);
278 }
279 
280 static ssize_t pids_max_write(struct kernfs_open_file *of, char *buf,
281 			      size_t nbytes, loff_t off)
282 {
283 	struct cgroup_subsys_state *css = of_css(of);
284 	struct pids_cgroup *pids = css_pids(css);
285 	int64_t limit;
286 	int err;
287 
288 	buf = strstrip(buf);
289 	if (!strcmp(buf, PIDS_MAX_STR)) {
290 		limit = PIDS_MAX;
291 		goto set_limit;
292 	}
293 
294 	err = kstrtoll(buf, 0, &limit);
295 	if (err)
296 		return err;
297 
298 	if (limit < 0 || limit >= PIDS_MAX)
299 		return -EINVAL;
300 
301 set_limit:
302 	/*
303 	 * Limit updates don't need to be mutex'd, since it isn't
304 	 * critical that any racing fork()s follow the new limit.
305 	 */
306 	atomic64_set(&pids->limit, limit);
307 	return nbytes;
308 }
309 
310 static int pids_max_show(struct seq_file *sf, void *v)
311 {
312 	struct cgroup_subsys_state *css = seq_css(sf);
313 	struct pids_cgroup *pids = css_pids(css);
314 	int64_t limit = atomic64_read(&pids->limit);
315 
316 	if (limit >= PIDS_MAX)
317 		seq_printf(sf, "%s\n", PIDS_MAX_STR);
318 	else
319 		seq_printf(sf, "%lld\n", limit);
320 
321 	return 0;
322 }
323 
324 static s64 pids_current_read(struct cgroup_subsys_state *css,
325 			     struct cftype *cft)
326 {
327 	struct pids_cgroup *pids = css_pids(css);
328 
329 	return atomic64_read(&pids->counter);
330 }
331 
332 static s64 pids_peak_read(struct cgroup_subsys_state *css,
333 			  struct cftype *cft)
334 {
335 	struct pids_cgroup *pids = css_pids(css);
336 
337 	return READ_ONCE(pids->watermark);
338 }
339 
340 static int pids_events_show(struct seq_file *sf, void *v)
341 {
342 	struct pids_cgroup *pids = css_pids(seq_css(sf));
343 
344 	seq_printf(sf, "max %lld\n", (s64)atomic64_read(&pids->events_limit));
345 	return 0;
346 }
347 
348 static struct cftype pids_files[] = {
349 	{
350 		.name = "max",
351 		.write = pids_max_write,
352 		.seq_show = pids_max_show,
353 		.flags = CFTYPE_NOT_ON_ROOT,
354 	},
355 	{
356 		.name = "current",
357 		.read_s64 = pids_current_read,
358 		.flags = CFTYPE_NOT_ON_ROOT,
359 	},
360 	{
361 		.name = "peak",
362 		.flags = CFTYPE_NOT_ON_ROOT,
363 		.read_s64 = pids_peak_read,
364 	},
365 	{
366 		.name = "events",
367 		.seq_show = pids_events_show,
368 		.file_offset = offsetof(struct pids_cgroup, events_file),
369 		.flags = CFTYPE_NOT_ON_ROOT,
370 	},
371 	{ }	/* terminate */
372 };
373 
374 struct cgroup_subsys pids_cgrp_subsys = {
375 	.css_alloc	= pids_css_alloc,
376 	.css_free	= pids_css_free,
377 	.can_attach 	= pids_can_attach,
378 	.cancel_attach 	= pids_cancel_attach,
379 	.can_fork	= pids_can_fork,
380 	.cancel_fork	= pids_cancel_fork,
381 	.release	= pids_release,
382 	.legacy_cftypes	= pids_files,
383 	.dfl_cftypes	= pids_files,
384 	.threaded	= true,
385 };
386