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