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