xref: /linux/kernel/bpf/bpf_struct_ops.c (revision 369d9dcd8fb855f103a83454f0e1cd1cbc9118be)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2019 Facebook */
3 
4 #include <linux/bpf.h>
5 #include <linux/bpf_verifier.h>
6 #include <linux/btf.h>
7 #include <linux/filter.h>
8 #include <linux/slab.h>
9 #include <linux/numa.h>
10 #include <linux/seq_file.h>
11 #include <linux/refcount.h>
12 #include <linux/mutex.h>
13 #include <linux/btf_ids.h>
14 #include <linux/rcupdate_wait.h>
15 #include <linux/poll.h>
16 #include <linux/bpf-cgroup.h>
17 
18 struct bpf_struct_ops_value {
19 	struct bpf_struct_ops_common_value common;
20 	char data[] ____cacheline_aligned_in_smp;
21 };
22 
23 #define MAX_TRAMP_IMAGE_PAGES 8
24 
25 struct bpf_struct_ops_map {
26 	struct bpf_map map;
27 	const struct bpf_struct_ops_desc *st_ops_desc;
28 	/* protect map_update */
29 	struct mutex lock;
30 	/* link has all the bpf_links that is populated
31 	 * to the func ptr of the kernel's struct
32 	 * (in kvalue.data).
33 	 */
34 	struct bpf_link **links;
35 	/* ksyms for bpf trampolines */
36 	struct bpf_ksym **ksyms;
37 	u32 funcs_cnt;
38 	u32 image_pages_cnt;
39 	/* image_pages is an array of pages that has all the trampolines
40 	 * that stores the func args before calling the bpf_prog.
41 	 */
42 	void *image_pages[MAX_TRAMP_IMAGE_PAGES];
43 	/* The owner moduler's btf. */
44 	struct btf *btf;
45 	/* uvalue->data stores the kernel struct
46 	 * (e.g. tcp_congestion_ops) that is more useful
47 	 * to userspace than the kvalue.  For example,
48 	 * the bpf_prog's id is stored instead of the kernel
49 	 * address of a func ptr.
50 	 */
51 	struct bpf_struct_ops_value *uvalue;
52 	/* kvalue.data stores the actual kernel's struct
53 	 * (e.g. tcp_congestion_ops) that will be
54 	 * registered to the kernel subsystem.
55 	 */
56 	struct bpf_struct_ops_value kvalue;
57 };
58 
59 struct bpf_struct_ops_link {
60 	struct bpf_link link;
61 	struct bpf_map *map;
62 	wait_queue_head_t wait_hup;
63 };
64 
65 static DEFINE_MUTEX(update_mutex);
66 
67 #define VALUE_PREFIX "bpf_struct_ops_"
68 #define VALUE_PREFIX_LEN (sizeof(VALUE_PREFIX) - 1)
69 
70 const struct bpf_verifier_ops bpf_struct_ops_verifier_ops = {
71 };
72 
73 const struct bpf_prog_ops bpf_struct_ops_prog_ops = {
74 #ifdef CONFIG_NET
75 	.test_run = bpf_struct_ops_test_run,
76 #endif
77 };
78 
79 BTF_ID_LIST(st_ops_ids)
80 BTF_ID(struct, module)
81 BTF_ID(struct, bpf_struct_ops_common_value)
82 
83 enum {
84 	IDX_MODULE_ID,
85 	IDX_ST_OPS_COMMON_VALUE_ID,
86 };
87 
88 extern struct btf *btf_vmlinux;
89 
90 static bool is_valid_value_type(struct btf *btf, s32 value_id,
91 				const struct btf_type *type,
92 				const char *value_name)
93 {
94 	const struct btf_type *common_value_type;
95 	const struct btf_member *member;
96 	const struct btf_type *vt, *mt;
97 
98 	vt = btf_type_by_id(btf, value_id);
99 	if (btf_vlen(vt) != 2) {
100 		pr_warn("The number of %s's members should be 2, but we get %d\n",
101 			value_name, btf_vlen(vt));
102 		return false;
103 	}
104 	member = btf_type_member(vt);
105 	mt = btf_type_by_id(btf, member->type);
106 	common_value_type = btf_type_by_id(btf_vmlinux,
107 					   st_ops_ids[IDX_ST_OPS_COMMON_VALUE_ID]);
108 	if (mt != common_value_type) {
109 		pr_warn("The first member of %s should be bpf_struct_ops_common_value\n",
110 			value_name);
111 		return false;
112 	}
113 	member++;
114 	mt = btf_type_by_id(btf, member->type);
115 	if (mt != type) {
116 		pr_warn("The second member of %s should be %s\n",
117 			value_name, btf_name_by_offset(btf, type->name_off));
118 		return false;
119 	}
120 
121 	return true;
122 }
123 
124 static void *bpf_struct_ops_image_alloc(void)
125 {
126 	void *image;
127 	int err;
128 
129 	err = bpf_jit_charge_modmem(PAGE_SIZE);
130 	if (err)
131 		return ERR_PTR(err);
132 	image = arch_alloc_bpf_trampoline(PAGE_SIZE);
133 	if (!image) {
134 		bpf_jit_uncharge_modmem(PAGE_SIZE);
135 		return ERR_PTR(-ENOMEM);
136 	}
137 
138 	return image;
139 }
140 
141 void bpf_struct_ops_image_free(void *image)
142 {
143 	if (image) {
144 		arch_free_bpf_trampoline(image, PAGE_SIZE);
145 		bpf_jit_uncharge_modmem(PAGE_SIZE);
146 	}
147 }
148 
149 #define MAYBE_NULL_SUFFIX "__nullable"
150 #define REFCOUNTED_SUFFIX "__ref"
151 #define ARENA_SUFFIX "__arena"
152 #define ARENA_MAYBE_NULL_SUFFIX "__arena__nullable"
153 
154 /* Prepare argument info for every nullable argument of a member of a
155  * struct_ops type.
156  *
157  * Initialize a struct bpf_struct_ops_arg_info according to type info of
158  * the arguments of a stub function. (Check kCFI for more information about
159  * stub functions.)
160  *
161  * Each member in the struct_ops type has a struct bpf_struct_ops_arg_info
162  * to provide an array of struct bpf_ctx_arg_aux, which in turn provides
163  * the information that used by the verifier to check the arguments of the
164  * BPF struct_ops program assigned to the member. Here, we only care about
165  * the arguments that are marked as __nullable, __ref or __arena.
166  *
167  * The array of struct bpf_ctx_arg_aux is eventually assigned to
168  * prog->aux->ctx_arg_info of BPF struct_ops programs and passed to the
169  * verifier. (See check_struct_ops_btf_id())
170  *
171  * arg_info->info will be the list of struct bpf_ctx_arg_aux if success. If
172  * fails, it will be kept untouched.
173  */
174 static int prepare_arg_info(struct btf *btf,
175 			    const char *st_ops_name,
176 			    const char *member_name,
177 			    const struct btf_type *func_proto, void *stub_func_addr,
178 			    struct btf_func_model *model,
179 			    struct bpf_struct_ops_arg_info *arg_info)
180 {
181 	const struct btf_type *stub_func_proto, *pointed_type;
182 	bool is_nullable = false, is_refcounted = false, is_arena = false;
183 	bool is_arena_nullable = false;
184 	const struct btf_param *stub_args, *args;
185 	struct bpf_ctx_arg_aux *info, *info_buf;
186 	u32 nargs, arg_no, info_cnt = 0;
187 	char ksym[KSYM_SYMBOL_LEN];
188 	const char *stub_fname;
189 	const char *suffix;
190 	s32 stub_func_id;
191 	u32 arg_btf_id;
192 	int offset;
193 
194 	stub_fname = kallsyms_lookup((unsigned long)stub_func_addr, NULL, NULL, NULL, ksym);
195 	if (!stub_fname) {
196 		pr_warn("Cannot find the stub function name for the %s in struct %s\n",
197 			member_name, st_ops_name);
198 		return -ENOENT;
199 	}
200 
201 	stub_func_id = btf_find_by_name_kind(btf, stub_fname, BTF_KIND_FUNC);
202 	if (stub_func_id < 0) {
203 		pr_warn("Cannot find the stub function %s in btf\n", stub_fname);
204 		return -ENOENT;
205 	}
206 
207 	stub_func_proto = btf_type_by_id(btf, stub_func_id);
208 	stub_func_proto = btf_type_by_id(btf, stub_func_proto->type);
209 
210 	/* Check if the number of arguments of the stub function is the same
211 	 * as the number of arguments of the function pointer.
212 	 */
213 	nargs = btf_type_vlen(func_proto);
214 	if (nargs != btf_type_vlen(stub_func_proto)) {
215 		pr_warn("the number of arguments of the stub function %s does not match the number of arguments of the member %s of struct %s\n",
216 			stub_fname, member_name, st_ops_name);
217 		return -EINVAL;
218 	}
219 
220 	if (!nargs)
221 		return 0;
222 
223 	args = btf_params(func_proto);
224 	stub_args = btf_params(stub_func_proto);
225 
226 	info_buf = kzalloc_objs(*info_buf, nargs);
227 	if (!info_buf)
228 		return -ENOMEM;
229 
230 	/* Prepare info for every nullable argument */
231 	info = info_buf;
232 	for (arg_no = 0; arg_no < nargs; arg_no++) {
233 		bool ptr_to_arena, ptr_to_struct;
234 
235 		/*
236 		 * Skip arguments that are not suffixed with "__arena__nullable",
237 		 * "__arena", "__nullable", or "__ref".
238 		 */
239 		is_arena_nullable = btf_param_match_suffix(btf, &stub_args[arg_no],
240 							   ARENA_MAYBE_NULL_SUFFIX);
241 		is_arena = btf_param_match_suffix(btf, &stub_args[arg_no], ARENA_SUFFIX);
242 		is_nullable = !is_arena_nullable &&
243 			      btf_param_match_suffix(btf, &stub_args[arg_no], MAYBE_NULL_SUFFIX);
244 		is_refcounted = btf_param_match_suffix(btf, &stub_args[arg_no],
245 						       REFCOUNTED_SUFFIX);
246 
247 		if (is_arena_nullable)
248 			suffix = ARENA_MAYBE_NULL_SUFFIX;
249 		else if (is_arena)
250 			suffix = ARENA_SUFFIX;
251 		else if (is_nullable)
252 			suffix = MAYBE_NULL_SUFFIX;
253 		else if (is_refcounted)
254 			suffix = REFCOUNTED_SUFFIX;
255 		else
256 			continue;
257 
258 		/*
259 		 * Should be a pointer to struct, or any pointer for __arena or
260 		 * __arena__nullable.
261 		 */
262 		pointed_type = btf_type_resolve_ptr(btf, args[arg_no].type, &arg_btf_id);
263 		ptr_to_arena = pointed_type && (is_arena || is_arena_nullable);
264 		ptr_to_struct = pointed_type && btf_type_is_struct(pointed_type);
265 		if (!ptr_to_arena && !ptr_to_struct) {
266 			pr_warn("stub function %s has %s tagging to an unsupported type\n",
267 				stub_fname, suffix);
268 			goto err_out;
269 		}
270 
271 		offset = btf_ctx_arg_offset(btf, func_proto, arg_no);
272 		if (offset < 0) {
273 			pr_warn("stub function %s has an invalid trampoline ctx offset for arg#%u\n",
274 				stub_fname, arg_no);
275 			goto err_out;
276 		}
277 
278 		if (args[arg_no].type != stub_args[arg_no].type) {
279 			pr_warn("arg#%u type in stub function %s does not match with its original func_proto\n",
280 				arg_no, stub_fname);
281 			goto err_out;
282 		}
283 
284 		/* Fill the information of the new argument */
285 		info->btf_id = arg_btf_id;
286 		info->btf = btf;
287 		info->offset = offset;
288 		if (is_arena || is_arena_nullable) {
289 			/*
290 			 * Both types get PTR_TO_ARENA. In verifier state,
291 			 * PTR_TO_ARENA encompasses potential NULL values, but
292 			 * we do not force the program to check it, or maintain
293 			 * precision around it, since it has no safety implication.
294 			 */
295 			info->reg_type = PTR_TO_ARENA;
296 			model->arg_flags[arg_no] |= BTF_FMODEL_ARENA_ARG;
297 			if (is_arena_nullable)
298 				model->arg_flags[arg_no] |= BTF_FMODEL_NULLABLE_ARG;
299 		} else if (is_nullable) {
300 			info->reg_type = PTR_TRUSTED | PTR_TO_BTF_ID | PTR_MAYBE_NULL;
301 		} else if (is_refcounted) {
302 			info->reg_type = PTR_TRUSTED | PTR_TO_BTF_ID;
303 			info->refcounted = true;
304 		}
305 
306 		info++;
307 		info_cnt++;
308 	}
309 
310 	if (info_cnt) {
311 		arg_info->info = info_buf;
312 		arg_info->cnt = info_cnt;
313 	} else {
314 		kfree(info_buf);
315 	}
316 
317 	return 0;
318 
319 err_out:
320 	kfree(info_buf);
321 
322 	return -EINVAL;
323 }
324 
325 /* Clean up the arg_info in a struct bpf_struct_ops_desc. */
326 void bpf_struct_ops_desc_release(struct bpf_struct_ops_desc *st_ops_desc)
327 {
328 	struct bpf_struct_ops_arg_info *arg_info;
329 	int i;
330 
331 	arg_info = st_ops_desc->arg_info;
332 	for (i = 0; i < btf_type_vlen(st_ops_desc->type); i++)
333 		kfree(arg_info[i].info);
334 
335 	kfree(arg_info);
336 }
337 
338 static bool is_module_member(const struct btf *btf, u32 id)
339 {
340 	const struct btf_type *t;
341 
342 	t = btf_type_resolve_ptr(btf, id, NULL);
343 	if (!t)
344 		return false;
345 
346 	if (!__btf_type_is_struct(t) && !btf_type_is_fwd(t))
347 		return false;
348 
349 	return !strcmp(btf_name_by_offset(btf, t->name_off), "module");
350 }
351 
352 int bpf_struct_ops_supported(const struct bpf_struct_ops *st_ops, u32 moff)
353 {
354 	void *func_ptr = *(void **)(st_ops->cfi_stubs + moff);
355 
356 	return func_ptr ? 0 : -ENOTSUPP;
357 }
358 
359 int bpf_struct_ops_desc_init(struct bpf_struct_ops_desc *st_ops_desc,
360 			     struct btf *btf,
361 			     struct bpf_verifier_log *log)
362 {
363 	struct bpf_struct_ops *st_ops = st_ops_desc->st_ops;
364 	struct bpf_struct_ops_arg_info *arg_info;
365 	const struct btf_member *member;
366 	const struct btf_type *t;
367 	s32 type_id, value_id;
368 	char value_name[128];
369 	const char *mname;
370 	int i, err;
371 
372 	if (strlen(st_ops->name) + VALUE_PREFIX_LEN >=
373 	    sizeof(value_name)) {
374 		pr_warn("struct_ops name %s is too long\n",
375 			st_ops->name);
376 		return -EINVAL;
377 	}
378 	sprintf(value_name, "%s%s", VALUE_PREFIX, st_ops->name);
379 
380 	if (!st_ops->cfi_stubs) {
381 		pr_warn("struct_ops for %s has no cfi_stubs\n", st_ops->name);
382 		return -EINVAL;
383 	}
384 
385 	type_id = btf_find_by_name_kind(btf, st_ops->name,
386 					BTF_KIND_STRUCT);
387 	if (type_id < 0) {
388 		pr_warn("Cannot find struct %s in %s\n",
389 			st_ops->name, btf_get_name(btf));
390 		return -EINVAL;
391 	}
392 	t = btf_type_by_id(btf, type_id);
393 	if (btf_type_vlen(t) > BPF_STRUCT_OPS_MAX_NR_MEMBERS) {
394 		pr_warn("Cannot support #%u members in struct %s\n",
395 			btf_type_vlen(t), st_ops->name);
396 		return -EINVAL;
397 	}
398 
399 	value_id = btf_find_by_name_kind(btf, value_name,
400 					 BTF_KIND_STRUCT);
401 	if (value_id < 0) {
402 		pr_warn("Cannot find struct %s in %s\n",
403 			value_name, btf_get_name(btf));
404 		return -EINVAL;
405 	}
406 	if (!is_valid_value_type(btf, value_id, t, value_name))
407 		return -EINVAL;
408 
409 	arg_info = kzalloc_objs(*arg_info, btf_type_vlen(t));
410 	if (!arg_info)
411 		return -ENOMEM;
412 
413 	st_ops_desc->arg_info = arg_info;
414 	st_ops_desc->type = t;
415 	st_ops_desc->type_id = type_id;
416 	st_ops_desc->value_id = value_id;
417 	st_ops_desc->value_type = btf_type_by_id(btf, value_id);
418 
419 	for_each_member(i, t, member) {
420 		const struct btf_type *func_proto, *ret_type;
421 		void **stub_func_addr;
422 		u32 moff;
423 
424 		moff = __btf_member_bit_offset(t, member) / 8;
425 		mname = btf_name_by_offset(btf, member->name_off);
426 		if (!*mname) {
427 			pr_warn("anon member in struct %s is not supported\n",
428 				st_ops->name);
429 			err = -EOPNOTSUPP;
430 			goto errout;
431 		}
432 
433 		if (__btf_member_bitfield_size(t, member)) {
434 			pr_warn("bit field member %s in struct %s is not supported\n",
435 				mname, st_ops->name);
436 			err = -EOPNOTSUPP;
437 			goto errout;
438 		}
439 
440 		if (!st_ops_ids[IDX_MODULE_ID] && is_module_member(btf, member->type)) {
441 			pr_warn("'struct module' btf id not found. Is CONFIG_MODULES enabled? bpf_struct_ops '%s' needs module support.\n",
442 				st_ops->name);
443 			err = -EOPNOTSUPP;
444 			goto errout;
445 		}
446 
447 		func_proto = btf_type_resolve_func_ptr(btf,
448 						       member->type,
449 						       NULL);
450 
451 		/* The member is not a function pointer or
452 		 * the function pointer is not supported.
453 		 */
454 		if (!func_proto || bpf_struct_ops_supported(st_ops, moff))
455 			continue;
456 
457 		if (func_proto->type) {
458 			ret_type = btf_type_resolve_ptr(btf, func_proto->type, NULL);
459 			if (ret_type && !__btf_type_is_struct(ret_type)) {
460 				pr_warn("func ptr %s in struct %s returns non-struct pointer, which is not supported\n",
461 					mname, st_ops->name);
462 				err = -EOPNOTSUPP;
463 				goto errout;
464 			}
465 		}
466 
467 		if (btf_distill_func_proto(log, btf,
468 					   func_proto, mname,
469 					   &st_ops->func_models[i])) {
470 			pr_warn("Error in parsing func ptr %s in struct %s\n",
471 				mname, st_ops->name);
472 			err = -EINVAL;
473 			goto errout;
474 		}
475 
476 		/*
477 		 * A >8 byte return value is passed back in a register pair,
478 		 * which the struct_ops trampoline does not preserve (only
479 		 * 8 bytes of the return value are saved and restored).
480 		 */
481 		if (st_ops->func_models[i].ret_size > 8) {
482 			pr_warn("func ptr %s in struct %s has a >8 byte return value, which is not supported\n",
483 				mname, st_ops->name);
484 			err = -EOPNOTSUPP;
485 			goto errout;
486 		}
487 
488 		stub_func_addr = *(void **)(st_ops->cfi_stubs + moff);
489 		err = prepare_arg_info(btf, st_ops->name, mname,
490 				       func_proto, stub_func_addr,
491 				       &st_ops->func_models[i],
492 				       arg_info + i);
493 		if (err)
494 			goto errout;
495 	}
496 
497 	if (st_ops->init(btf)) {
498 		pr_warn("Error in init bpf_struct_ops %s\n",
499 			st_ops->name);
500 		err = -EINVAL;
501 		goto errout;
502 	}
503 
504 	return 0;
505 
506 errout:
507 	bpf_struct_ops_desc_release(st_ops_desc);
508 
509 	return err;
510 }
511 
512 static int bpf_struct_ops_map_get_next_key(struct bpf_map *map, void *key,
513 					   void *next_key)
514 {
515 	if (key && *(u32 *)key == 0)
516 		return -ENOENT;
517 
518 	*(u32 *)next_key = 0;
519 	return 0;
520 }
521 
522 int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map, void *key,
523 				       void *value)
524 {
525 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
526 	struct bpf_struct_ops_value *uvalue, *kvalue;
527 	enum bpf_struct_ops_state state;
528 	s64 refcnt;
529 
530 	if (unlikely(*(u32 *)key != 0))
531 		return -ENOENT;
532 
533 	kvalue = &st_map->kvalue;
534 	/* Pair with smp_store_release() during map_update */
535 	state = smp_load_acquire(&kvalue->common.state);
536 	if (state == BPF_STRUCT_OPS_STATE_INIT) {
537 		memset(value, 0, map->value_size);
538 		return 0;
539 	}
540 
541 	/* No lock is needed.  state and refcnt do not need
542 	 * to be updated together under atomic context.
543 	 */
544 	uvalue = value;
545 	memcpy(uvalue, st_map->uvalue, map->value_size);
546 	uvalue->common.state = state;
547 
548 	/* This value offers the user space a general estimate of how
549 	 * many sockets are still utilizing this struct_ops for TCP
550 	 * congestion control. The number might not be exact, but it
551 	 * should sufficiently meet our present goals.
552 	 */
553 	refcnt = atomic64_read(&map->refcnt) - atomic64_read(&map->usercnt);
554 	refcount_set(&uvalue->common.refcnt, max_t(s64, refcnt, 0));
555 
556 	return 0;
557 }
558 
559 static void *bpf_struct_ops_map_lookup_elem(struct bpf_map *map, void *key)
560 {
561 	return ERR_PTR(-EINVAL);
562 }
563 
564 static void bpf_struct_ops_map_put_progs(struct bpf_struct_ops_map *st_map)
565 {
566 	u32 i;
567 
568 	for (i = 0; i < st_map->funcs_cnt; i++) {
569 		if (!st_map->links[i])
570 			break;
571 		bpf_link_put(st_map->links[i]);
572 		st_map->links[i] = NULL;
573 	}
574 }
575 
576 static void bpf_struct_ops_map_dissoc_progs(struct bpf_struct_ops_map *st_map)
577 {
578 	u32 i;
579 
580 	for (i = 0; i < st_map->funcs_cnt; i++) {
581 		if (!st_map->links[i])
582 			break;
583 		bpf_prog_disassoc_struct_ops(st_map->links[i]->prog);
584 	}
585 }
586 
587 static void bpf_struct_ops_map_free_image(struct bpf_struct_ops_map *st_map)
588 {
589 	int i;
590 
591 	for (i = 0; i < st_map->image_pages_cnt; i++)
592 		bpf_struct_ops_image_free(st_map->image_pages[i]);
593 	st_map->image_pages_cnt = 0;
594 }
595 
596 static int check_zero_holes(const struct btf *btf, const struct btf_type *t, void *data)
597 {
598 	const struct btf_member *member;
599 	u32 i, moff, msize, prev_mend = 0;
600 	const struct btf_type *mtype;
601 
602 	for_each_member(i, t, member) {
603 		moff = __btf_member_bit_offset(t, member) / 8;
604 		if (moff > prev_mend &&
605 		    memchr_inv(data + prev_mend, 0, moff - prev_mend))
606 			return -EINVAL;
607 
608 		mtype = btf_type_by_id(btf, member->type);
609 		mtype = btf_resolve_size(btf, mtype, &msize);
610 		if (IS_ERR(mtype))
611 			return PTR_ERR(mtype);
612 		prev_mend = moff + msize;
613 	}
614 
615 	if (t->size > prev_mend &&
616 	    memchr_inv(data + prev_mend, 0, t->size - prev_mend))
617 		return -EINVAL;
618 
619 	return 0;
620 }
621 
622 static void bpf_struct_ops_link_release(struct bpf_link *link)
623 {
624 }
625 
626 static void bpf_struct_ops_link_dealloc(struct bpf_link *link)
627 {
628 	struct bpf_tramp_link *tlink = container_of(link, struct bpf_tramp_link, link);
629 
630 	kfree(tlink);
631 }
632 
633 const struct bpf_link_ops bpf_struct_ops_link_lops = {
634 	.release = bpf_struct_ops_link_release,
635 	.dealloc = bpf_struct_ops_link_dealloc,
636 };
637 
638 int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes,
639 				      struct bpf_tramp_node *node,
640 				      const struct btf_func_model *model,
641 				      void *stub_func,
642 				      void **_image, u32 *_image_off,
643 				      bool allow_alloc)
644 {
645 	u32 image_off = *_image_off, flags = BPF_TRAMP_F_INDIRECT;
646 	void *image = *_image;
647 	int size;
648 
649 	tnodes[BPF_TRAMP_FENTRY].nodes[0] = node;
650 	tnodes[BPF_TRAMP_FENTRY].nr_nodes = 1;
651 
652 	if (model->ret_size > 0)
653 		flags |= BPF_TRAMP_F_RET_FENTRY_RET;
654 
655 	size = arch_bpf_trampoline_size(model, flags, tnodes, stub_func);
656 	if (size <= 0)
657 		return size ? : -EFAULT;
658 
659 	/* Allocate image buffer if necessary */
660 	if (!image || size > PAGE_SIZE - image_off) {
661 		if (!allow_alloc)
662 			return -E2BIG;
663 
664 		image = bpf_struct_ops_image_alloc();
665 		if (IS_ERR(image))
666 			return PTR_ERR(image);
667 		image_off = 0;
668 	}
669 
670 	size = arch_prepare_bpf_trampoline(NULL, image + image_off,
671 					   image + image_off + size,
672 					   model, flags, tnodes, stub_func);
673 	if (size <= 0) {
674 		if (image != *_image)
675 			bpf_struct_ops_image_free(image);
676 		return size ? : -EFAULT;
677 	}
678 
679 	*_image = image;
680 	*_image_off = image_off + size;
681 	return 0;
682 }
683 
684 static void bpf_struct_ops_ksym_init(const char *tname, const char *mname,
685 				     void *image, unsigned int size,
686 				     struct bpf_ksym *ksym)
687 {
688 	snprintf(ksym->name, KSYM_NAME_LEN, "bpf__%s_%s", tname, mname);
689 	INIT_LIST_HEAD_RCU(&ksym->lnode);
690 	bpf_image_ksym_init(image, size, ksym);
691 }
692 
693 static void bpf_struct_ops_map_add_ksyms(struct bpf_struct_ops_map *st_map)
694 {
695 	u32 i;
696 
697 	for (i = 0; i < st_map->funcs_cnt; i++) {
698 		if (!st_map->ksyms[i])
699 			break;
700 		bpf_image_ksym_add(st_map->ksyms[i]);
701 	}
702 }
703 
704 static void bpf_struct_ops_map_del_ksyms(struct bpf_struct_ops_map *st_map)
705 {
706 	u32 i;
707 
708 	for (i = 0; i < st_map->funcs_cnt; i++) {
709 		if (!st_map->ksyms[i])
710 			break;
711 		bpf_image_ksym_del(st_map->ksyms[i]);
712 	}
713 }
714 
715 static void bpf_struct_ops_map_free_ksyms(struct bpf_struct_ops_map *st_map)
716 {
717 	u32 i;
718 
719 	for (i = 0; i < st_map->funcs_cnt; i++) {
720 		if (!st_map->ksyms[i])
721 			break;
722 		kfree(st_map->ksyms[i]);
723 		st_map->ksyms[i] = NULL;
724 	}
725 }
726 
727 static long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key,
728 					   void *value, u64 flags)
729 {
730 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
731 	const struct bpf_struct_ops_desc *st_ops_desc = st_map->st_ops_desc;
732 	const struct bpf_struct_ops *st_ops = st_ops_desc->st_ops;
733 	struct bpf_struct_ops_value *uvalue, *kvalue;
734 	const struct btf_type *module_type;
735 	const struct btf_member *member;
736 	const struct btf_type *t = st_ops_desc->type;
737 	struct bpf_tramp_nodes *tnodes;
738 	void *udata, *kdata;
739 	int prog_fd, err;
740 	u32 i, trampoline_start, image_off = 0;
741 	void *cur_image = NULL, *image = NULL;
742 	struct bpf_link **plink;
743 	struct bpf_ksym **pksym;
744 	const char *tname, *mname;
745 
746 	if (flags)
747 		return -EINVAL;
748 
749 	if (*(u32 *)key != 0)
750 		return -E2BIG;
751 
752 	err = check_zero_holes(st_map->btf, st_ops_desc->value_type, value);
753 	if (err)
754 		return err;
755 
756 	uvalue = value;
757 	err = check_zero_holes(st_map->btf, t, uvalue->data);
758 	if (err)
759 		return err;
760 
761 	if (uvalue->common.state || refcount_read(&uvalue->common.refcnt))
762 		return -EINVAL;
763 
764 	tnodes = kzalloc_objs(*tnodes, BPF_TRAMP_MAX);
765 	if (!tnodes)
766 		return -ENOMEM;
767 
768 	uvalue = (struct bpf_struct_ops_value *)st_map->uvalue;
769 	kvalue = (struct bpf_struct_ops_value *)&st_map->kvalue;
770 
771 	mutex_lock(&st_map->lock);
772 
773 	if (kvalue->common.state != BPF_STRUCT_OPS_STATE_INIT) {
774 		err = -EBUSY;
775 		goto unlock;
776 	}
777 
778 	memcpy(uvalue, value, map->value_size);
779 
780 	udata = &uvalue->data;
781 	kdata = &kvalue->data;
782 
783 	plink = st_map->links;
784 	pksym = st_map->ksyms;
785 	tname = btf_name_by_offset(st_map->btf, t->name_off);
786 	module_type = btf_type_by_id(btf_vmlinux, st_ops_ids[IDX_MODULE_ID]);
787 	for_each_member(i, t, member) {
788 		const struct btf_type *mtype, *ptype;
789 		struct bpf_prog *prog;
790 		struct bpf_tramp_link *link;
791 		struct bpf_ksym *ksym;
792 		u32 moff;
793 
794 		moff = __btf_member_bit_offset(t, member) / 8;
795 		mname = btf_name_by_offset(st_map->btf, member->name_off);
796 		ptype = btf_type_resolve_ptr(st_map->btf, member->type, NULL);
797 		if (ptype == module_type) {
798 			if (*(void **)(udata + moff))
799 				goto reset_unlock;
800 			*(void **)(kdata + moff) = BPF_MODULE_OWNER;
801 			continue;
802 		}
803 
804 		err = st_ops->init_member(t, member, kdata, udata);
805 		if (err < 0)
806 			goto reset_unlock;
807 
808 		/* The ->init_member() has handled this member */
809 		if (err > 0)
810 			continue;
811 
812 		/* If st_ops->init_member does not handle it,
813 		 * we will only handle func ptrs and zero-ed members
814 		 * here.  Reject everything else.
815 		 */
816 
817 		/* All non func ptr member must be 0 */
818 		if (!ptype || !btf_type_is_func_proto(ptype)) {
819 			u32 msize;
820 
821 			mtype = btf_type_by_id(st_map->btf, member->type);
822 			mtype = btf_resolve_size(st_map->btf, mtype, &msize);
823 			if (IS_ERR(mtype)) {
824 				err = PTR_ERR(mtype);
825 				goto reset_unlock;
826 			}
827 
828 			if (memchr_inv(udata + moff, 0, msize)) {
829 				err = -EINVAL;
830 				goto reset_unlock;
831 			}
832 
833 			continue;
834 		}
835 
836 		prog_fd = (int)(*(unsigned long *)(udata + moff));
837 		/* Similar check as the attr->attach_prog_fd */
838 		if (!prog_fd)
839 			continue;
840 
841 		prog = bpf_prog_get(prog_fd);
842 		if (IS_ERR(prog)) {
843 			err = PTR_ERR(prog);
844 			goto reset_unlock;
845 		}
846 
847 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
848 		    prog->aux->attach_btf_id != st_ops_desc->type_id ||
849 		    prog->expected_attach_type != i) {
850 			bpf_prog_put(prog);
851 			err = -EINVAL;
852 			goto reset_unlock;
853 		}
854 
855 		link = kzalloc_obj(*link, GFP_USER);
856 		if (!link) {
857 			bpf_prog_put(prog);
858 			err = -ENOMEM;
859 			goto reset_unlock;
860 		}
861 		bpf_tramp_link_init(link, BPF_LINK_TYPE_STRUCT_OPS,
862 			      &bpf_struct_ops_link_lops, prog, prog->expected_attach_type, 0);
863 
864 		*plink++ = &link->link;
865 
866 		/* Poison pointer on error instead of return for backward compatibility */
867 		bpf_prog_assoc_struct_ops(prog, &st_map->map);
868 
869 		ksym = kzalloc_obj(*ksym, GFP_USER);
870 		if (!ksym) {
871 			err = -ENOMEM;
872 			goto reset_unlock;
873 		}
874 		*pksym++ = ksym;
875 
876 		trampoline_start = image_off;
877 		err = bpf_struct_ops_prepare_trampoline(tnodes, &link->node,
878 						&st_ops->func_models[i],
879 						*(void **)(st_ops->cfi_stubs + moff),
880 						&image, &image_off,
881 						st_map->image_pages_cnt < MAX_TRAMP_IMAGE_PAGES);
882 		if (err)
883 			goto reset_unlock;
884 
885 		if (cur_image != image) {
886 			st_map->image_pages[st_map->image_pages_cnt++] = image;
887 			cur_image = image;
888 			trampoline_start = 0;
889 		}
890 
891 		*(void **)(kdata + moff) = image + trampoline_start + cfi_get_offset();
892 
893 		/* put prog_id to udata */
894 		*(unsigned long *)(udata + moff) = prog->aux->id;
895 
896 		/* init ksym for this trampoline */
897 		bpf_struct_ops_ksym_init(tname, mname,
898 					 image + trampoline_start,
899 					 image_off - trampoline_start,
900 					 ksym);
901 	}
902 
903 	if (st_ops->validate) {
904 		err = st_ops->validate(kdata);
905 		if (err)
906 			goto reset_unlock;
907 	}
908 	for (i = 0; i < st_map->image_pages_cnt; i++) {
909 		err = arch_protect_bpf_trampoline(st_map->image_pages[i],
910 						  PAGE_SIZE);
911 		if (err)
912 			goto reset_unlock;
913 	}
914 
915 	if (st_map->map.map_flags & BPF_F_LINK) {
916 		err = 0;
917 		/* Let bpf_link handle registration & unregistration.
918 		 *
919 		 * Pair with smp_load_acquire() during lookup_elem().
920 		 */
921 		smp_store_release(&kvalue->common.state, BPF_STRUCT_OPS_STATE_READY);
922 		goto unlock;
923 	}
924 
925 	err = st_ops->reg(kdata, NULL);
926 	if (likely(!err)) {
927 		/* This refcnt increment on the map here after
928 		 * 'st_ops->reg()' is secure since the state of the
929 		 * map must be set to INIT at this moment, and thus
930 		 * bpf_struct_ops_map_delete_elem() can't unregister
931 		 * or transition it to TOBEFREE concurrently.
932 		 */
933 		bpf_map_inc(map);
934 		/* Pair with smp_load_acquire() during lookup_elem().
935 		 * It ensures the above udata updates (e.g. prog->aux->id)
936 		 * can be seen once BPF_STRUCT_OPS_STATE_INUSE is set.
937 		 */
938 		smp_store_release(&kvalue->common.state, BPF_STRUCT_OPS_STATE_INUSE);
939 		goto unlock;
940 	}
941 
942 	/* Error during st_ops->reg(). Can happen if this struct_ops needs to be
943 	 * verified as a whole, after all init_member() calls. Can also happen if
944 	 * there was a race in registering the struct_ops (under the same name) to
945 	 * a sub-system through different struct_ops's maps.
946 	 */
947 
948 reset_unlock:
949 	bpf_struct_ops_map_free_ksyms(st_map);
950 	bpf_struct_ops_map_free_image(st_map);
951 	bpf_struct_ops_map_dissoc_progs(st_map);
952 	bpf_struct_ops_map_put_progs(st_map);
953 	memset(uvalue, 0, map->value_size);
954 	memset(kvalue, 0, map->value_size);
955 unlock:
956 	kfree(tnodes);
957 	mutex_unlock(&st_map->lock);
958 	if (!err)
959 		bpf_struct_ops_map_add_ksyms(st_map);
960 	return err;
961 }
962 
963 static long bpf_struct_ops_map_delete_elem(struct bpf_map *map, void *key)
964 {
965 	enum bpf_struct_ops_state prev_state;
966 	struct bpf_struct_ops_map *st_map;
967 
968 	st_map = (struct bpf_struct_ops_map *)map;
969 	if (st_map->map.map_flags & BPF_F_LINK)
970 		return -EOPNOTSUPP;
971 
972 	prev_state = cmpxchg(&st_map->kvalue.common.state,
973 			     BPF_STRUCT_OPS_STATE_INUSE,
974 			     BPF_STRUCT_OPS_STATE_TOBEFREE);
975 	switch (prev_state) {
976 	case BPF_STRUCT_OPS_STATE_INUSE:
977 		st_map->st_ops_desc->st_ops->unreg(&st_map->kvalue.data, NULL);
978 		bpf_map_put(map);
979 		return 0;
980 	case BPF_STRUCT_OPS_STATE_TOBEFREE:
981 		return -EINPROGRESS;
982 	case BPF_STRUCT_OPS_STATE_INIT:
983 		return -ENOENT;
984 	default:
985 		WARN_ON_ONCE(1);
986 		/* Should never happen.  Treat it as not found. */
987 		return -ENOENT;
988 	}
989 }
990 
991 static void bpf_struct_ops_map_seq_show_elem(struct bpf_map *map, void *key,
992 					     struct seq_file *m)
993 {
994 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
995 	void *value;
996 	int err;
997 
998 	value = kmalloc(map->value_size, GFP_USER | __GFP_NOWARN);
999 	if (!value)
1000 		return;
1001 
1002 	err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
1003 	if (!err) {
1004 		btf_type_seq_show(st_map->btf,
1005 				  map->btf_vmlinux_value_type_id,
1006 				  value, m);
1007 		seq_putc(m, '\n');
1008 	}
1009 
1010 	kfree(value);
1011 }
1012 
1013 static void __bpf_struct_ops_map_free(struct bpf_map *map)
1014 {
1015 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1016 
1017 	if (st_map->links)
1018 		bpf_struct_ops_map_put_progs(st_map);
1019 	if (st_map->ksyms)
1020 		bpf_struct_ops_map_free_ksyms(st_map);
1021 	bpf_map_area_free(st_map->links);
1022 	bpf_map_area_free(st_map->ksyms);
1023 	bpf_struct_ops_map_free_image(st_map);
1024 	bpf_map_area_free(st_map->uvalue);
1025 	bpf_map_area_free(st_map);
1026 }
1027 
1028 static void bpf_struct_ops_map_free_pre_rcu(struct bpf_map *map)
1029 {
1030 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1031 
1032 	bpf_struct_ops_map_del_ksyms(st_map);
1033 }
1034 
1035 static void bpf_struct_ops_map_free(struct bpf_map *map)
1036 {
1037 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1038 	struct bpf_struct_ops *st_ops = st_map->st_ops_desc->st_ops;
1039 	bool tasks_rcu = st_ops->free_after_tasks_rcu_gp;
1040 
1041 	/* st_ops->owner was acquired during map_alloc to implicitly holds
1042 	 * the btf's refcnt. The acquire was only done when btf_is_module()
1043 	 * st_map->btf cannot be NULL here.
1044 	 */
1045 	if (btf_is_module(st_map->btf))
1046 		module_put(st_map->st_ops_desc->st_ops->owner);
1047 
1048 	bpf_struct_ops_map_dissoc_progs(st_map);
1049 
1050 	if (tasks_rcu && IS_ENABLED(CONFIG_TASKS_RCU))
1051 		synchronize_rcu_tasks();
1052 
1053 	__bpf_struct_ops_map_free(map);
1054 }
1055 
1056 static int bpf_struct_ops_map_alloc_check(union bpf_attr *attr)
1057 {
1058 	if (attr->key_size != sizeof(unsigned int) || attr->max_entries != 1 ||
1059 	    (attr->map_flags & ~(BPF_F_LINK | BPF_F_VTYPE_BTF_OBJ_FD)) ||
1060 	    !attr->btf_vmlinux_value_type_id)
1061 		return -EINVAL;
1062 	return 0;
1063 }
1064 
1065 static u32 count_func_ptrs(const struct btf *btf, const struct btf_type *t)
1066 {
1067 	int i;
1068 	u32 count;
1069 	const struct btf_member *member;
1070 
1071 	count = 0;
1072 	for_each_member(i, t, member)
1073 		if (btf_type_resolve_func_ptr(btf, member->type, NULL))
1074 			count++;
1075 	return count;
1076 }
1077 
1078 static struct bpf_map *bpf_struct_ops_map_alloc(union bpf_attr *attr)
1079 {
1080 	const struct bpf_struct_ops_desc *st_ops_desc;
1081 	size_t st_map_size;
1082 	struct bpf_struct_ops_map *st_map;
1083 	const struct btf_type *t, *vt;
1084 	struct module *mod = NULL;
1085 	struct bpf_map *map;
1086 	struct btf *btf;
1087 	int ret;
1088 
1089 	if (attr->map_flags & BPF_F_VTYPE_BTF_OBJ_FD) {
1090 		/* The map holds btf for its whole life time. */
1091 		btf = btf_get_by_fd(attr->value_type_btf_obj_fd);
1092 		if (IS_ERR(btf))
1093 			return ERR_CAST(btf);
1094 		if (!btf_is_module(btf)) {
1095 			btf_put(btf);
1096 			return ERR_PTR(-EINVAL);
1097 		}
1098 
1099 		mod = btf_try_get_module(btf);
1100 		/* mod holds a refcnt to btf. We don't need an extra refcnt
1101 		 * here.
1102 		 */
1103 		btf_put(btf);
1104 		if (!mod)
1105 			return ERR_PTR(-EINVAL);
1106 	} else {
1107 		btf = bpf_get_btf_vmlinux();
1108 		if (IS_ERR(btf))
1109 			return ERR_CAST(btf);
1110 		if (!btf)
1111 			return ERR_PTR(-ENOTSUPP);
1112 	}
1113 
1114 	st_ops_desc = bpf_struct_ops_find_value(btf, attr->btf_vmlinux_value_type_id);
1115 	if (!st_ops_desc) {
1116 		ret = -ENOTSUPP;
1117 		goto errout;
1118 	}
1119 
1120 	if (st_ops_desc->st_ops->cgroup_atype && !(attr->map_flags & BPF_F_LINK)) {
1121 		ret = -EOPNOTSUPP;
1122 		goto errout;
1123 	}
1124 
1125 	vt = st_ops_desc->value_type;
1126 	if (attr->value_size != vt->size) {
1127 		ret = -EINVAL;
1128 		goto errout;
1129 	}
1130 
1131 	t = st_ops_desc->type;
1132 
1133 	st_map_size = sizeof(*st_map) +
1134 		/* kvalue stores the
1135 		 * struct bpf_struct_ops_tcp_congestions_ops
1136 		 */
1137 		(vt->size - sizeof(struct bpf_struct_ops_value));
1138 
1139 	st_map = bpf_map_area_alloc(st_map_size, NUMA_NO_NODE);
1140 	if (!st_map) {
1141 		ret = -ENOMEM;
1142 		goto errout;
1143 	}
1144 
1145 	st_map->st_ops_desc = st_ops_desc;
1146 	map = &st_map->map;
1147 
1148 	st_map->uvalue = bpf_map_area_alloc(vt->size, NUMA_NO_NODE);
1149 	st_map->funcs_cnt = count_func_ptrs(btf, t);
1150 	st_map->links =
1151 		bpf_map_area_alloc(st_map->funcs_cnt * sizeof(struct bpf_link *),
1152 				   NUMA_NO_NODE);
1153 
1154 	st_map->ksyms =
1155 		bpf_map_area_alloc(st_map->funcs_cnt * sizeof(struct bpf_ksym *),
1156 				   NUMA_NO_NODE);
1157 	if (!st_map->uvalue || !st_map->links || !st_map->ksyms) {
1158 		ret = -ENOMEM;
1159 		goto errout_free;
1160 	}
1161 	st_map->btf = btf;
1162 
1163 	mutex_init(&st_map->lock);
1164 	bpf_map_init_from_attr(map, attr);
1165 	map->free_after_mult_rcu_gp = st_ops_desc->st_ops->free_after_mult_rcu_gp;
1166 	map->free_after_rcu_gp = true;
1167 
1168 	return map;
1169 
1170 errout_free:
1171 	__bpf_struct_ops_map_free(map);
1172 errout:
1173 	module_put(mod);
1174 
1175 	return ERR_PTR(ret);
1176 }
1177 
1178 static u64 bpf_struct_ops_map_mem_usage(const struct bpf_map *map)
1179 {
1180 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1181 	const struct bpf_struct_ops_desc *st_ops_desc = st_map->st_ops_desc;
1182 	const struct btf_type *vt = st_ops_desc->value_type;
1183 	u64 usage;
1184 
1185 	usage = sizeof(*st_map) +
1186 			vt->size - sizeof(struct bpf_struct_ops_value);
1187 	usage += vt->size;
1188 	usage += st_map->funcs_cnt * sizeof(struct bpf_link *);
1189 	usage += st_map->funcs_cnt * sizeof(struct bpf_ksym *);
1190 	usage += PAGE_SIZE;
1191 	return usage;
1192 }
1193 
1194 BTF_ID_LIST_SINGLE(bpf_struct_ops_map_btf_ids, struct, bpf_struct_ops_map)
1195 const struct bpf_map_ops bpf_struct_ops_map_ops = {
1196 	.map_alloc_check = bpf_struct_ops_map_alloc_check,
1197 	.map_alloc = bpf_struct_ops_map_alloc,
1198 	.map_free = bpf_struct_ops_map_free,
1199 	.map_free_pre_rcu = bpf_struct_ops_map_free_pre_rcu,
1200 	.map_get_next_key = bpf_struct_ops_map_get_next_key,
1201 	.map_lookup_elem = bpf_struct_ops_map_lookup_elem,
1202 	.map_delete_elem = bpf_struct_ops_map_delete_elem,
1203 	.map_update_elem = bpf_struct_ops_map_update_elem,
1204 	.map_seq_show_elem = bpf_struct_ops_map_seq_show_elem,
1205 	.map_mem_usage = bpf_struct_ops_map_mem_usage,
1206 	.map_btf_id = &bpf_struct_ops_map_btf_ids[0],
1207 };
1208 
1209 /* "const void *" because some subsystem is
1210  * passing a const (e.g. const struct tcp_congestion_ops *)
1211  */
1212 bool bpf_struct_ops_get(const void *kdata)
1213 {
1214 	struct bpf_struct_ops_value *kvalue;
1215 	struct bpf_struct_ops_map *st_map;
1216 	struct bpf_map *map;
1217 
1218 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
1219 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
1220 
1221 	map = __bpf_map_inc_not_zero(&st_map->map, false);
1222 	return !IS_ERR(map);
1223 }
1224 EXPORT_SYMBOL_GPL(bpf_struct_ops_get);
1225 
1226 void bpf_struct_ops_put(const void *kdata)
1227 {
1228 	struct bpf_struct_ops_value *kvalue;
1229 	struct bpf_struct_ops_map *st_map;
1230 
1231 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
1232 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
1233 
1234 	bpf_map_put(&st_map->map);
1235 }
1236 EXPORT_SYMBOL_GPL(bpf_struct_ops_put);
1237 
1238 u32 bpf_struct_ops_id(const void *kdata)
1239 {
1240 	struct bpf_struct_ops_value *kvalue;
1241 	struct bpf_struct_ops_map *st_map;
1242 
1243 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
1244 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
1245 
1246 	return st_map->map.id;
1247 }
1248 EXPORT_SYMBOL_GPL(bpf_struct_ops_id);
1249 
1250 /**
1251  * bpf_struct_ops_for_each_prog - Invoke @cb for each member prog
1252  * @kdata: kernel-side struct_ops vmtable (the @kdata arg to ->reg/->update/->unreg)
1253  * @cb: callback invoked once per member prog; non-zero return stops iteration
1254  * @data: opaque argument passed to @cb
1255  *
1256  * Walks the struct_ops member progs registered on the map containing @kdata.
1257  * Intended for use from struct_ops ->reg() callbacks (and similar) that need to
1258  * inspect the loaded BPF programs (for example to discover maps they reference
1259  * via @prog->aux->used_maps).
1260  *
1261  * Return 0 if iteration completed, otherwise the first non-zero @cb return.
1262  */
1263 int bpf_struct_ops_for_each_prog(const void *kdata,
1264 				 int (*cb)(struct bpf_prog *prog, void *data),
1265 				 void *data)
1266 {
1267 	struct bpf_struct_ops_value *kvalue;
1268 	struct bpf_struct_ops_map *st_map;
1269 	u32 i;
1270 	int ret;
1271 
1272 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
1273 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
1274 
1275 	for (i = 0; i < st_map->funcs_cnt; i++) {
1276 		if (!st_map->links[i])
1277 			continue;
1278 		ret = cb(st_map->links[i]->prog, data);
1279 		if (ret)
1280 			return ret;
1281 	}
1282 	return 0;
1283 }
1284 EXPORT_SYMBOL_GPL(bpf_struct_ops_for_each_prog);
1285 
1286 void *bpf_struct_ops_map_kdata(struct bpf_map *map)
1287 {
1288 	struct bpf_struct_ops_map *st_map;
1289 
1290 	st_map = container_of(map, struct bpf_struct_ops_map, map);
1291 	return st_map->kvalue.data;
1292 }
1293 
1294 int bpf_struct_ops_map_cgroup_atype(struct bpf_map *map)
1295 {
1296 	struct bpf_struct_ops_map *st_map;
1297 
1298 	st_map = container_of(map, struct bpf_struct_ops_map, map);
1299 	return st_map->st_ops_desc->st_ops->cgroup_atype;
1300 }
1301 
1302 void *bpf_struct_ops_map_cfi_stubs(struct bpf_map *map)
1303 {
1304 	struct bpf_struct_ops_map *st_map;
1305 
1306 	st_map = container_of(map, struct bpf_struct_ops_map, map);
1307 	return st_map->st_ops_desc->st_ops->cfi_stubs;
1308 }
1309 
1310 bool bpf_struct_ops_valid_to_reg(struct bpf_map *map)
1311 {
1312 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1313 
1314 	return map->map_type == BPF_MAP_TYPE_STRUCT_OPS &&
1315 		map->map_flags & BPF_F_LINK &&
1316 		/* Pair with smp_store_release() during map_update */
1317 		smp_load_acquire(&st_map->kvalue.common.state) == BPF_STRUCT_OPS_STATE_READY;
1318 }
1319 
1320 static void bpf_struct_ops_map_link_dealloc(struct bpf_link *link)
1321 {
1322 	struct bpf_struct_ops_link *st_link;
1323 	struct bpf_struct_ops_map *st_map;
1324 
1325 	st_link = container_of(link, struct bpf_struct_ops_link, link);
1326 	st_map = (struct bpf_struct_ops_map *)st_link->map;
1327 	if (st_map) {
1328 		st_map->st_ops_desc->st_ops->unreg(&st_map->kvalue.data, link);
1329 		bpf_map_put(&st_map->map);
1330 	}
1331 	kfree(st_link);
1332 }
1333 
1334 static void bpf_struct_ops_map_link_show_fdinfo(const struct bpf_link *link,
1335 					    struct seq_file *seq)
1336 {
1337 	struct bpf_struct_ops_link *st_link;
1338 	struct bpf_map *map;
1339 
1340 	st_link = container_of(link, struct bpf_struct_ops_link, link);
1341 	mutex_lock(&update_mutex);
1342 	map = st_link->map;
1343 	if (map)
1344 		seq_printf(seq, "map_id:\t%d\n", map->id);
1345 	mutex_unlock(&update_mutex);
1346 }
1347 
1348 static int bpf_struct_ops_map_link_fill_link_info(const struct bpf_link *link,
1349 					       struct bpf_link_info *info)
1350 {
1351 	struct bpf_struct_ops_link *st_link;
1352 	struct bpf_map *map;
1353 
1354 	st_link = container_of(link, struct bpf_struct_ops_link, link);
1355 	mutex_lock(&update_mutex);
1356 	map = st_link->map;
1357 	if (map)
1358 		info->struct_ops.map_id = map->id;
1359 	mutex_unlock(&update_mutex);
1360 	return 0;
1361 }
1362 
1363 int bpf_struct_ops_link_update_check(struct bpf_map *new_map,
1364 				     struct bpf_map *old_map,
1365 				     struct bpf_map *expected_old_map)
1366 {
1367 	struct bpf_struct_ops_map *st_map, *old_st_map;
1368 
1369 	if (!old_map)
1370 		return -ENOLINK;
1371 	if (expected_old_map && old_map != expected_old_map)
1372 		return -EPERM;
1373 
1374 	st_map = container_of(new_map, struct bpf_struct_ops_map, map);
1375 	old_st_map = container_of(old_map, struct bpf_struct_ops_map, map);
1376 	/* The new and old struct_ops must be the same type. */
1377 	if (st_map->st_ops_desc != old_st_map->st_ops_desc)
1378 		return -EINVAL;
1379 
1380 	return 0;
1381 }
1382 
1383 static int bpf_struct_ops_map_link_update(struct bpf_link *link, struct bpf_map *new_map,
1384 					  struct bpf_map *expected_old_map)
1385 {
1386 	struct bpf_struct_ops_map *st_map, *old_st_map;
1387 	struct bpf_map *old_map;
1388 	struct bpf_struct_ops_link *st_link;
1389 	int err;
1390 
1391 	st_link = container_of(link, struct bpf_struct_ops_link, link);
1392 	st_map = container_of(new_map, struct bpf_struct_ops_map, map);
1393 
1394 	if (!bpf_struct_ops_valid_to_reg(new_map))
1395 		return -EINVAL;
1396 
1397 	if (!st_map->st_ops_desc->st_ops->update)
1398 		return -EOPNOTSUPP;
1399 
1400 	mutex_lock(&update_mutex);
1401 	old_map = st_link->map;
1402 	err = bpf_struct_ops_link_update_check(new_map, old_map, expected_old_map);
1403 	if (err)
1404 		goto err_out;
1405 
1406 	old_st_map = container_of(old_map, struct bpf_struct_ops_map, map);
1407 
1408 	err = st_map->st_ops_desc->st_ops->update(st_map->kvalue.data, old_st_map->kvalue.data, link);
1409 	if (err)
1410 		goto err_out;
1411 
1412 	bpf_map_inc(new_map);
1413 	WRITE_ONCE(st_link->map, new_map);
1414 	bpf_map_put(old_map);
1415 
1416 err_out:
1417 	mutex_unlock(&update_mutex);
1418 
1419 	return err;
1420 }
1421 
1422 static int bpf_struct_ops_map_link_detach(struct bpf_link *link)
1423 {
1424 	struct bpf_struct_ops_link *st_link = container_of(link, struct bpf_struct_ops_link, link);
1425 	struct bpf_struct_ops_map *st_map;
1426 	struct bpf_map *map;
1427 
1428 	mutex_lock(&update_mutex);
1429 
1430 	map = st_link->map;
1431 	if (!map) {
1432 		mutex_unlock(&update_mutex);
1433 		return 0;
1434 	}
1435 	st_map = container_of(map, struct bpf_struct_ops_map, map);
1436 
1437 	st_map->st_ops_desc->st_ops->unreg(&st_map->kvalue.data, link);
1438 
1439 	WRITE_ONCE(st_link->map, NULL);
1440 	/* Pair with bpf_map_get() in bpf_struct_ops_link_create() or
1441 	 * bpf_map_inc() in bpf_struct_ops_map_link_update().
1442 	 */
1443 	bpf_map_put(&st_map->map);
1444 
1445 	mutex_unlock(&update_mutex);
1446 
1447 	wake_up_interruptible_poll(&st_link->wait_hup, EPOLLHUP);
1448 
1449 	return 0;
1450 }
1451 
1452 static __poll_t bpf_struct_ops_map_link_poll(struct file *file,
1453 					     struct poll_table_struct *pts)
1454 {
1455 	struct bpf_struct_ops_link *st_link = file->private_data;
1456 
1457 	poll_wait(file, &st_link->wait_hup, pts);
1458 
1459 	return READ_ONCE(st_link->map) ? 0 : EPOLLHUP;
1460 }
1461 
1462 static const struct bpf_link_ops bpf_struct_ops_map_lops = {
1463 	.dealloc = bpf_struct_ops_map_link_dealloc,
1464 	.detach = bpf_struct_ops_map_link_detach,
1465 	.show_fdinfo = bpf_struct_ops_map_link_show_fdinfo,
1466 	.fill_link_info = bpf_struct_ops_map_link_fill_link_info,
1467 	.update_map = bpf_struct_ops_map_link_update,
1468 	.poll = bpf_struct_ops_map_link_poll,
1469 };
1470 
1471 int bpf_struct_ops_link_create(union bpf_attr *attr)
1472 {
1473 	struct bpf_struct_ops_link *link = NULL;
1474 	struct bpf_link_primer link_primer;
1475 	struct bpf_struct_ops_map *st_map;
1476 	struct bpf_map *map;
1477 	int cgroup_atype;
1478 	int err;
1479 
1480 	map = bpf_map_get(attr->link_create.map_fd);
1481 	if (IS_ERR(map))
1482 		return PTR_ERR(map);
1483 
1484 	st_map = (struct bpf_struct_ops_map *)map;
1485 
1486 	if (!bpf_struct_ops_valid_to_reg(map)) {
1487 		err = -EINVAL;
1488 		goto err_out;
1489 	}
1490 
1491 	cgroup_atype = st_map->st_ops_desc->st_ops->cgroup_atype;
1492 	if (cgroup_atype) {
1493 		err = cgroup_bpf_struct_ops_attach(map, attr);
1494 		bpf_map_put(map);
1495 		return err;
1496 	}
1497 
1498 	if (memchr_inv(&attr->link_create.cgroup, 0, sizeof(attr->link_create.cgroup)) ||
1499 	    attr->link_create.target_fd) {
1500 		err = -EINVAL;
1501 		goto err_out;
1502 	}
1503 
1504 	link = kzalloc_obj(*link, GFP_USER);
1505 	if (!link) {
1506 		err = -ENOMEM;
1507 		goto err_out;
1508 	}
1509 	bpf_link_init(&link->link, BPF_LINK_TYPE_STRUCT_OPS, &bpf_struct_ops_map_lops, NULL,
1510 		      attr->link_create.attach_type);
1511 
1512 	err = bpf_link_prime(&link->link, &link_primer);
1513 	if (err)
1514 		goto err_out;
1515 
1516 	init_waitqueue_head(&link->wait_hup);
1517 
1518 	/* Hold the update_mutex such that the subsystem cannot
1519 	 * do link->ops->detach() before the link is fully initialized.
1520 	 */
1521 	mutex_lock(&update_mutex);
1522 	err = st_map->st_ops_desc->st_ops->reg(st_map->kvalue.data, &link->link);
1523 	if (err) {
1524 		mutex_unlock(&update_mutex);
1525 		bpf_link_cleanup(&link_primer);
1526 		link = NULL;
1527 		goto err_out;
1528 	}
1529 	link->map = map;
1530 	mutex_unlock(&update_mutex);
1531 
1532 	return bpf_link_settle(&link_primer);
1533 
1534 err_out:
1535 	bpf_map_put(map);
1536 	kfree(link);
1537 	return err;
1538 }
1539 
1540 int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_map *map)
1541 {
1542 	struct bpf_map *st_ops_assoc;
1543 
1544 	guard(mutex)(&prog->aux->st_ops_assoc_mutex);
1545 
1546 	st_ops_assoc = rcu_dereference_protected(prog->aux->st_ops_assoc,
1547 						 lockdep_is_held(&prog->aux->st_ops_assoc_mutex));
1548 	if (st_ops_assoc && st_ops_assoc == map)
1549 		return 0;
1550 
1551 	if (st_ops_assoc) {
1552 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1553 			return -EBUSY;
1554 
1555 		rcu_assign_pointer(prog->aux->st_ops_assoc, BPF_PTR_POISON);
1556 	} else {
1557 		/*
1558 		 * struct_ops map does not track associated non-struct_ops programs.
1559 		 * Bump the refcount to make sure st_ops_assoc is always valid.
1560 		 */
1561 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1562 			bpf_map_inc(map);
1563 
1564 		rcu_assign_pointer(prog->aux->st_ops_assoc, map);
1565 	}
1566 
1567 	return 0;
1568 }
1569 
1570 void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog)
1571 {
1572 	struct bpf_map *st_ops_assoc;
1573 
1574 	guard(mutex)(&prog->aux->st_ops_assoc_mutex);
1575 
1576 	st_ops_assoc = rcu_dereference_protected(prog->aux->st_ops_assoc,
1577 						 lockdep_is_held(&prog->aux->st_ops_assoc_mutex));
1578 	if (!st_ops_assoc || st_ops_assoc == BPF_PTR_POISON)
1579 		return;
1580 
1581 	if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1582 		bpf_map_put(st_ops_assoc);
1583 
1584 	RCU_INIT_POINTER(prog->aux->st_ops_assoc, NULL);
1585 }
1586 
1587 /*
1588  * Get a reference to the struct_ops struct (i.e., kdata) associated with a
1589  * program. Should only be called in BPF program context (e.g., in a kfunc).
1590  *
1591  * If the returned pointer is not NULL, it must points to a valid struct_ops.
1592  * The struct_ops map is not guaranteed to be initialized nor attached.
1593  * Kernel struct_ops implementers are responsible for tracking and checking
1594  * the state of the struct_ops if the use case requires an initialized or
1595  * attached struct_ops.
1596  */
1597 void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux)
1598 {
1599 	struct bpf_struct_ops_map *st_map;
1600 	struct bpf_map *st_ops_assoc;
1601 
1602 	st_ops_assoc = rcu_dereference_check(aux->st_ops_assoc, bpf_rcu_lock_held());
1603 	if (!st_ops_assoc || st_ops_assoc == BPF_PTR_POISON)
1604 		return NULL;
1605 
1606 	st_map = (struct bpf_struct_ops_map *)st_ops_assoc;
1607 
1608 	return &st_map->kvalue.data;
1609 }
1610 EXPORT_SYMBOL_GPL(bpf_prog_get_assoc_struct_ops);
1611 
1612 void bpf_map_struct_ops_info_fill(struct bpf_map_info *info, struct bpf_map *map)
1613 {
1614 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1615 
1616 	info->btf_vmlinux_id = btf_obj_id(st_map->btf);
1617 }
1618