xref: /openbmc/linux/kernel/bpf/cgroup.c (revision c0e19f2c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Functions to manage eBPF programs attached to cgroups
4  *
5  * Copyright (c) 2016 Daniel Mack
6  */
7 
8 #include <linux/kernel.h>
9 #include <linux/atomic.h>
10 #include <linux/cgroup.h>
11 #include <linux/filter.h>
12 #include <linux/slab.h>
13 #include <linux/sysctl.h>
14 #include <linux/string.h>
15 #include <linux/bpf.h>
16 #include <linux/bpf-cgroup.h>
17 #include <linux/bpf_lsm.h>
18 #include <linux/bpf_verifier.h>
19 #include <net/sock.h>
20 #include <net/bpf_sk_storage.h>
21 
22 #include "../cgroup/cgroup-internal.h"
23 
24 DEFINE_STATIC_KEY_ARRAY_FALSE(cgroup_bpf_enabled_key, MAX_CGROUP_BPF_ATTACH_TYPE);
25 EXPORT_SYMBOL(cgroup_bpf_enabled_key);
26 
27 /* __always_inline is necessary to prevent indirect call through run_prog
28  * function pointer.
29  */
30 static __always_inline int
31 bpf_prog_run_array_cg(const struct cgroup_bpf *cgrp,
32 		      enum cgroup_bpf_attach_type atype,
33 		      const void *ctx, bpf_prog_run_fn run_prog,
34 		      int retval, u32 *ret_flags)
35 {
36 	const struct bpf_prog_array_item *item;
37 	const struct bpf_prog *prog;
38 	const struct bpf_prog_array *array;
39 	struct bpf_run_ctx *old_run_ctx;
40 	struct bpf_cg_run_ctx run_ctx;
41 	u32 func_ret;
42 
43 	run_ctx.retval = retval;
44 	migrate_disable();
45 	rcu_read_lock();
46 	array = rcu_dereference(cgrp->effective[atype]);
47 	item = &array->items[0];
48 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
49 	while ((prog = READ_ONCE(item->prog))) {
50 		run_ctx.prog_item = item;
51 		func_ret = run_prog(prog, ctx);
52 		if (ret_flags) {
53 			*(ret_flags) |= (func_ret >> 1);
54 			func_ret &= 1;
55 		}
56 		if (!func_ret && !IS_ERR_VALUE((long)run_ctx.retval))
57 			run_ctx.retval = -EPERM;
58 		item++;
59 	}
60 	bpf_reset_run_ctx(old_run_ctx);
61 	rcu_read_unlock();
62 	migrate_enable();
63 	return run_ctx.retval;
64 }
65 
66 unsigned int __cgroup_bpf_run_lsm_sock(const void *ctx,
67 				       const struct bpf_insn *insn)
68 {
69 	const struct bpf_prog *shim_prog;
70 	struct sock *sk;
71 	struct cgroup *cgrp;
72 	int ret = 0;
73 	u64 *args;
74 
75 	args = (u64 *)ctx;
76 	sk = (void *)(unsigned long)args[0];
77 	/*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
78 	shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
79 
80 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
81 	if (likely(cgrp))
82 		ret = bpf_prog_run_array_cg(&cgrp->bpf,
83 					    shim_prog->aux->cgroup_atype,
84 					    ctx, bpf_prog_run, 0, NULL);
85 	return ret;
86 }
87 
88 unsigned int __cgroup_bpf_run_lsm_socket(const void *ctx,
89 					 const struct bpf_insn *insn)
90 {
91 	const struct bpf_prog *shim_prog;
92 	struct socket *sock;
93 	struct cgroup *cgrp;
94 	int ret = 0;
95 	u64 *args;
96 
97 	args = (u64 *)ctx;
98 	sock = (void *)(unsigned long)args[0];
99 	/*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
100 	shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
101 
102 	cgrp = sock_cgroup_ptr(&sock->sk->sk_cgrp_data);
103 	if (likely(cgrp))
104 		ret = bpf_prog_run_array_cg(&cgrp->bpf,
105 					    shim_prog->aux->cgroup_atype,
106 					    ctx, bpf_prog_run, 0, NULL);
107 	return ret;
108 }
109 
110 unsigned int __cgroup_bpf_run_lsm_current(const void *ctx,
111 					  const struct bpf_insn *insn)
112 {
113 	const struct bpf_prog *shim_prog;
114 	struct cgroup *cgrp;
115 	int ret = 0;
116 
117 	/*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
118 	shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
119 
120 	/* We rely on trampoline's __bpf_prog_enter_lsm_cgroup to grab RCU read lock. */
121 	cgrp = task_dfl_cgroup(current);
122 	if (likely(cgrp))
123 		ret = bpf_prog_run_array_cg(&cgrp->bpf,
124 					    shim_prog->aux->cgroup_atype,
125 					    ctx, bpf_prog_run, 0, NULL);
126 	return ret;
127 }
128 
129 #ifdef CONFIG_BPF_LSM
130 struct cgroup_lsm_atype {
131 	u32 attach_btf_id;
132 	int refcnt;
133 };
134 
135 static struct cgroup_lsm_atype cgroup_lsm_atype[CGROUP_LSM_NUM];
136 
137 static enum cgroup_bpf_attach_type
138 bpf_cgroup_atype_find(enum bpf_attach_type attach_type, u32 attach_btf_id)
139 {
140 	int i;
141 
142 	lockdep_assert_held(&cgroup_mutex);
143 
144 	if (attach_type != BPF_LSM_CGROUP)
145 		return to_cgroup_bpf_attach_type(attach_type);
146 
147 	for (i = 0; i < ARRAY_SIZE(cgroup_lsm_atype); i++)
148 		if (cgroup_lsm_atype[i].attach_btf_id == attach_btf_id)
149 			return CGROUP_LSM_START + i;
150 
151 	for (i = 0; i < ARRAY_SIZE(cgroup_lsm_atype); i++)
152 		if (cgroup_lsm_atype[i].attach_btf_id == 0)
153 			return CGROUP_LSM_START + i;
154 
155 	return -E2BIG;
156 
157 }
158 
159 void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype)
160 {
161 	int i = cgroup_atype - CGROUP_LSM_START;
162 
163 	lockdep_assert_held(&cgroup_mutex);
164 
165 	WARN_ON_ONCE(cgroup_lsm_atype[i].attach_btf_id &&
166 		     cgroup_lsm_atype[i].attach_btf_id != attach_btf_id);
167 
168 	cgroup_lsm_atype[i].attach_btf_id = attach_btf_id;
169 	cgroup_lsm_atype[i].refcnt++;
170 }
171 
172 void bpf_cgroup_atype_put(int cgroup_atype)
173 {
174 	int i = cgroup_atype - CGROUP_LSM_START;
175 
176 	mutex_lock(&cgroup_mutex);
177 	if (--cgroup_lsm_atype[i].refcnt <= 0)
178 		cgroup_lsm_atype[i].attach_btf_id = 0;
179 	WARN_ON_ONCE(cgroup_lsm_atype[i].refcnt < 0);
180 	mutex_unlock(&cgroup_mutex);
181 }
182 #else
183 static enum cgroup_bpf_attach_type
184 bpf_cgroup_atype_find(enum bpf_attach_type attach_type, u32 attach_btf_id)
185 {
186 	if (attach_type != BPF_LSM_CGROUP)
187 		return to_cgroup_bpf_attach_type(attach_type);
188 	return -EOPNOTSUPP;
189 }
190 #endif /* CONFIG_BPF_LSM */
191 
192 void cgroup_bpf_offline(struct cgroup *cgrp)
193 {
194 	cgroup_get(cgrp);
195 	percpu_ref_kill(&cgrp->bpf.refcnt);
196 }
197 
198 static void bpf_cgroup_storages_free(struct bpf_cgroup_storage *storages[])
199 {
200 	enum bpf_cgroup_storage_type stype;
201 
202 	for_each_cgroup_storage_type(stype)
203 		bpf_cgroup_storage_free(storages[stype]);
204 }
205 
206 static int bpf_cgroup_storages_alloc(struct bpf_cgroup_storage *storages[],
207 				     struct bpf_cgroup_storage *new_storages[],
208 				     enum bpf_attach_type type,
209 				     struct bpf_prog *prog,
210 				     struct cgroup *cgrp)
211 {
212 	enum bpf_cgroup_storage_type stype;
213 	struct bpf_cgroup_storage_key key;
214 	struct bpf_map *map;
215 
216 	key.cgroup_inode_id = cgroup_id(cgrp);
217 	key.attach_type = type;
218 
219 	for_each_cgroup_storage_type(stype) {
220 		map = prog->aux->cgroup_storage[stype];
221 		if (!map)
222 			continue;
223 
224 		storages[stype] = cgroup_storage_lookup((void *)map, &key, false);
225 		if (storages[stype])
226 			continue;
227 
228 		storages[stype] = bpf_cgroup_storage_alloc(prog, stype);
229 		if (IS_ERR(storages[stype])) {
230 			bpf_cgroup_storages_free(new_storages);
231 			return -ENOMEM;
232 		}
233 
234 		new_storages[stype] = storages[stype];
235 	}
236 
237 	return 0;
238 }
239 
240 static void bpf_cgroup_storages_assign(struct bpf_cgroup_storage *dst[],
241 				       struct bpf_cgroup_storage *src[])
242 {
243 	enum bpf_cgroup_storage_type stype;
244 
245 	for_each_cgroup_storage_type(stype)
246 		dst[stype] = src[stype];
247 }
248 
249 static void bpf_cgroup_storages_link(struct bpf_cgroup_storage *storages[],
250 				     struct cgroup *cgrp,
251 				     enum bpf_attach_type attach_type)
252 {
253 	enum bpf_cgroup_storage_type stype;
254 
255 	for_each_cgroup_storage_type(stype)
256 		bpf_cgroup_storage_link(storages[stype], cgrp, attach_type);
257 }
258 
259 /* Called when bpf_cgroup_link is auto-detached from dying cgroup.
260  * It drops cgroup and bpf_prog refcounts, and marks bpf_link as defunct. It
261  * doesn't free link memory, which will eventually be done by bpf_link's
262  * release() callback, when its last FD is closed.
263  */
264 static void bpf_cgroup_link_auto_detach(struct bpf_cgroup_link *link)
265 {
266 	cgroup_put(link->cgroup);
267 	link->cgroup = NULL;
268 }
269 
270 /**
271  * cgroup_bpf_release() - put references of all bpf programs and
272  *                        release all cgroup bpf data
273  * @work: work structure embedded into the cgroup to modify
274  */
275 static void cgroup_bpf_release(struct work_struct *work)
276 {
277 	struct cgroup *p, *cgrp = container_of(work, struct cgroup,
278 					       bpf.release_work);
279 	struct bpf_prog_array *old_array;
280 	struct list_head *storages = &cgrp->bpf.storages;
281 	struct bpf_cgroup_storage *storage, *stmp;
282 
283 	unsigned int atype;
284 
285 	mutex_lock(&cgroup_mutex);
286 
287 	for (atype = 0; atype < ARRAY_SIZE(cgrp->bpf.progs); atype++) {
288 		struct hlist_head *progs = &cgrp->bpf.progs[atype];
289 		struct bpf_prog_list *pl;
290 		struct hlist_node *pltmp;
291 
292 		hlist_for_each_entry_safe(pl, pltmp, progs, node) {
293 			hlist_del(&pl->node);
294 			if (pl->prog) {
295 				if (pl->prog->expected_attach_type == BPF_LSM_CGROUP)
296 					bpf_trampoline_unlink_cgroup_shim(pl->prog);
297 				bpf_prog_put(pl->prog);
298 			}
299 			if (pl->link) {
300 				if (pl->link->link.prog->expected_attach_type == BPF_LSM_CGROUP)
301 					bpf_trampoline_unlink_cgroup_shim(pl->link->link.prog);
302 				bpf_cgroup_link_auto_detach(pl->link);
303 			}
304 			kfree(pl);
305 			static_branch_dec(&cgroup_bpf_enabled_key[atype]);
306 		}
307 		old_array = rcu_dereference_protected(
308 				cgrp->bpf.effective[atype],
309 				lockdep_is_held(&cgroup_mutex));
310 		bpf_prog_array_free(old_array);
311 	}
312 
313 	list_for_each_entry_safe(storage, stmp, storages, list_cg) {
314 		bpf_cgroup_storage_unlink(storage);
315 		bpf_cgroup_storage_free(storage);
316 	}
317 
318 	mutex_unlock(&cgroup_mutex);
319 
320 	for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
321 		cgroup_bpf_put(p);
322 
323 	percpu_ref_exit(&cgrp->bpf.refcnt);
324 	cgroup_put(cgrp);
325 }
326 
327 /**
328  * cgroup_bpf_release_fn() - callback used to schedule releasing
329  *                           of bpf cgroup data
330  * @ref: percpu ref counter structure
331  */
332 static void cgroup_bpf_release_fn(struct percpu_ref *ref)
333 {
334 	struct cgroup *cgrp = container_of(ref, struct cgroup, bpf.refcnt);
335 
336 	INIT_WORK(&cgrp->bpf.release_work, cgroup_bpf_release);
337 	queue_work(system_wq, &cgrp->bpf.release_work);
338 }
339 
340 /* Get underlying bpf_prog of bpf_prog_list entry, regardless if it's through
341  * link or direct prog.
342  */
343 static struct bpf_prog *prog_list_prog(struct bpf_prog_list *pl)
344 {
345 	if (pl->prog)
346 		return pl->prog;
347 	if (pl->link)
348 		return pl->link->link.prog;
349 	return NULL;
350 }
351 
352 /* count number of elements in the list.
353  * it's slow but the list cannot be long
354  */
355 static u32 prog_list_length(struct hlist_head *head)
356 {
357 	struct bpf_prog_list *pl;
358 	u32 cnt = 0;
359 
360 	hlist_for_each_entry(pl, head, node) {
361 		if (!prog_list_prog(pl))
362 			continue;
363 		cnt++;
364 	}
365 	return cnt;
366 }
367 
368 /* if parent has non-overridable prog attached,
369  * disallow attaching new programs to the descendent cgroup.
370  * if parent has overridable or multi-prog, allow attaching
371  */
372 static bool hierarchy_allows_attach(struct cgroup *cgrp,
373 				    enum cgroup_bpf_attach_type atype)
374 {
375 	struct cgroup *p;
376 
377 	p = cgroup_parent(cgrp);
378 	if (!p)
379 		return true;
380 	do {
381 		u32 flags = p->bpf.flags[atype];
382 		u32 cnt;
383 
384 		if (flags & BPF_F_ALLOW_MULTI)
385 			return true;
386 		cnt = prog_list_length(&p->bpf.progs[atype]);
387 		WARN_ON_ONCE(cnt > 1);
388 		if (cnt == 1)
389 			return !!(flags & BPF_F_ALLOW_OVERRIDE);
390 		p = cgroup_parent(p);
391 	} while (p);
392 	return true;
393 }
394 
395 /* compute a chain of effective programs for a given cgroup:
396  * start from the list of programs in this cgroup and add
397  * all parent programs.
398  * Note that parent's F_ALLOW_OVERRIDE-type program is yielding
399  * to programs in this cgroup
400  */
401 static int compute_effective_progs(struct cgroup *cgrp,
402 				   enum cgroup_bpf_attach_type atype,
403 				   struct bpf_prog_array **array)
404 {
405 	struct bpf_prog_array_item *item;
406 	struct bpf_prog_array *progs;
407 	struct bpf_prog_list *pl;
408 	struct cgroup *p = cgrp;
409 	int cnt = 0;
410 
411 	/* count number of effective programs by walking parents */
412 	do {
413 		if (cnt == 0 || (p->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
414 			cnt += prog_list_length(&p->bpf.progs[atype]);
415 		p = cgroup_parent(p);
416 	} while (p);
417 
418 	progs = bpf_prog_array_alloc(cnt, GFP_KERNEL);
419 	if (!progs)
420 		return -ENOMEM;
421 
422 	/* populate the array with effective progs */
423 	cnt = 0;
424 	p = cgrp;
425 	do {
426 		if (cnt > 0 && !(p->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
427 			continue;
428 
429 		hlist_for_each_entry(pl, &p->bpf.progs[atype], node) {
430 			if (!prog_list_prog(pl))
431 				continue;
432 
433 			item = &progs->items[cnt];
434 			item->prog = prog_list_prog(pl);
435 			bpf_cgroup_storages_assign(item->cgroup_storage,
436 						   pl->storage);
437 			cnt++;
438 		}
439 	} while ((p = cgroup_parent(p)));
440 
441 	*array = progs;
442 	return 0;
443 }
444 
445 static void activate_effective_progs(struct cgroup *cgrp,
446 				     enum cgroup_bpf_attach_type atype,
447 				     struct bpf_prog_array *old_array)
448 {
449 	old_array = rcu_replace_pointer(cgrp->bpf.effective[atype], old_array,
450 					lockdep_is_held(&cgroup_mutex));
451 	/* free prog array after grace period, since __cgroup_bpf_run_*()
452 	 * might be still walking the array
453 	 */
454 	bpf_prog_array_free(old_array);
455 }
456 
457 /**
458  * cgroup_bpf_inherit() - inherit effective programs from parent
459  * @cgrp: the cgroup to modify
460  */
461 int cgroup_bpf_inherit(struct cgroup *cgrp)
462 {
463 /* has to use marco instead of const int, since compiler thinks
464  * that array below is variable length
465  */
466 #define	NR ARRAY_SIZE(cgrp->bpf.effective)
467 	struct bpf_prog_array *arrays[NR] = {};
468 	struct cgroup *p;
469 	int ret, i;
470 
471 	ret = percpu_ref_init(&cgrp->bpf.refcnt, cgroup_bpf_release_fn, 0,
472 			      GFP_KERNEL);
473 	if (ret)
474 		return ret;
475 
476 	for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
477 		cgroup_bpf_get(p);
478 
479 	for (i = 0; i < NR; i++)
480 		INIT_HLIST_HEAD(&cgrp->bpf.progs[i]);
481 
482 	INIT_LIST_HEAD(&cgrp->bpf.storages);
483 
484 	for (i = 0; i < NR; i++)
485 		if (compute_effective_progs(cgrp, i, &arrays[i]))
486 			goto cleanup;
487 
488 	for (i = 0; i < NR; i++)
489 		activate_effective_progs(cgrp, i, arrays[i]);
490 
491 	return 0;
492 cleanup:
493 	for (i = 0; i < NR; i++)
494 		bpf_prog_array_free(arrays[i]);
495 
496 	for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
497 		cgroup_bpf_put(p);
498 
499 	percpu_ref_exit(&cgrp->bpf.refcnt);
500 
501 	return -ENOMEM;
502 }
503 
504 static int update_effective_progs(struct cgroup *cgrp,
505 				  enum cgroup_bpf_attach_type atype)
506 {
507 	struct cgroup_subsys_state *css;
508 	int err;
509 
510 	/* allocate and recompute effective prog arrays */
511 	css_for_each_descendant_pre(css, &cgrp->self) {
512 		struct cgroup *desc = container_of(css, struct cgroup, self);
513 
514 		if (percpu_ref_is_zero(&desc->bpf.refcnt))
515 			continue;
516 
517 		err = compute_effective_progs(desc, atype, &desc->bpf.inactive);
518 		if (err)
519 			goto cleanup;
520 	}
521 
522 	/* all allocations were successful. Activate all prog arrays */
523 	css_for_each_descendant_pre(css, &cgrp->self) {
524 		struct cgroup *desc = container_of(css, struct cgroup, self);
525 
526 		if (percpu_ref_is_zero(&desc->bpf.refcnt)) {
527 			if (unlikely(desc->bpf.inactive)) {
528 				bpf_prog_array_free(desc->bpf.inactive);
529 				desc->bpf.inactive = NULL;
530 			}
531 			continue;
532 		}
533 
534 		activate_effective_progs(desc, atype, desc->bpf.inactive);
535 		desc->bpf.inactive = NULL;
536 	}
537 
538 	return 0;
539 
540 cleanup:
541 	/* oom while computing effective. Free all computed effective arrays
542 	 * since they were not activated
543 	 */
544 	css_for_each_descendant_pre(css, &cgrp->self) {
545 		struct cgroup *desc = container_of(css, struct cgroup, self);
546 
547 		bpf_prog_array_free(desc->bpf.inactive);
548 		desc->bpf.inactive = NULL;
549 	}
550 
551 	return err;
552 }
553 
554 #define BPF_CGROUP_MAX_PROGS 64
555 
556 static struct bpf_prog_list *find_attach_entry(struct hlist_head *progs,
557 					       struct bpf_prog *prog,
558 					       struct bpf_cgroup_link *link,
559 					       struct bpf_prog *replace_prog,
560 					       bool allow_multi)
561 {
562 	struct bpf_prog_list *pl;
563 
564 	/* single-attach case */
565 	if (!allow_multi) {
566 		if (hlist_empty(progs))
567 			return NULL;
568 		return hlist_entry(progs->first, typeof(*pl), node);
569 	}
570 
571 	hlist_for_each_entry(pl, progs, node) {
572 		if (prog && pl->prog == prog && prog != replace_prog)
573 			/* disallow attaching the same prog twice */
574 			return ERR_PTR(-EINVAL);
575 		if (link && pl->link == link)
576 			/* disallow attaching the same link twice */
577 			return ERR_PTR(-EINVAL);
578 	}
579 
580 	/* direct prog multi-attach w/ replacement case */
581 	if (replace_prog) {
582 		hlist_for_each_entry(pl, progs, node) {
583 			if (pl->prog == replace_prog)
584 				/* a match found */
585 				return pl;
586 		}
587 		/* prog to replace not found for cgroup */
588 		return ERR_PTR(-ENOENT);
589 	}
590 
591 	return NULL;
592 }
593 
594 /**
595  * __cgroup_bpf_attach() - Attach the program or the link to a cgroup, and
596  *                         propagate the change to descendants
597  * @cgrp: The cgroup which descendants to traverse
598  * @prog: A program to attach
599  * @link: A link to attach
600  * @replace_prog: Previously attached program to replace if BPF_F_REPLACE is set
601  * @type: Type of attach operation
602  * @flags: Option flags
603  *
604  * Exactly one of @prog or @link can be non-null.
605  * Must be called with cgroup_mutex held.
606  */
607 static int __cgroup_bpf_attach(struct cgroup *cgrp,
608 			       struct bpf_prog *prog, struct bpf_prog *replace_prog,
609 			       struct bpf_cgroup_link *link,
610 			       enum bpf_attach_type type, u32 flags)
611 {
612 	u32 saved_flags = (flags & (BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI));
613 	struct bpf_prog *old_prog = NULL;
614 	struct bpf_cgroup_storage *storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {};
615 	struct bpf_cgroup_storage *new_storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {};
616 	struct bpf_prog *new_prog = prog ? : link->link.prog;
617 	enum cgroup_bpf_attach_type atype;
618 	struct bpf_prog_list *pl;
619 	struct hlist_head *progs;
620 	int err;
621 
622 	if (((flags & BPF_F_ALLOW_OVERRIDE) && (flags & BPF_F_ALLOW_MULTI)) ||
623 	    ((flags & BPF_F_REPLACE) && !(flags & BPF_F_ALLOW_MULTI)))
624 		/* invalid combination */
625 		return -EINVAL;
626 	if (link && (prog || replace_prog))
627 		/* only either link or prog/replace_prog can be specified */
628 		return -EINVAL;
629 	if (!!replace_prog != !!(flags & BPF_F_REPLACE))
630 		/* replace_prog implies BPF_F_REPLACE, and vice versa */
631 		return -EINVAL;
632 
633 	atype = bpf_cgroup_atype_find(type, new_prog->aux->attach_btf_id);
634 	if (atype < 0)
635 		return -EINVAL;
636 
637 	progs = &cgrp->bpf.progs[atype];
638 
639 	if (!hierarchy_allows_attach(cgrp, atype))
640 		return -EPERM;
641 
642 	if (!hlist_empty(progs) && cgrp->bpf.flags[atype] != saved_flags)
643 		/* Disallow attaching non-overridable on top
644 		 * of existing overridable in this cgroup.
645 		 * Disallow attaching multi-prog if overridable or none
646 		 */
647 		return -EPERM;
648 
649 	if (prog_list_length(progs) >= BPF_CGROUP_MAX_PROGS)
650 		return -E2BIG;
651 
652 	pl = find_attach_entry(progs, prog, link, replace_prog,
653 			       flags & BPF_F_ALLOW_MULTI);
654 	if (IS_ERR(pl))
655 		return PTR_ERR(pl);
656 
657 	if (bpf_cgroup_storages_alloc(storage, new_storage, type,
658 				      prog ? : link->link.prog, cgrp))
659 		return -ENOMEM;
660 
661 	if (pl) {
662 		old_prog = pl->prog;
663 	} else {
664 		struct hlist_node *last = NULL;
665 
666 		pl = kmalloc(sizeof(*pl), GFP_KERNEL);
667 		if (!pl) {
668 			bpf_cgroup_storages_free(new_storage);
669 			return -ENOMEM;
670 		}
671 		if (hlist_empty(progs))
672 			hlist_add_head(&pl->node, progs);
673 		else
674 			hlist_for_each(last, progs) {
675 				if (last->next)
676 					continue;
677 				hlist_add_behind(&pl->node, last);
678 				break;
679 			}
680 	}
681 
682 	pl->prog = prog;
683 	pl->link = link;
684 	bpf_cgroup_storages_assign(pl->storage, storage);
685 	cgrp->bpf.flags[atype] = saved_flags;
686 
687 	if (type == BPF_LSM_CGROUP) {
688 		err = bpf_trampoline_link_cgroup_shim(new_prog, atype);
689 		if (err)
690 			goto cleanup;
691 	}
692 
693 	err = update_effective_progs(cgrp, atype);
694 	if (err)
695 		goto cleanup_trampoline;
696 
697 	if (old_prog) {
698 		if (type == BPF_LSM_CGROUP)
699 			bpf_trampoline_unlink_cgroup_shim(old_prog);
700 		bpf_prog_put(old_prog);
701 	} else {
702 		static_branch_inc(&cgroup_bpf_enabled_key[atype]);
703 	}
704 	bpf_cgroup_storages_link(new_storage, cgrp, type);
705 	return 0;
706 
707 cleanup_trampoline:
708 	if (type == BPF_LSM_CGROUP)
709 		bpf_trampoline_unlink_cgroup_shim(new_prog);
710 
711 cleanup:
712 	if (old_prog) {
713 		pl->prog = old_prog;
714 		pl->link = NULL;
715 	}
716 	bpf_cgroup_storages_free(new_storage);
717 	if (!old_prog) {
718 		hlist_del(&pl->node);
719 		kfree(pl);
720 	}
721 	return err;
722 }
723 
724 static int cgroup_bpf_attach(struct cgroup *cgrp,
725 			     struct bpf_prog *prog, struct bpf_prog *replace_prog,
726 			     struct bpf_cgroup_link *link,
727 			     enum bpf_attach_type type,
728 			     u32 flags)
729 {
730 	int ret;
731 
732 	mutex_lock(&cgroup_mutex);
733 	ret = __cgroup_bpf_attach(cgrp, prog, replace_prog, link, type, flags);
734 	mutex_unlock(&cgroup_mutex);
735 	return ret;
736 }
737 
738 /* Swap updated BPF program for given link in effective program arrays across
739  * all descendant cgroups. This function is guaranteed to succeed.
740  */
741 static void replace_effective_prog(struct cgroup *cgrp,
742 				   enum cgroup_bpf_attach_type atype,
743 				   struct bpf_cgroup_link *link)
744 {
745 	struct bpf_prog_array_item *item;
746 	struct cgroup_subsys_state *css;
747 	struct bpf_prog_array *progs;
748 	struct bpf_prog_list *pl;
749 	struct hlist_head *head;
750 	struct cgroup *cg;
751 	int pos;
752 
753 	css_for_each_descendant_pre(css, &cgrp->self) {
754 		struct cgroup *desc = container_of(css, struct cgroup, self);
755 
756 		if (percpu_ref_is_zero(&desc->bpf.refcnt))
757 			continue;
758 
759 		/* find position of link in effective progs array */
760 		for (pos = 0, cg = desc; cg; cg = cgroup_parent(cg)) {
761 			if (pos && !(cg->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
762 				continue;
763 
764 			head = &cg->bpf.progs[atype];
765 			hlist_for_each_entry(pl, head, node) {
766 				if (!prog_list_prog(pl))
767 					continue;
768 				if (pl->link == link)
769 					goto found;
770 				pos++;
771 			}
772 		}
773 found:
774 		BUG_ON(!cg);
775 		progs = rcu_dereference_protected(
776 				desc->bpf.effective[atype],
777 				lockdep_is_held(&cgroup_mutex));
778 		item = &progs->items[pos];
779 		WRITE_ONCE(item->prog, link->link.prog);
780 	}
781 }
782 
783 /**
784  * __cgroup_bpf_replace() - Replace link's program and propagate the change
785  *                          to descendants
786  * @cgrp: The cgroup which descendants to traverse
787  * @link: A link for which to replace BPF program
788  * @type: Type of attach operation
789  *
790  * Must be called with cgroup_mutex held.
791  */
792 static int __cgroup_bpf_replace(struct cgroup *cgrp,
793 				struct bpf_cgroup_link *link,
794 				struct bpf_prog *new_prog)
795 {
796 	enum cgroup_bpf_attach_type atype;
797 	struct bpf_prog *old_prog;
798 	struct bpf_prog_list *pl;
799 	struct hlist_head *progs;
800 	bool found = false;
801 
802 	atype = bpf_cgroup_atype_find(link->type, new_prog->aux->attach_btf_id);
803 	if (atype < 0)
804 		return -EINVAL;
805 
806 	progs = &cgrp->bpf.progs[atype];
807 
808 	if (link->link.prog->type != new_prog->type)
809 		return -EINVAL;
810 
811 	hlist_for_each_entry(pl, progs, node) {
812 		if (pl->link == link) {
813 			found = true;
814 			break;
815 		}
816 	}
817 	if (!found)
818 		return -ENOENT;
819 
820 	old_prog = xchg(&link->link.prog, new_prog);
821 	replace_effective_prog(cgrp, atype, link);
822 	bpf_prog_put(old_prog);
823 	return 0;
824 }
825 
826 static int cgroup_bpf_replace(struct bpf_link *link, struct bpf_prog *new_prog,
827 			      struct bpf_prog *old_prog)
828 {
829 	struct bpf_cgroup_link *cg_link;
830 	int ret;
831 
832 	cg_link = container_of(link, struct bpf_cgroup_link, link);
833 
834 	mutex_lock(&cgroup_mutex);
835 	/* link might have been auto-released by dying cgroup, so fail */
836 	if (!cg_link->cgroup) {
837 		ret = -ENOLINK;
838 		goto out_unlock;
839 	}
840 	if (old_prog && link->prog != old_prog) {
841 		ret = -EPERM;
842 		goto out_unlock;
843 	}
844 	ret = __cgroup_bpf_replace(cg_link->cgroup, cg_link, new_prog);
845 out_unlock:
846 	mutex_unlock(&cgroup_mutex);
847 	return ret;
848 }
849 
850 static struct bpf_prog_list *find_detach_entry(struct hlist_head *progs,
851 					       struct bpf_prog *prog,
852 					       struct bpf_cgroup_link *link,
853 					       bool allow_multi)
854 {
855 	struct bpf_prog_list *pl;
856 
857 	if (!allow_multi) {
858 		if (hlist_empty(progs))
859 			/* report error when trying to detach and nothing is attached */
860 			return ERR_PTR(-ENOENT);
861 
862 		/* to maintain backward compatibility NONE and OVERRIDE cgroups
863 		 * allow detaching with invalid FD (prog==NULL) in legacy mode
864 		 */
865 		return hlist_entry(progs->first, typeof(*pl), node);
866 	}
867 
868 	if (!prog && !link)
869 		/* to detach MULTI prog the user has to specify valid FD
870 		 * of the program or link to be detached
871 		 */
872 		return ERR_PTR(-EINVAL);
873 
874 	/* find the prog or link and detach it */
875 	hlist_for_each_entry(pl, progs, node) {
876 		if (pl->prog == prog && pl->link == link)
877 			return pl;
878 	}
879 	return ERR_PTR(-ENOENT);
880 }
881 
882 /**
883  * purge_effective_progs() - After compute_effective_progs fails to alloc new
884  *                           cgrp->bpf.inactive table we can recover by
885  *                           recomputing the array in place.
886  *
887  * @cgrp: The cgroup which descendants to travers
888  * @prog: A program to detach or NULL
889  * @link: A link to detach or NULL
890  * @atype: Type of detach operation
891  */
892 static void purge_effective_progs(struct cgroup *cgrp, struct bpf_prog *prog,
893 				  struct bpf_cgroup_link *link,
894 				  enum cgroup_bpf_attach_type atype)
895 {
896 	struct cgroup_subsys_state *css;
897 	struct bpf_prog_array *progs;
898 	struct bpf_prog_list *pl;
899 	struct hlist_head *head;
900 	struct cgroup *cg;
901 	int pos;
902 
903 	/* recompute effective prog array in place */
904 	css_for_each_descendant_pre(css, &cgrp->self) {
905 		struct cgroup *desc = container_of(css, struct cgroup, self);
906 
907 		if (percpu_ref_is_zero(&desc->bpf.refcnt))
908 			continue;
909 
910 		/* find position of link or prog in effective progs array */
911 		for (pos = 0, cg = desc; cg; cg = cgroup_parent(cg)) {
912 			if (pos && !(cg->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
913 				continue;
914 
915 			head = &cg->bpf.progs[atype];
916 			hlist_for_each_entry(pl, head, node) {
917 				if (!prog_list_prog(pl))
918 					continue;
919 				if (pl->prog == prog && pl->link == link)
920 					goto found;
921 				pos++;
922 			}
923 		}
924 found:
925 		BUG_ON(!cg);
926 		progs = rcu_dereference_protected(
927 				desc->bpf.effective[atype],
928 				lockdep_is_held(&cgroup_mutex));
929 
930 		/* Remove the program from the array */
931 		WARN_ONCE(bpf_prog_array_delete_safe_at(progs, pos),
932 			  "Failed to purge a prog from array at index %d", pos);
933 	}
934 }
935 
936 /**
937  * __cgroup_bpf_detach() - Detach the program or link from a cgroup, and
938  *                         propagate the change to descendants
939  * @cgrp: The cgroup which descendants to traverse
940  * @prog: A program to detach or NULL
941  * @link: A link to detach or NULL
942  * @type: Type of detach operation
943  *
944  * At most one of @prog or @link can be non-NULL.
945  * Must be called with cgroup_mutex held.
946  */
947 static int __cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
948 			       struct bpf_cgroup_link *link, enum bpf_attach_type type)
949 {
950 	enum cgroup_bpf_attach_type atype;
951 	struct bpf_prog *old_prog;
952 	struct bpf_prog_list *pl;
953 	struct hlist_head *progs;
954 	u32 attach_btf_id = 0;
955 	u32 flags;
956 
957 	if (prog)
958 		attach_btf_id = prog->aux->attach_btf_id;
959 	if (link)
960 		attach_btf_id = link->link.prog->aux->attach_btf_id;
961 
962 	atype = bpf_cgroup_atype_find(type, attach_btf_id);
963 	if (atype < 0)
964 		return -EINVAL;
965 
966 	progs = &cgrp->bpf.progs[atype];
967 	flags = cgrp->bpf.flags[atype];
968 
969 	if (prog && link)
970 		/* only one of prog or link can be specified */
971 		return -EINVAL;
972 
973 	pl = find_detach_entry(progs, prog, link, flags & BPF_F_ALLOW_MULTI);
974 	if (IS_ERR(pl))
975 		return PTR_ERR(pl);
976 
977 	/* mark it deleted, so it's ignored while recomputing effective */
978 	old_prog = pl->prog;
979 	pl->prog = NULL;
980 	pl->link = NULL;
981 
982 	if (update_effective_progs(cgrp, atype)) {
983 		/* if update effective array failed replace the prog with a dummy prog*/
984 		pl->prog = old_prog;
985 		pl->link = link;
986 		purge_effective_progs(cgrp, old_prog, link, atype);
987 	}
988 
989 	/* now can actually delete it from this cgroup list */
990 	hlist_del(&pl->node);
991 
992 	kfree(pl);
993 	if (hlist_empty(progs))
994 		/* last program was detached, reset flags to zero */
995 		cgrp->bpf.flags[atype] = 0;
996 	if (old_prog) {
997 		if (type == BPF_LSM_CGROUP)
998 			bpf_trampoline_unlink_cgroup_shim(old_prog);
999 		bpf_prog_put(old_prog);
1000 	}
1001 	static_branch_dec(&cgroup_bpf_enabled_key[atype]);
1002 	return 0;
1003 }
1004 
1005 static int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
1006 			     enum bpf_attach_type type)
1007 {
1008 	int ret;
1009 
1010 	mutex_lock(&cgroup_mutex);
1011 	ret = __cgroup_bpf_detach(cgrp, prog, NULL, type);
1012 	mutex_unlock(&cgroup_mutex);
1013 	return ret;
1014 }
1015 
1016 /* Must be called with cgroup_mutex held to avoid races. */
1017 static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
1018 			      union bpf_attr __user *uattr)
1019 {
1020 	__u32 __user *prog_ids = u64_to_user_ptr(attr->query.prog_ids);
1021 	enum bpf_attach_type type = attr->query.attach_type;
1022 	enum cgroup_bpf_attach_type atype;
1023 	struct bpf_prog_array *effective;
1024 	struct hlist_head *progs;
1025 	struct bpf_prog *prog;
1026 	int cnt, ret = 0, i;
1027 	u32 flags;
1028 
1029 	atype = to_cgroup_bpf_attach_type(type);
1030 	if (atype < 0)
1031 		return -EINVAL;
1032 
1033 	progs = &cgrp->bpf.progs[atype];
1034 	flags = cgrp->bpf.flags[atype];
1035 
1036 	effective = rcu_dereference_protected(cgrp->bpf.effective[atype],
1037 					      lockdep_is_held(&cgroup_mutex));
1038 
1039 	if (attr->query.query_flags & BPF_F_QUERY_EFFECTIVE)
1040 		cnt = bpf_prog_array_length(effective);
1041 	else
1042 		cnt = prog_list_length(progs);
1043 
1044 	if (copy_to_user(&uattr->query.attach_flags, &flags, sizeof(flags)))
1045 		return -EFAULT;
1046 	if (copy_to_user(&uattr->query.prog_cnt, &cnt, sizeof(cnt)))
1047 		return -EFAULT;
1048 	if (attr->query.prog_cnt == 0 || !prog_ids || !cnt)
1049 		/* return early if user requested only program count + flags */
1050 		return 0;
1051 	if (attr->query.prog_cnt < cnt) {
1052 		cnt = attr->query.prog_cnt;
1053 		ret = -ENOSPC;
1054 	}
1055 
1056 	if (attr->query.query_flags & BPF_F_QUERY_EFFECTIVE) {
1057 		return bpf_prog_array_copy_to_user(effective, prog_ids, cnt);
1058 	} else {
1059 		struct bpf_prog_list *pl;
1060 		u32 id;
1061 
1062 		i = 0;
1063 		hlist_for_each_entry(pl, progs, node) {
1064 			prog = prog_list_prog(pl);
1065 			id = prog->aux->id;
1066 			if (copy_to_user(prog_ids + i, &id, sizeof(id)))
1067 				return -EFAULT;
1068 			if (++i == cnt)
1069 				break;
1070 		}
1071 	}
1072 	return ret;
1073 }
1074 
1075 static int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
1076 			    union bpf_attr __user *uattr)
1077 {
1078 	int ret;
1079 
1080 	mutex_lock(&cgroup_mutex);
1081 	ret = __cgroup_bpf_query(cgrp, attr, uattr);
1082 	mutex_unlock(&cgroup_mutex);
1083 	return ret;
1084 }
1085 
1086 int cgroup_bpf_prog_attach(const union bpf_attr *attr,
1087 			   enum bpf_prog_type ptype, struct bpf_prog *prog)
1088 {
1089 	struct bpf_prog *replace_prog = NULL;
1090 	struct cgroup *cgrp;
1091 	int ret;
1092 
1093 	cgrp = cgroup_get_from_fd(attr->target_fd);
1094 	if (IS_ERR(cgrp))
1095 		return PTR_ERR(cgrp);
1096 
1097 	if ((attr->attach_flags & BPF_F_ALLOW_MULTI) &&
1098 	    (attr->attach_flags & BPF_F_REPLACE)) {
1099 		replace_prog = bpf_prog_get_type(attr->replace_bpf_fd, ptype);
1100 		if (IS_ERR(replace_prog)) {
1101 			cgroup_put(cgrp);
1102 			return PTR_ERR(replace_prog);
1103 		}
1104 	}
1105 
1106 	ret = cgroup_bpf_attach(cgrp, prog, replace_prog, NULL,
1107 				attr->attach_type, attr->attach_flags);
1108 
1109 	if (replace_prog)
1110 		bpf_prog_put(replace_prog);
1111 	cgroup_put(cgrp);
1112 	return ret;
1113 }
1114 
1115 int cgroup_bpf_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)
1116 {
1117 	struct bpf_prog *prog;
1118 	struct cgroup *cgrp;
1119 	int ret;
1120 
1121 	cgrp = cgroup_get_from_fd(attr->target_fd);
1122 	if (IS_ERR(cgrp))
1123 		return PTR_ERR(cgrp);
1124 
1125 	prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
1126 	if (IS_ERR(prog))
1127 		prog = NULL;
1128 
1129 	ret = cgroup_bpf_detach(cgrp, prog, attr->attach_type);
1130 	if (prog)
1131 		bpf_prog_put(prog);
1132 
1133 	cgroup_put(cgrp);
1134 	return ret;
1135 }
1136 
1137 static void bpf_cgroup_link_release(struct bpf_link *link)
1138 {
1139 	struct bpf_cgroup_link *cg_link =
1140 		container_of(link, struct bpf_cgroup_link, link);
1141 	struct cgroup *cg;
1142 
1143 	/* link might have been auto-detached by dying cgroup already,
1144 	 * in that case our work is done here
1145 	 */
1146 	if (!cg_link->cgroup)
1147 		return;
1148 
1149 	mutex_lock(&cgroup_mutex);
1150 
1151 	/* re-check cgroup under lock again */
1152 	if (!cg_link->cgroup) {
1153 		mutex_unlock(&cgroup_mutex);
1154 		return;
1155 	}
1156 
1157 	WARN_ON(__cgroup_bpf_detach(cg_link->cgroup, NULL, cg_link,
1158 				    cg_link->type));
1159 	if (cg_link->type == BPF_LSM_CGROUP)
1160 		bpf_trampoline_unlink_cgroup_shim(cg_link->link.prog);
1161 
1162 	cg = cg_link->cgroup;
1163 	cg_link->cgroup = NULL;
1164 
1165 	mutex_unlock(&cgroup_mutex);
1166 
1167 	cgroup_put(cg);
1168 }
1169 
1170 static void bpf_cgroup_link_dealloc(struct bpf_link *link)
1171 {
1172 	struct bpf_cgroup_link *cg_link =
1173 		container_of(link, struct bpf_cgroup_link, link);
1174 
1175 	kfree(cg_link);
1176 }
1177 
1178 static int bpf_cgroup_link_detach(struct bpf_link *link)
1179 {
1180 	bpf_cgroup_link_release(link);
1181 
1182 	return 0;
1183 }
1184 
1185 static void bpf_cgroup_link_show_fdinfo(const struct bpf_link *link,
1186 					struct seq_file *seq)
1187 {
1188 	struct bpf_cgroup_link *cg_link =
1189 		container_of(link, struct bpf_cgroup_link, link);
1190 	u64 cg_id = 0;
1191 
1192 	mutex_lock(&cgroup_mutex);
1193 	if (cg_link->cgroup)
1194 		cg_id = cgroup_id(cg_link->cgroup);
1195 	mutex_unlock(&cgroup_mutex);
1196 
1197 	seq_printf(seq,
1198 		   "cgroup_id:\t%llu\n"
1199 		   "attach_type:\t%d\n",
1200 		   cg_id,
1201 		   cg_link->type);
1202 }
1203 
1204 static int bpf_cgroup_link_fill_link_info(const struct bpf_link *link,
1205 					  struct bpf_link_info *info)
1206 {
1207 	struct bpf_cgroup_link *cg_link =
1208 		container_of(link, struct bpf_cgroup_link, link);
1209 	u64 cg_id = 0;
1210 
1211 	mutex_lock(&cgroup_mutex);
1212 	if (cg_link->cgroup)
1213 		cg_id = cgroup_id(cg_link->cgroup);
1214 	mutex_unlock(&cgroup_mutex);
1215 
1216 	info->cgroup.cgroup_id = cg_id;
1217 	info->cgroup.attach_type = cg_link->type;
1218 	return 0;
1219 }
1220 
1221 static const struct bpf_link_ops bpf_cgroup_link_lops = {
1222 	.release = bpf_cgroup_link_release,
1223 	.dealloc = bpf_cgroup_link_dealloc,
1224 	.detach = bpf_cgroup_link_detach,
1225 	.update_prog = cgroup_bpf_replace,
1226 	.show_fdinfo = bpf_cgroup_link_show_fdinfo,
1227 	.fill_link_info = bpf_cgroup_link_fill_link_info,
1228 };
1229 
1230 int cgroup_bpf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
1231 {
1232 	struct bpf_link_primer link_primer;
1233 	struct bpf_cgroup_link *link;
1234 	struct cgroup *cgrp;
1235 	int err;
1236 
1237 	if (attr->link_create.flags)
1238 		return -EINVAL;
1239 
1240 	cgrp = cgroup_get_from_fd(attr->link_create.target_fd);
1241 	if (IS_ERR(cgrp))
1242 		return PTR_ERR(cgrp);
1243 
1244 	link = kzalloc(sizeof(*link), GFP_USER);
1245 	if (!link) {
1246 		err = -ENOMEM;
1247 		goto out_put_cgroup;
1248 	}
1249 	bpf_link_init(&link->link, BPF_LINK_TYPE_CGROUP, &bpf_cgroup_link_lops,
1250 		      prog);
1251 	link->cgroup = cgrp;
1252 	link->type = attr->link_create.attach_type;
1253 
1254 	err = bpf_link_prime(&link->link, &link_primer);
1255 	if (err) {
1256 		kfree(link);
1257 		goto out_put_cgroup;
1258 	}
1259 
1260 	err = cgroup_bpf_attach(cgrp, NULL, NULL, link,
1261 				link->type, BPF_F_ALLOW_MULTI);
1262 	if (err) {
1263 		bpf_link_cleanup(&link_primer);
1264 		goto out_put_cgroup;
1265 	}
1266 
1267 	return bpf_link_settle(&link_primer);
1268 
1269 out_put_cgroup:
1270 	cgroup_put(cgrp);
1271 	return err;
1272 }
1273 
1274 int cgroup_bpf_prog_query(const union bpf_attr *attr,
1275 			  union bpf_attr __user *uattr)
1276 {
1277 	struct cgroup *cgrp;
1278 	int ret;
1279 
1280 	cgrp = cgroup_get_from_fd(attr->query.target_fd);
1281 	if (IS_ERR(cgrp))
1282 		return PTR_ERR(cgrp);
1283 
1284 	ret = cgroup_bpf_query(cgrp, attr, uattr);
1285 
1286 	cgroup_put(cgrp);
1287 	return ret;
1288 }
1289 
1290 /**
1291  * __cgroup_bpf_run_filter_skb() - Run a program for packet filtering
1292  * @sk: The socket sending or receiving traffic
1293  * @skb: The skb that is being sent or received
1294  * @type: The type of program to be executed
1295  *
1296  * If no socket is passed, or the socket is not of type INET or INET6,
1297  * this function does nothing and returns 0.
1298  *
1299  * The program type passed in via @type must be suitable for network
1300  * filtering. No further check is performed to assert that.
1301  *
1302  * For egress packets, this function can return:
1303  *   NET_XMIT_SUCCESS    (0)	- continue with packet output
1304  *   NET_XMIT_DROP       (1)	- drop packet and notify TCP to call cwr
1305  *   NET_XMIT_CN         (2)	- continue with packet output and notify TCP
1306  *				  to call cwr
1307  *   -err			- drop packet
1308  *
1309  * For ingress packets, this function will return -EPERM if any
1310  * attached program was found and if it returned != 1 during execution.
1311  * Otherwise 0 is returned.
1312  */
1313 int __cgroup_bpf_run_filter_skb(struct sock *sk,
1314 				struct sk_buff *skb,
1315 				enum cgroup_bpf_attach_type atype)
1316 {
1317 	unsigned int offset = skb->data - skb_network_header(skb);
1318 	struct sock *save_sk;
1319 	void *saved_data_end;
1320 	struct cgroup *cgrp;
1321 	int ret;
1322 
1323 	if (!sk || !sk_fullsock(sk))
1324 		return 0;
1325 
1326 	if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
1327 		return 0;
1328 
1329 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1330 	save_sk = skb->sk;
1331 	skb->sk = sk;
1332 	__skb_push(skb, offset);
1333 
1334 	/* compute pointers for the bpf prog */
1335 	bpf_compute_and_save_data_end(skb, &saved_data_end);
1336 
1337 	if (atype == CGROUP_INET_EGRESS) {
1338 		u32 flags = 0;
1339 		bool cn;
1340 
1341 		ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, skb,
1342 					    __bpf_prog_run_save_cb, 0, &flags);
1343 
1344 		/* Return values of CGROUP EGRESS BPF programs are:
1345 		 *   0: drop packet
1346 		 *   1: keep packet
1347 		 *   2: drop packet and cn
1348 		 *   3: keep packet and cn
1349 		 *
1350 		 * The returned value is then converted to one of the NET_XMIT
1351 		 * or an error code that is then interpreted as drop packet
1352 		 * (and no cn):
1353 		 *   0: NET_XMIT_SUCCESS  skb should be transmitted
1354 		 *   1: NET_XMIT_DROP     skb should be dropped and cn
1355 		 *   2: NET_XMIT_CN       skb should be transmitted and cn
1356 		 *   3: -err              skb should be dropped
1357 		 */
1358 
1359 		cn = flags & BPF_RET_SET_CN;
1360 		if (ret && !IS_ERR_VALUE((long)ret))
1361 			ret = -EFAULT;
1362 		if (!ret)
1363 			ret = (cn ? NET_XMIT_CN : NET_XMIT_SUCCESS);
1364 		else
1365 			ret = (cn ? NET_XMIT_DROP : ret);
1366 	} else {
1367 		ret = bpf_prog_run_array_cg(&cgrp->bpf, atype,
1368 					    skb, __bpf_prog_run_save_cb, 0,
1369 					    NULL);
1370 		if (ret && !IS_ERR_VALUE((long)ret))
1371 			ret = -EFAULT;
1372 	}
1373 	bpf_restore_data_end(skb, saved_data_end);
1374 	__skb_pull(skb, offset);
1375 	skb->sk = save_sk;
1376 
1377 	return ret;
1378 }
1379 EXPORT_SYMBOL(__cgroup_bpf_run_filter_skb);
1380 
1381 /**
1382  * __cgroup_bpf_run_filter_sk() - Run a program on a sock
1383  * @sk: sock structure to manipulate
1384  * @type: The type of program to be executed
1385  *
1386  * socket is passed is expected to be of type INET or INET6.
1387  *
1388  * The program type passed in via @type must be suitable for sock
1389  * filtering. No further check is performed to assert that.
1390  *
1391  * This function will return %-EPERM if any if an attached program was found
1392  * and if it returned != 1 during execution. In all other cases, 0 is returned.
1393  */
1394 int __cgroup_bpf_run_filter_sk(struct sock *sk,
1395 			       enum cgroup_bpf_attach_type atype)
1396 {
1397 	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1398 
1399 	return bpf_prog_run_array_cg(&cgrp->bpf, atype, sk, bpf_prog_run, 0,
1400 				     NULL);
1401 }
1402 EXPORT_SYMBOL(__cgroup_bpf_run_filter_sk);
1403 
1404 /**
1405  * __cgroup_bpf_run_filter_sock_addr() - Run a program on a sock and
1406  *                                       provided by user sockaddr
1407  * @sk: sock struct that will use sockaddr
1408  * @uaddr: sockaddr struct provided by user
1409  * @type: The type of program to be executed
1410  * @t_ctx: Pointer to attach type specific context
1411  * @flags: Pointer to u32 which contains higher bits of BPF program
1412  *         return value (OR'ed together).
1413  *
1414  * socket is expected to be of type INET or INET6.
1415  *
1416  * This function will return %-EPERM if an attached program is found and
1417  * returned value != 1 during execution. In all other cases, 0 is returned.
1418  */
1419 int __cgroup_bpf_run_filter_sock_addr(struct sock *sk,
1420 				      struct sockaddr *uaddr,
1421 				      enum cgroup_bpf_attach_type atype,
1422 				      void *t_ctx,
1423 				      u32 *flags)
1424 {
1425 	struct bpf_sock_addr_kern ctx = {
1426 		.sk = sk,
1427 		.uaddr = uaddr,
1428 		.t_ctx = t_ctx,
1429 	};
1430 	struct sockaddr_storage unspec;
1431 	struct cgroup *cgrp;
1432 
1433 	/* Check socket family since not all sockets represent network
1434 	 * endpoint (e.g. AF_UNIX).
1435 	 */
1436 	if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
1437 		return 0;
1438 
1439 	if (!ctx.uaddr) {
1440 		memset(&unspec, 0, sizeof(unspec));
1441 		ctx.uaddr = (struct sockaddr *)&unspec;
1442 	}
1443 
1444 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1445 	return bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run,
1446 				     0, flags);
1447 }
1448 EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_addr);
1449 
1450 /**
1451  * __cgroup_bpf_run_filter_sock_ops() - Run a program on a sock
1452  * @sk: socket to get cgroup from
1453  * @sock_ops: bpf_sock_ops_kern struct to pass to program. Contains
1454  * sk with connection information (IP addresses, etc.) May not contain
1455  * cgroup info if it is a req sock.
1456  * @type: The type of program to be executed
1457  *
1458  * socket passed is expected to be of type INET or INET6.
1459  *
1460  * The program type passed in via @type must be suitable for sock_ops
1461  * filtering. No further check is performed to assert that.
1462  *
1463  * This function will return %-EPERM if any if an attached program was found
1464  * and if it returned != 1 during execution. In all other cases, 0 is returned.
1465  */
1466 int __cgroup_bpf_run_filter_sock_ops(struct sock *sk,
1467 				     struct bpf_sock_ops_kern *sock_ops,
1468 				     enum cgroup_bpf_attach_type atype)
1469 {
1470 	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1471 
1472 	return bpf_prog_run_array_cg(&cgrp->bpf, atype, sock_ops, bpf_prog_run,
1473 				     0, NULL);
1474 }
1475 EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_ops);
1476 
1477 int __cgroup_bpf_check_dev_permission(short dev_type, u32 major, u32 minor,
1478 				      short access, enum cgroup_bpf_attach_type atype)
1479 {
1480 	struct cgroup *cgrp;
1481 	struct bpf_cgroup_dev_ctx ctx = {
1482 		.access_type = (access << 16) | dev_type,
1483 		.major = major,
1484 		.minor = minor,
1485 	};
1486 	int ret;
1487 
1488 	rcu_read_lock();
1489 	cgrp = task_dfl_cgroup(current);
1490 	ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run, 0,
1491 				    NULL);
1492 	rcu_read_unlock();
1493 
1494 	return ret;
1495 }
1496 
1497 BPF_CALL_0(bpf_get_retval)
1498 {
1499 	struct bpf_cg_run_ctx *ctx =
1500 		container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx);
1501 
1502 	return ctx->retval;
1503 }
1504 
1505 const struct bpf_func_proto bpf_get_retval_proto = {
1506 	.func		= bpf_get_retval,
1507 	.gpl_only	= false,
1508 	.ret_type	= RET_INTEGER,
1509 };
1510 
1511 BPF_CALL_1(bpf_set_retval, int, retval)
1512 {
1513 	struct bpf_cg_run_ctx *ctx =
1514 		container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx);
1515 
1516 	ctx->retval = retval;
1517 	return 0;
1518 }
1519 
1520 const struct bpf_func_proto bpf_set_retval_proto = {
1521 	.func		= bpf_set_retval,
1522 	.gpl_only	= false,
1523 	.ret_type	= RET_INTEGER,
1524 	.arg1_type	= ARG_ANYTHING,
1525 };
1526 
1527 static const struct bpf_func_proto *
1528 cgroup_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1529 {
1530 	switch (func_id) {
1531 	case BPF_FUNC_get_current_uid_gid:
1532 		return &bpf_get_current_uid_gid_proto;
1533 	case BPF_FUNC_get_local_storage:
1534 		return &bpf_get_local_storage_proto;
1535 	case BPF_FUNC_get_current_cgroup_id:
1536 		return &bpf_get_current_cgroup_id_proto;
1537 	case BPF_FUNC_perf_event_output:
1538 		return &bpf_event_output_data_proto;
1539 	case BPF_FUNC_get_retval:
1540 		return &bpf_get_retval_proto;
1541 	case BPF_FUNC_set_retval:
1542 		return &bpf_set_retval_proto;
1543 	default:
1544 		return bpf_base_func_proto(func_id);
1545 	}
1546 }
1547 
1548 static const struct bpf_func_proto *
1549 cgroup_dev_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1550 {
1551 	return cgroup_base_func_proto(func_id, prog);
1552 }
1553 
1554 static bool cgroup_dev_is_valid_access(int off, int size,
1555 				       enum bpf_access_type type,
1556 				       const struct bpf_prog *prog,
1557 				       struct bpf_insn_access_aux *info)
1558 {
1559 	const int size_default = sizeof(__u32);
1560 
1561 	if (type == BPF_WRITE)
1562 		return false;
1563 
1564 	if (off < 0 || off + size > sizeof(struct bpf_cgroup_dev_ctx))
1565 		return false;
1566 	/* The verifier guarantees that size > 0. */
1567 	if (off % size != 0)
1568 		return false;
1569 
1570 	switch (off) {
1571 	case bpf_ctx_range(struct bpf_cgroup_dev_ctx, access_type):
1572 		bpf_ctx_record_field_size(info, size_default);
1573 		if (!bpf_ctx_narrow_access_ok(off, size, size_default))
1574 			return false;
1575 		break;
1576 	default:
1577 		if (size != size_default)
1578 			return false;
1579 	}
1580 
1581 	return true;
1582 }
1583 
1584 const struct bpf_prog_ops cg_dev_prog_ops = {
1585 };
1586 
1587 const struct bpf_verifier_ops cg_dev_verifier_ops = {
1588 	.get_func_proto		= cgroup_dev_func_proto,
1589 	.is_valid_access	= cgroup_dev_is_valid_access,
1590 };
1591 
1592 /**
1593  * __cgroup_bpf_run_filter_sysctl - Run a program on sysctl
1594  *
1595  * @head: sysctl table header
1596  * @table: sysctl table
1597  * @write: sysctl is being read (= 0) or written (= 1)
1598  * @buf: pointer to buffer (in and out)
1599  * @pcount: value-result argument: value is size of buffer pointed to by @buf,
1600  *	result is size of @new_buf if program set new value, initial value
1601  *	otherwise
1602  * @ppos: value-result argument: value is position at which read from or write
1603  *	to sysctl is happening, result is new position if program overrode it,
1604  *	initial value otherwise
1605  * @type: type of program to be executed
1606  *
1607  * Program is run when sysctl is being accessed, either read or written, and
1608  * can allow or deny such access.
1609  *
1610  * This function will return %-EPERM if an attached program is found and
1611  * returned value != 1 during execution. In all other cases 0 is returned.
1612  */
1613 int __cgroup_bpf_run_filter_sysctl(struct ctl_table_header *head,
1614 				   struct ctl_table *table, int write,
1615 				   char **buf, size_t *pcount, loff_t *ppos,
1616 				   enum cgroup_bpf_attach_type atype)
1617 {
1618 	struct bpf_sysctl_kern ctx = {
1619 		.head = head,
1620 		.table = table,
1621 		.write = write,
1622 		.ppos = ppos,
1623 		.cur_val = NULL,
1624 		.cur_len = PAGE_SIZE,
1625 		.new_val = NULL,
1626 		.new_len = 0,
1627 		.new_updated = 0,
1628 	};
1629 	struct cgroup *cgrp;
1630 	loff_t pos = 0;
1631 	int ret;
1632 
1633 	ctx.cur_val = kmalloc_track_caller(ctx.cur_len, GFP_KERNEL);
1634 	if (!ctx.cur_val ||
1635 	    table->proc_handler(table, 0, ctx.cur_val, &ctx.cur_len, &pos)) {
1636 		/* Let BPF program decide how to proceed. */
1637 		ctx.cur_len = 0;
1638 	}
1639 
1640 	if (write && *buf && *pcount) {
1641 		/* BPF program should be able to override new value with a
1642 		 * buffer bigger than provided by user.
1643 		 */
1644 		ctx.new_val = kmalloc_track_caller(PAGE_SIZE, GFP_KERNEL);
1645 		ctx.new_len = min_t(size_t, PAGE_SIZE, *pcount);
1646 		if (ctx.new_val) {
1647 			memcpy(ctx.new_val, *buf, ctx.new_len);
1648 		} else {
1649 			/* Let BPF program decide how to proceed. */
1650 			ctx.new_len = 0;
1651 		}
1652 	}
1653 
1654 	rcu_read_lock();
1655 	cgrp = task_dfl_cgroup(current);
1656 	ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run, 0,
1657 				    NULL);
1658 	rcu_read_unlock();
1659 
1660 	kfree(ctx.cur_val);
1661 
1662 	if (ret == 1 && ctx.new_updated) {
1663 		kfree(*buf);
1664 		*buf = ctx.new_val;
1665 		*pcount = ctx.new_len;
1666 	} else {
1667 		kfree(ctx.new_val);
1668 	}
1669 
1670 	return ret;
1671 }
1672 
1673 #ifdef CONFIG_NET
1674 static int sockopt_alloc_buf(struct bpf_sockopt_kern *ctx, int max_optlen,
1675 			     struct bpf_sockopt_buf *buf)
1676 {
1677 	if (unlikely(max_optlen < 0))
1678 		return -EINVAL;
1679 
1680 	if (unlikely(max_optlen > PAGE_SIZE)) {
1681 		/* We don't expose optvals that are greater than PAGE_SIZE
1682 		 * to the BPF program.
1683 		 */
1684 		max_optlen = PAGE_SIZE;
1685 	}
1686 
1687 	if (max_optlen <= sizeof(buf->data)) {
1688 		/* When the optval fits into BPF_SOCKOPT_KERN_BUF_SIZE
1689 		 * bytes avoid the cost of kzalloc.
1690 		 */
1691 		ctx->optval = buf->data;
1692 		ctx->optval_end = ctx->optval + max_optlen;
1693 		return max_optlen;
1694 	}
1695 
1696 	ctx->optval = kzalloc(max_optlen, GFP_USER);
1697 	if (!ctx->optval)
1698 		return -ENOMEM;
1699 
1700 	ctx->optval_end = ctx->optval + max_optlen;
1701 
1702 	return max_optlen;
1703 }
1704 
1705 static void sockopt_free_buf(struct bpf_sockopt_kern *ctx,
1706 			     struct bpf_sockopt_buf *buf)
1707 {
1708 	if (ctx->optval == buf->data)
1709 		return;
1710 	kfree(ctx->optval);
1711 }
1712 
1713 static bool sockopt_buf_allocated(struct bpf_sockopt_kern *ctx,
1714 				  struct bpf_sockopt_buf *buf)
1715 {
1716 	return ctx->optval != buf->data;
1717 }
1718 
1719 int __cgroup_bpf_run_filter_setsockopt(struct sock *sk, int *level,
1720 				       int *optname, char __user *optval,
1721 				       int *optlen, char **kernel_optval)
1722 {
1723 	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1724 	struct bpf_sockopt_buf buf = {};
1725 	struct bpf_sockopt_kern ctx = {
1726 		.sk = sk,
1727 		.level = *level,
1728 		.optname = *optname,
1729 	};
1730 	int ret, max_optlen;
1731 
1732 	/* Allocate a bit more than the initial user buffer for
1733 	 * BPF program. The canonical use case is overriding
1734 	 * TCP_CONGESTION(nv) to TCP_CONGESTION(cubic).
1735 	 */
1736 	max_optlen = max_t(int, 16, *optlen);
1737 	max_optlen = sockopt_alloc_buf(&ctx, max_optlen, &buf);
1738 	if (max_optlen < 0)
1739 		return max_optlen;
1740 
1741 	ctx.optlen = *optlen;
1742 
1743 	if (copy_from_user(ctx.optval, optval, min(*optlen, max_optlen)) != 0) {
1744 		ret = -EFAULT;
1745 		goto out;
1746 	}
1747 
1748 	lock_sock(sk);
1749 	ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_SETSOCKOPT,
1750 				    &ctx, bpf_prog_run, 0, NULL);
1751 	release_sock(sk);
1752 
1753 	if (ret)
1754 		goto out;
1755 
1756 	if (ctx.optlen == -1) {
1757 		/* optlen set to -1, bypass kernel */
1758 		ret = 1;
1759 	} else if (ctx.optlen > max_optlen || ctx.optlen < -1) {
1760 		/* optlen is out of bounds */
1761 		ret = -EFAULT;
1762 	} else {
1763 		/* optlen within bounds, run kernel handler */
1764 		ret = 0;
1765 
1766 		/* export any potential modifications */
1767 		*level = ctx.level;
1768 		*optname = ctx.optname;
1769 
1770 		/* optlen == 0 from BPF indicates that we should
1771 		 * use original userspace data.
1772 		 */
1773 		if (ctx.optlen != 0) {
1774 			*optlen = ctx.optlen;
1775 			/* We've used bpf_sockopt_kern->buf as an intermediary
1776 			 * storage, but the BPF program indicates that we need
1777 			 * to pass this data to the kernel setsockopt handler.
1778 			 * No way to export on-stack buf, have to allocate a
1779 			 * new buffer.
1780 			 */
1781 			if (!sockopt_buf_allocated(&ctx, &buf)) {
1782 				void *p = kmalloc(ctx.optlen, GFP_USER);
1783 
1784 				if (!p) {
1785 					ret = -ENOMEM;
1786 					goto out;
1787 				}
1788 				memcpy(p, ctx.optval, ctx.optlen);
1789 				*kernel_optval = p;
1790 			} else {
1791 				*kernel_optval = ctx.optval;
1792 			}
1793 			/* export and don't free sockopt buf */
1794 			return 0;
1795 		}
1796 	}
1797 
1798 out:
1799 	sockopt_free_buf(&ctx, &buf);
1800 	return ret;
1801 }
1802 
1803 int __cgroup_bpf_run_filter_getsockopt(struct sock *sk, int level,
1804 				       int optname, char __user *optval,
1805 				       int __user *optlen, int max_optlen,
1806 				       int retval)
1807 {
1808 	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1809 	struct bpf_sockopt_buf buf = {};
1810 	struct bpf_sockopt_kern ctx = {
1811 		.sk = sk,
1812 		.level = level,
1813 		.optname = optname,
1814 		.current_task = current,
1815 	};
1816 	int ret;
1817 
1818 	ctx.optlen = max_optlen;
1819 	max_optlen = sockopt_alloc_buf(&ctx, max_optlen, &buf);
1820 	if (max_optlen < 0)
1821 		return max_optlen;
1822 
1823 	if (!retval) {
1824 		/* If kernel getsockopt finished successfully,
1825 		 * copy whatever was returned to the user back
1826 		 * into our temporary buffer. Set optlen to the
1827 		 * one that kernel returned as well to let
1828 		 * BPF programs inspect the value.
1829 		 */
1830 
1831 		if (get_user(ctx.optlen, optlen)) {
1832 			ret = -EFAULT;
1833 			goto out;
1834 		}
1835 
1836 		if (ctx.optlen < 0) {
1837 			ret = -EFAULT;
1838 			goto out;
1839 		}
1840 
1841 		if (copy_from_user(ctx.optval, optval,
1842 				   min(ctx.optlen, max_optlen)) != 0) {
1843 			ret = -EFAULT;
1844 			goto out;
1845 		}
1846 	}
1847 
1848 	lock_sock(sk);
1849 	ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_GETSOCKOPT,
1850 				    &ctx, bpf_prog_run, retval, NULL);
1851 	release_sock(sk);
1852 
1853 	if (ret < 0)
1854 		goto out;
1855 
1856 	if (ctx.optlen > max_optlen || ctx.optlen < 0) {
1857 		ret = -EFAULT;
1858 		goto out;
1859 	}
1860 
1861 	if (ctx.optlen != 0) {
1862 		if (copy_to_user(optval, ctx.optval, ctx.optlen) ||
1863 		    put_user(ctx.optlen, optlen)) {
1864 			ret = -EFAULT;
1865 			goto out;
1866 		}
1867 	}
1868 
1869 out:
1870 	sockopt_free_buf(&ctx, &buf);
1871 	return ret;
1872 }
1873 
1874 int __cgroup_bpf_run_filter_getsockopt_kern(struct sock *sk, int level,
1875 					    int optname, void *optval,
1876 					    int *optlen, int retval)
1877 {
1878 	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1879 	struct bpf_sockopt_kern ctx = {
1880 		.sk = sk,
1881 		.level = level,
1882 		.optname = optname,
1883 		.optlen = *optlen,
1884 		.optval = optval,
1885 		.optval_end = optval + *optlen,
1886 		.current_task = current,
1887 	};
1888 	int ret;
1889 
1890 	/* Note that __cgroup_bpf_run_filter_getsockopt doesn't copy
1891 	 * user data back into BPF buffer when reval != 0. This is
1892 	 * done as an optimization to avoid extra copy, assuming
1893 	 * kernel won't populate the data in case of an error.
1894 	 * Here we always pass the data and memset() should
1895 	 * be called if that data shouldn't be "exported".
1896 	 */
1897 
1898 	ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_GETSOCKOPT,
1899 				    &ctx, bpf_prog_run, retval, NULL);
1900 	if (ret < 0)
1901 		return ret;
1902 
1903 	if (ctx.optlen > *optlen)
1904 		return -EFAULT;
1905 
1906 	/* BPF programs can shrink the buffer, export the modifications.
1907 	 */
1908 	if (ctx.optlen != 0)
1909 		*optlen = ctx.optlen;
1910 
1911 	return ret;
1912 }
1913 #endif
1914 
1915 static ssize_t sysctl_cpy_dir(const struct ctl_dir *dir, char **bufp,
1916 			      size_t *lenp)
1917 {
1918 	ssize_t tmp_ret = 0, ret;
1919 
1920 	if (dir->header.parent) {
1921 		tmp_ret = sysctl_cpy_dir(dir->header.parent, bufp, lenp);
1922 		if (tmp_ret < 0)
1923 			return tmp_ret;
1924 	}
1925 
1926 	ret = strscpy(*bufp, dir->header.ctl_table[0].procname, *lenp);
1927 	if (ret < 0)
1928 		return ret;
1929 	*bufp += ret;
1930 	*lenp -= ret;
1931 	ret += tmp_ret;
1932 
1933 	/* Avoid leading slash. */
1934 	if (!ret)
1935 		return ret;
1936 
1937 	tmp_ret = strscpy(*bufp, "/", *lenp);
1938 	if (tmp_ret < 0)
1939 		return tmp_ret;
1940 	*bufp += tmp_ret;
1941 	*lenp -= tmp_ret;
1942 
1943 	return ret + tmp_ret;
1944 }
1945 
1946 BPF_CALL_4(bpf_sysctl_get_name, struct bpf_sysctl_kern *, ctx, char *, buf,
1947 	   size_t, buf_len, u64, flags)
1948 {
1949 	ssize_t tmp_ret = 0, ret;
1950 
1951 	if (!buf)
1952 		return -EINVAL;
1953 
1954 	if (!(flags & BPF_F_SYSCTL_BASE_NAME)) {
1955 		if (!ctx->head)
1956 			return -EINVAL;
1957 		tmp_ret = sysctl_cpy_dir(ctx->head->parent, &buf, &buf_len);
1958 		if (tmp_ret < 0)
1959 			return tmp_ret;
1960 	}
1961 
1962 	ret = strscpy(buf, ctx->table->procname, buf_len);
1963 
1964 	return ret < 0 ? ret : tmp_ret + ret;
1965 }
1966 
1967 static const struct bpf_func_proto bpf_sysctl_get_name_proto = {
1968 	.func		= bpf_sysctl_get_name,
1969 	.gpl_only	= false,
1970 	.ret_type	= RET_INTEGER,
1971 	.arg1_type	= ARG_PTR_TO_CTX,
1972 	.arg2_type	= ARG_PTR_TO_MEM,
1973 	.arg3_type	= ARG_CONST_SIZE,
1974 	.arg4_type	= ARG_ANYTHING,
1975 };
1976 
1977 static int copy_sysctl_value(char *dst, size_t dst_len, char *src,
1978 			     size_t src_len)
1979 {
1980 	if (!dst)
1981 		return -EINVAL;
1982 
1983 	if (!dst_len)
1984 		return -E2BIG;
1985 
1986 	if (!src || !src_len) {
1987 		memset(dst, 0, dst_len);
1988 		return -EINVAL;
1989 	}
1990 
1991 	memcpy(dst, src, min(dst_len, src_len));
1992 
1993 	if (dst_len > src_len) {
1994 		memset(dst + src_len, '\0', dst_len - src_len);
1995 		return src_len;
1996 	}
1997 
1998 	dst[dst_len - 1] = '\0';
1999 
2000 	return -E2BIG;
2001 }
2002 
2003 BPF_CALL_3(bpf_sysctl_get_current_value, struct bpf_sysctl_kern *, ctx,
2004 	   char *, buf, size_t, buf_len)
2005 {
2006 	return copy_sysctl_value(buf, buf_len, ctx->cur_val, ctx->cur_len);
2007 }
2008 
2009 static const struct bpf_func_proto bpf_sysctl_get_current_value_proto = {
2010 	.func		= bpf_sysctl_get_current_value,
2011 	.gpl_only	= false,
2012 	.ret_type	= RET_INTEGER,
2013 	.arg1_type	= ARG_PTR_TO_CTX,
2014 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
2015 	.arg3_type	= ARG_CONST_SIZE,
2016 };
2017 
2018 BPF_CALL_3(bpf_sysctl_get_new_value, struct bpf_sysctl_kern *, ctx, char *, buf,
2019 	   size_t, buf_len)
2020 {
2021 	if (!ctx->write) {
2022 		if (buf && buf_len)
2023 			memset(buf, '\0', buf_len);
2024 		return -EINVAL;
2025 	}
2026 	return copy_sysctl_value(buf, buf_len, ctx->new_val, ctx->new_len);
2027 }
2028 
2029 static const struct bpf_func_proto bpf_sysctl_get_new_value_proto = {
2030 	.func		= bpf_sysctl_get_new_value,
2031 	.gpl_only	= false,
2032 	.ret_type	= RET_INTEGER,
2033 	.arg1_type	= ARG_PTR_TO_CTX,
2034 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
2035 	.arg3_type	= ARG_CONST_SIZE,
2036 };
2037 
2038 BPF_CALL_3(bpf_sysctl_set_new_value, struct bpf_sysctl_kern *, ctx,
2039 	   const char *, buf, size_t, buf_len)
2040 {
2041 	if (!ctx->write || !ctx->new_val || !ctx->new_len || !buf || !buf_len)
2042 		return -EINVAL;
2043 
2044 	if (buf_len > PAGE_SIZE - 1)
2045 		return -E2BIG;
2046 
2047 	memcpy(ctx->new_val, buf, buf_len);
2048 	ctx->new_len = buf_len;
2049 	ctx->new_updated = 1;
2050 
2051 	return 0;
2052 }
2053 
2054 static const struct bpf_func_proto bpf_sysctl_set_new_value_proto = {
2055 	.func		= bpf_sysctl_set_new_value,
2056 	.gpl_only	= false,
2057 	.ret_type	= RET_INTEGER,
2058 	.arg1_type	= ARG_PTR_TO_CTX,
2059 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
2060 	.arg3_type	= ARG_CONST_SIZE,
2061 };
2062 
2063 static const struct bpf_func_proto *
2064 sysctl_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2065 {
2066 	switch (func_id) {
2067 	case BPF_FUNC_strtol:
2068 		return &bpf_strtol_proto;
2069 	case BPF_FUNC_strtoul:
2070 		return &bpf_strtoul_proto;
2071 	case BPF_FUNC_sysctl_get_name:
2072 		return &bpf_sysctl_get_name_proto;
2073 	case BPF_FUNC_sysctl_get_current_value:
2074 		return &bpf_sysctl_get_current_value_proto;
2075 	case BPF_FUNC_sysctl_get_new_value:
2076 		return &bpf_sysctl_get_new_value_proto;
2077 	case BPF_FUNC_sysctl_set_new_value:
2078 		return &bpf_sysctl_set_new_value_proto;
2079 	case BPF_FUNC_ktime_get_coarse_ns:
2080 		return &bpf_ktime_get_coarse_ns_proto;
2081 	default:
2082 		return cgroup_base_func_proto(func_id, prog);
2083 	}
2084 }
2085 
2086 static bool sysctl_is_valid_access(int off, int size, enum bpf_access_type type,
2087 				   const struct bpf_prog *prog,
2088 				   struct bpf_insn_access_aux *info)
2089 {
2090 	const int size_default = sizeof(__u32);
2091 
2092 	if (off < 0 || off + size > sizeof(struct bpf_sysctl) || off % size)
2093 		return false;
2094 
2095 	switch (off) {
2096 	case bpf_ctx_range(struct bpf_sysctl, write):
2097 		if (type != BPF_READ)
2098 			return false;
2099 		bpf_ctx_record_field_size(info, size_default);
2100 		return bpf_ctx_narrow_access_ok(off, size, size_default);
2101 	case bpf_ctx_range(struct bpf_sysctl, file_pos):
2102 		if (type == BPF_READ) {
2103 			bpf_ctx_record_field_size(info, size_default);
2104 			return bpf_ctx_narrow_access_ok(off, size, size_default);
2105 		} else {
2106 			return size == size_default;
2107 		}
2108 	default:
2109 		return false;
2110 	}
2111 }
2112 
2113 static u32 sysctl_convert_ctx_access(enum bpf_access_type type,
2114 				     const struct bpf_insn *si,
2115 				     struct bpf_insn *insn_buf,
2116 				     struct bpf_prog *prog, u32 *target_size)
2117 {
2118 	struct bpf_insn *insn = insn_buf;
2119 	u32 read_size;
2120 
2121 	switch (si->off) {
2122 	case offsetof(struct bpf_sysctl, write):
2123 		*insn++ = BPF_LDX_MEM(
2124 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
2125 			bpf_target_off(struct bpf_sysctl_kern, write,
2126 				       sizeof_field(struct bpf_sysctl_kern,
2127 						    write),
2128 				       target_size));
2129 		break;
2130 	case offsetof(struct bpf_sysctl, file_pos):
2131 		/* ppos is a pointer so it should be accessed via indirect
2132 		 * loads and stores. Also for stores additional temporary
2133 		 * register is used since neither src_reg nor dst_reg can be
2134 		 * overridden.
2135 		 */
2136 		if (type == BPF_WRITE) {
2137 			int treg = BPF_REG_9;
2138 
2139 			if (si->src_reg == treg || si->dst_reg == treg)
2140 				--treg;
2141 			if (si->src_reg == treg || si->dst_reg == treg)
2142 				--treg;
2143 			*insn++ = BPF_STX_MEM(
2144 				BPF_DW, si->dst_reg, treg,
2145 				offsetof(struct bpf_sysctl_kern, tmp_reg));
2146 			*insn++ = BPF_LDX_MEM(
2147 				BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
2148 				treg, si->dst_reg,
2149 				offsetof(struct bpf_sysctl_kern, ppos));
2150 			*insn++ = BPF_STX_MEM(
2151 				BPF_SIZEOF(u32), treg, si->src_reg,
2152 				bpf_ctx_narrow_access_offset(
2153 					0, sizeof(u32), sizeof(loff_t)));
2154 			*insn++ = BPF_LDX_MEM(
2155 				BPF_DW, treg, si->dst_reg,
2156 				offsetof(struct bpf_sysctl_kern, tmp_reg));
2157 		} else {
2158 			*insn++ = BPF_LDX_MEM(
2159 				BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
2160 				si->dst_reg, si->src_reg,
2161 				offsetof(struct bpf_sysctl_kern, ppos));
2162 			read_size = bpf_size_to_bytes(BPF_SIZE(si->code));
2163 			*insn++ = BPF_LDX_MEM(
2164 				BPF_SIZE(si->code), si->dst_reg, si->dst_reg,
2165 				bpf_ctx_narrow_access_offset(
2166 					0, read_size, sizeof(loff_t)));
2167 		}
2168 		*target_size = sizeof(u32);
2169 		break;
2170 	}
2171 
2172 	return insn - insn_buf;
2173 }
2174 
2175 const struct bpf_verifier_ops cg_sysctl_verifier_ops = {
2176 	.get_func_proto		= sysctl_func_proto,
2177 	.is_valid_access	= sysctl_is_valid_access,
2178 	.convert_ctx_access	= sysctl_convert_ctx_access,
2179 };
2180 
2181 const struct bpf_prog_ops cg_sysctl_prog_ops = {
2182 };
2183 
2184 #ifdef CONFIG_NET
2185 BPF_CALL_1(bpf_get_netns_cookie_sockopt, struct bpf_sockopt_kern *, ctx)
2186 {
2187 	const struct net *net = ctx ? sock_net(ctx->sk) : &init_net;
2188 
2189 	return net->net_cookie;
2190 }
2191 
2192 static const struct bpf_func_proto bpf_get_netns_cookie_sockopt_proto = {
2193 	.func		= bpf_get_netns_cookie_sockopt,
2194 	.gpl_only	= false,
2195 	.ret_type	= RET_INTEGER,
2196 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
2197 };
2198 #endif
2199 
2200 static const struct bpf_func_proto *
2201 cg_sockopt_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2202 {
2203 	switch (func_id) {
2204 #ifdef CONFIG_NET
2205 	case BPF_FUNC_get_netns_cookie:
2206 		return &bpf_get_netns_cookie_sockopt_proto;
2207 	case BPF_FUNC_sk_storage_get:
2208 		return &bpf_sk_storage_get_proto;
2209 	case BPF_FUNC_sk_storage_delete:
2210 		return &bpf_sk_storage_delete_proto;
2211 	case BPF_FUNC_setsockopt:
2212 		if (prog->expected_attach_type == BPF_CGROUP_SETSOCKOPT)
2213 			return &bpf_sk_setsockopt_proto;
2214 		return NULL;
2215 	case BPF_FUNC_getsockopt:
2216 		if (prog->expected_attach_type == BPF_CGROUP_SETSOCKOPT)
2217 			return &bpf_sk_getsockopt_proto;
2218 		return NULL;
2219 #endif
2220 #ifdef CONFIG_INET
2221 	case BPF_FUNC_tcp_sock:
2222 		return &bpf_tcp_sock_proto;
2223 #endif
2224 	default:
2225 		return cgroup_base_func_proto(func_id, prog);
2226 	}
2227 }
2228 
2229 static bool cg_sockopt_is_valid_access(int off, int size,
2230 				       enum bpf_access_type type,
2231 				       const struct bpf_prog *prog,
2232 				       struct bpf_insn_access_aux *info)
2233 {
2234 	const int size_default = sizeof(__u32);
2235 
2236 	if (off < 0 || off >= sizeof(struct bpf_sockopt))
2237 		return false;
2238 
2239 	if (off % size != 0)
2240 		return false;
2241 
2242 	if (type == BPF_WRITE) {
2243 		switch (off) {
2244 		case offsetof(struct bpf_sockopt, retval):
2245 			if (size != size_default)
2246 				return false;
2247 			return prog->expected_attach_type ==
2248 				BPF_CGROUP_GETSOCKOPT;
2249 		case offsetof(struct bpf_sockopt, optname):
2250 			fallthrough;
2251 		case offsetof(struct bpf_sockopt, level):
2252 			if (size != size_default)
2253 				return false;
2254 			return prog->expected_attach_type ==
2255 				BPF_CGROUP_SETSOCKOPT;
2256 		case offsetof(struct bpf_sockopt, optlen):
2257 			return size == size_default;
2258 		default:
2259 			return false;
2260 		}
2261 	}
2262 
2263 	switch (off) {
2264 	case offsetof(struct bpf_sockopt, sk):
2265 		if (size != sizeof(__u64))
2266 			return false;
2267 		info->reg_type = PTR_TO_SOCKET;
2268 		break;
2269 	case offsetof(struct bpf_sockopt, optval):
2270 		if (size != sizeof(__u64))
2271 			return false;
2272 		info->reg_type = PTR_TO_PACKET;
2273 		break;
2274 	case offsetof(struct bpf_sockopt, optval_end):
2275 		if (size != sizeof(__u64))
2276 			return false;
2277 		info->reg_type = PTR_TO_PACKET_END;
2278 		break;
2279 	case offsetof(struct bpf_sockopt, retval):
2280 		if (size != size_default)
2281 			return false;
2282 		return prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT;
2283 	default:
2284 		if (size != size_default)
2285 			return false;
2286 		break;
2287 	}
2288 	return true;
2289 }
2290 
2291 #define CG_SOCKOPT_ACCESS_FIELD(T, F)					\
2292 	T(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, F),			\
2293 	  si->dst_reg, si->src_reg,					\
2294 	  offsetof(struct bpf_sockopt_kern, F))
2295 
2296 static u32 cg_sockopt_convert_ctx_access(enum bpf_access_type type,
2297 					 const struct bpf_insn *si,
2298 					 struct bpf_insn *insn_buf,
2299 					 struct bpf_prog *prog,
2300 					 u32 *target_size)
2301 {
2302 	struct bpf_insn *insn = insn_buf;
2303 
2304 	switch (si->off) {
2305 	case offsetof(struct bpf_sockopt, sk):
2306 		*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, sk);
2307 		break;
2308 	case offsetof(struct bpf_sockopt, level):
2309 		if (type == BPF_WRITE)
2310 			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_STX_MEM, level);
2311 		else
2312 			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, level);
2313 		break;
2314 	case offsetof(struct bpf_sockopt, optname):
2315 		if (type == BPF_WRITE)
2316 			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_STX_MEM, optname);
2317 		else
2318 			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optname);
2319 		break;
2320 	case offsetof(struct bpf_sockopt, optlen):
2321 		if (type == BPF_WRITE)
2322 			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_STX_MEM, optlen);
2323 		else
2324 			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optlen);
2325 		break;
2326 	case offsetof(struct bpf_sockopt, retval):
2327 		BUILD_BUG_ON(offsetof(struct bpf_cg_run_ctx, run_ctx) != 0);
2328 
2329 		if (type == BPF_WRITE) {
2330 			int treg = BPF_REG_9;
2331 
2332 			if (si->src_reg == treg || si->dst_reg == treg)
2333 				--treg;
2334 			if (si->src_reg == treg || si->dst_reg == treg)
2335 				--treg;
2336 			*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, treg,
2337 					      offsetof(struct bpf_sockopt_kern, tmp_reg));
2338 			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, current_task),
2339 					      treg, si->dst_reg,
2340 					      offsetof(struct bpf_sockopt_kern, current_task));
2341 			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct task_struct, bpf_ctx),
2342 					      treg, treg,
2343 					      offsetof(struct task_struct, bpf_ctx));
2344 			*insn++ = BPF_STX_MEM(BPF_FIELD_SIZEOF(struct bpf_cg_run_ctx, retval),
2345 					      treg, si->src_reg,
2346 					      offsetof(struct bpf_cg_run_ctx, retval));
2347 			*insn++ = BPF_LDX_MEM(BPF_DW, treg, si->dst_reg,
2348 					      offsetof(struct bpf_sockopt_kern, tmp_reg));
2349 		} else {
2350 			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, current_task),
2351 					      si->dst_reg, si->src_reg,
2352 					      offsetof(struct bpf_sockopt_kern, current_task));
2353 			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct task_struct, bpf_ctx),
2354 					      si->dst_reg, si->dst_reg,
2355 					      offsetof(struct task_struct, bpf_ctx));
2356 			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_cg_run_ctx, retval),
2357 					      si->dst_reg, si->dst_reg,
2358 					      offsetof(struct bpf_cg_run_ctx, retval));
2359 		}
2360 		break;
2361 	case offsetof(struct bpf_sockopt, optval):
2362 		*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optval);
2363 		break;
2364 	case offsetof(struct bpf_sockopt, optval_end):
2365 		*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optval_end);
2366 		break;
2367 	}
2368 
2369 	return insn - insn_buf;
2370 }
2371 
2372 static int cg_sockopt_get_prologue(struct bpf_insn *insn_buf,
2373 				   bool direct_write,
2374 				   const struct bpf_prog *prog)
2375 {
2376 	/* Nothing to do for sockopt argument. The data is kzalloc'ated.
2377 	 */
2378 	return 0;
2379 }
2380 
2381 const struct bpf_verifier_ops cg_sockopt_verifier_ops = {
2382 	.get_func_proto		= cg_sockopt_func_proto,
2383 	.is_valid_access	= cg_sockopt_is_valid_access,
2384 	.convert_ctx_access	= cg_sockopt_convert_ctx_access,
2385 	.gen_prologue		= cg_sockopt_get_prologue,
2386 };
2387 
2388 const struct bpf_prog_ops cg_sockopt_prog_ops = {
2389 };
2390