xref: /linux/kernel/bpf/bpf_struct_ops.c (revision 1c34522e8b78b3d91b75fd7bd2318c8e7e293a76)
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, struct bpf_ksym *ksym)
644 {
645 	u32 image_off = *_image_off, flags = BPF_TRAMP_F_INDIRECT;
646 	struct bpf_tramp_image im = {};
647 	void *image = *_image;
648 	int size;
649 
650 	tnodes[BPF_TRAMP_FENTRY].nodes[0] = node;
651 	tnodes[BPF_TRAMP_FENTRY].nr_nodes = 1;
652 
653 	if (model->ret_size > 0)
654 		flags |= BPF_TRAMP_F_RET_FENTRY_RET;
655 
656 	size = arch_bpf_trampoline_size(model, flags, tnodes, stub_func);
657 	if (size <= 0)
658 		return size ? : -EFAULT;
659 
660 	/* Allocate image buffer if necessary */
661 	if (!image || size > PAGE_SIZE - image_off) {
662 		if (!allow_alloc)
663 			return -E2BIG;
664 
665 		image = bpf_struct_ops_image_alloc();
666 		if (IS_ERR(image))
667 			return PTR_ERR(image);
668 		image_off = 0;
669 	}
670 
671 	size = arch_prepare_bpf_trampoline(&im, image + image_off,
672 					   image + image_off + size,
673 					   model, flags, tnodes, stub_func);
674 	if (size <= 0) {
675 		if (image != *_image)
676 			bpf_struct_ops_image_free(image);
677 		return size ? : -EFAULT;
678 	}
679 
680 	if (ksym) {
681 		ksym->fp_start = im.ksym.fp_start;
682 		ksym->fp_end = im.ksym.fp_end;
683 	}
684 	*_image = image;
685 	*_image_off = image_off + size;
686 	return 0;
687 }
688 
689 static void bpf_struct_ops_ksym_init(const char *tname, const char *mname,
690 				     void *image, unsigned int size,
691 				     struct bpf_ksym *ksym)
692 {
693 	snprintf(ksym->name, KSYM_NAME_LEN, "bpf__%s_%s", tname, mname);
694 	INIT_LIST_HEAD_RCU(&ksym->lnode);
695 	bpf_image_ksym_init(image, size, ksym);
696 }
697 
698 static void bpf_struct_ops_map_add_ksyms(struct bpf_struct_ops_map *st_map)
699 {
700 	u32 i;
701 
702 	for (i = 0; i < st_map->funcs_cnt; i++) {
703 		if (!st_map->ksyms[i])
704 			break;
705 		bpf_image_ksym_add(st_map->ksyms[i]);
706 	}
707 }
708 
709 static void bpf_struct_ops_map_del_ksyms(struct bpf_struct_ops_map *st_map)
710 {
711 	u32 i;
712 
713 	for (i = 0; i < st_map->funcs_cnt; i++) {
714 		if (!st_map->ksyms[i])
715 			break;
716 		bpf_image_ksym_del(st_map->ksyms[i]);
717 	}
718 }
719 
720 static void bpf_struct_ops_map_free_ksyms(struct bpf_struct_ops_map *st_map)
721 {
722 	u32 i;
723 
724 	for (i = 0; i < st_map->funcs_cnt; i++) {
725 		if (!st_map->ksyms[i])
726 			break;
727 		kfree(st_map->ksyms[i]);
728 		st_map->ksyms[i] = NULL;
729 	}
730 }
731 
732 static long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key,
733 					   void *value, u64 flags)
734 {
735 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
736 	const struct bpf_struct_ops_desc *st_ops_desc = st_map->st_ops_desc;
737 	const struct bpf_struct_ops *st_ops = st_ops_desc->st_ops;
738 	struct bpf_struct_ops_value *uvalue, *kvalue;
739 	const struct btf_type *module_type;
740 	const struct btf_member *member;
741 	const struct btf_type *t = st_ops_desc->type;
742 	struct bpf_tramp_nodes *tnodes;
743 	void *udata, *kdata;
744 	int prog_fd, err;
745 	u32 i, trampoline_start, image_off = 0;
746 	void *cur_image = NULL, *image = NULL;
747 	struct bpf_link **plink;
748 	struct bpf_ksym **pksym;
749 	const char *tname, *mname;
750 
751 	if (flags)
752 		return -EINVAL;
753 
754 	if (*(u32 *)key != 0)
755 		return -E2BIG;
756 
757 	err = check_zero_holes(st_map->btf, st_ops_desc->value_type, value);
758 	if (err)
759 		return err;
760 
761 	uvalue = value;
762 	err = check_zero_holes(st_map->btf, t, uvalue->data);
763 	if (err)
764 		return err;
765 
766 	if (uvalue->common.state || refcount_read(&uvalue->common.refcnt))
767 		return -EINVAL;
768 
769 	tnodes = kzalloc_objs(*tnodes, BPF_TRAMP_MAX);
770 	if (!tnodes)
771 		return -ENOMEM;
772 
773 	uvalue = (struct bpf_struct_ops_value *)st_map->uvalue;
774 	kvalue = (struct bpf_struct_ops_value *)&st_map->kvalue;
775 
776 	mutex_lock(&st_map->lock);
777 
778 	if (kvalue->common.state != BPF_STRUCT_OPS_STATE_INIT) {
779 		err = -EBUSY;
780 		goto unlock;
781 	}
782 
783 	memcpy(uvalue, value, map->value_size);
784 
785 	udata = &uvalue->data;
786 	kdata = &kvalue->data;
787 
788 	plink = st_map->links;
789 	pksym = st_map->ksyms;
790 	tname = btf_name_by_offset(st_map->btf, t->name_off);
791 	module_type = btf_type_by_id(btf_vmlinux, st_ops_ids[IDX_MODULE_ID]);
792 	for_each_member(i, t, member) {
793 		const struct btf_type *mtype, *ptype;
794 		struct bpf_prog *prog;
795 		struct bpf_tramp_link *link;
796 		struct bpf_ksym *ksym;
797 		u32 moff;
798 
799 		moff = __btf_member_bit_offset(t, member) / 8;
800 		mname = btf_name_by_offset(st_map->btf, member->name_off);
801 		ptype = btf_type_resolve_ptr(st_map->btf, member->type, NULL);
802 		if (ptype == module_type) {
803 			if (*(void **)(udata + moff))
804 				goto reset_unlock;
805 			*(void **)(kdata + moff) = BPF_MODULE_OWNER;
806 			continue;
807 		}
808 
809 		err = st_ops->init_member(t, member, kdata, udata);
810 		if (err < 0)
811 			goto reset_unlock;
812 
813 		/* The ->init_member() has handled this member */
814 		if (err > 0)
815 			continue;
816 
817 		/* If st_ops->init_member does not handle it,
818 		 * we will only handle func ptrs and zero-ed members
819 		 * here.  Reject everything else.
820 		 */
821 
822 		/* All non func ptr member must be 0 */
823 		if (!ptype || !btf_type_is_func_proto(ptype)) {
824 			u32 msize;
825 
826 			mtype = btf_type_by_id(st_map->btf, member->type);
827 			mtype = btf_resolve_size(st_map->btf, mtype, &msize);
828 			if (IS_ERR(mtype)) {
829 				err = PTR_ERR(mtype);
830 				goto reset_unlock;
831 			}
832 
833 			if (memchr_inv(udata + moff, 0, msize)) {
834 				err = -EINVAL;
835 				goto reset_unlock;
836 			}
837 
838 			continue;
839 		}
840 
841 		prog_fd = (int)(*(unsigned long *)(udata + moff));
842 		/* Similar check as the attr->attach_prog_fd */
843 		if (!prog_fd)
844 			continue;
845 
846 		prog = bpf_prog_get(prog_fd);
847 		if (IS_ERR(prog)) {
848 			err = PTR_ERR(prog);
849 			goto reset_unlock;
850 		}
851 
852 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
853 		    prog->aux->attach_btf != st_map->btf ||
854 		    prog->aux->attach_btf_id != st_ops_desc->type_id ||
855 		    prog->expected_attach_type != i) {
856 			bpf_prog_put(prog);
857 			err = -EINVAL;
858 			goto reset_unlock;
859 		}
860 
861 		link = kzalloc_obj(*link, GFP_USER);
862 		if (!link) {
863 			bpf_prog_put(prog);
864 			err = -ENOMEM;
865 			goto reset_unlock;
866 		}
867 		bpf_tramp_link_init(link, BPF_LINK_TYPE_STRUCT_OPS,
868 			      &bpf_struct_ops_link_lops, prog, prog->expected_attach_type, 0);
869 
870 		*plink++ = &link->link;
871 
872 		/* Poison pointer on error instead of return for backward compatibility */
873 		bpf_prog_assoc_struct_ops(prog, &st_map->map);
874 
875 		ksym = kzalloc_obj(*ksym, GFP_USER);
876 		if (!ksym) {
877 			err = -ENOMEM;
878 			goto reset_unlock;
879 		}
880 		*pksym++ = ksym;
881 
882 		trampoline_start = image_off;
883 		err = bpf_struct_ops_prepare_trampoline(tnodes, &link->node,
884 						&st_ops->func_models[i],
885 						*(void **)(st_ops->cfi_stubs + moff),
886 						&image, &image_off,
887 						st_map->image_pages_cnt < MAX_TRAMP_IMAGE_PAGES,
888 						ksym);
889 		if (err)
890 			goto reset_unlock;
891 
892 		if (cur_image != image) {
893 			st_map->image_pages[st_map->image_pages_cnt++] = image;
894 			cur_image = image;
895 			trampoline_start = 0;
896 		}
897 
898 		*(void **)(kdata + moff) = image + trampoline_start + cfi_get_offset();
899 
900 		/* put prog_id to udata */
901 		*(unsigned long *)(udata + moff) = prog->aux->id;
902 
903 		/* init ksym for this trampoline */
904 		bpf_struct_ops_ksym_init(tname, mname,
905 					 image + trampoline_start,
906 					 image_off - trampoline_start,
907 					 ksym);
908 	}
909 
910 	if (st_ops->validate) {
911 		err = st_ops->validate(kdata);
912 		if (err)
913 			goto reset_unlock;
914 	}
915 	for (i = 0; i < st_map->image_pages_cnt; i++) {
916 		err = arch_protect_bpf_trampoline(st_map->image_pages[i],
917 						  PAGE_SIZE);
918 		if (err)
919 			goto reset_unlock;
920 	}
921 
922 	if (st_map->map.map_flags & BPF_F_LINK) {
923 		err = 0;
924 		/* Let bpf_link handle registration & unregistration.
925 		 *
926 		 * Pair with smp_load_acquire() during lookup_elem().
927 		 */
928 		smp_store_release(&kvalue->common.state, BPF_STRUCT_OPS_STATE_READY);
929 		goto unlock;
930 	}
931 
932 	err = st_ops->reg(kdata, NULL);
933 	if (likely(!err)) {
934 		/* This refcnt increment on the map here after
935 		 * 'st_ops->reg()' is secure since the state of the
936 		 * map must be set to INIT at this moment, and thus
937 		 * bpf_struct_ops_map_delete_elem() can't unregister
938 		 * or transition it to TOBEFREE concurrently.
939 		 */
940 		bpf_map_inc(map);
941 		/* Pair with smp_load_acquire() during lookup_elem().
942 		 * It ensures the above udata updates (e.g. prog->aux->id)
943 		 * can be seen once BPF_STRUCT_OPS_STATE_INUSE is set.
944 		 */
945 		smp_store_release(&kvalue->common.state, BPF_STRUCT_OPS_STATE_INUSE);
946 		goto unlock;
947 	}
948 
949 	/* Error during st_ops->reg(). Can happen if this struct_ops needs to be
950 	 * verified as a whole, after all init_member() calls. Can also happen if
951 	 * there was a race in registering the struct_ops (under the same name) to
952 	 * a sub-system through different struct_ops's maps.
953 	 */
954 
955 reset_unlock:
956 	bpf_struct_ops_map_free_ksyms(st_map);
957 	bpf_struct_ops_map_free_image(st_map);
958 	bpf_struct_ops_map_dissoc_progs(st_map);
959 	bpf_struct_ops_map_put_progs(st_map);
960 	memset(uvalue, 0, map->value_size);
961 	memset(kvalue, 0, map->value_size);
962 unlock:
963 	kfree(tnodes);
964 	mutex_unlock(&st_map->lock);
965 	if (!err)
966 		bpf_struct_ops_map_add_ksyms(st_map);
967 	return err;
968 }
969 
970 static long bpf_struct_ops_map_delete_elem(struct bpf_map *map, void *key)
971 {
972 	enum bpf_struct_ops_state prev_state;
973 	struct bpf_struct_ops_map *st_map;
974 
975 	st_map = (struct bpf_struct_ops_map *)map;
976 	if (st_map->map.map_flags & BPF_F_LINK)
977 		return -EOPNOTSUPP;
978 
979 	prev_state = cmpxchg(&st_map->kvalue.common.state,
980 			     BPF_STRUCT_OPS_STATE_INUSE,
981 			     BPF_STRUCT_OPS_STATE_TOBEFREE);
982 	switch (prev_state) {
983 	case BPF_STRUCT_OPS_STATE_INUSE:
984 		st_map->st_ops_desc->st_ops->unreg(&st_map->kvalue.data, NULL);
985 		bpf_map_put(map);
986 		return 0;
987 	case BPF_STRUCT_OPS_STATE_TOBEFREE:
988 		return -EINPROGRESS;
989 	case BPF_STRUCT_OPS_STATE_INIT:
990 		return -ENOENT;
991 	default:
992 		WARN_ON_ONCE(1);
993 		/* Should never happen.  Treat it as not found. */
994 		return -ENOENT;
995 	}
996 }
997 
998 static void bpf_struct_ops_map_seq_show_elem(struct bpf_map *map, void *key,
999 					     struct seq_file *m)
1000 {
1001 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1002 	void *value;
1003 	int err;
1004 
1005 	value = kmalloc(map->value_size, GFP_USER | __GFP_NOWARN);
1006 	if (!value)
1007 		return;
1008 
1009 	err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
1010 	if (!err) {
1011 		btf_type_seq_show(st_map->btf,
1012 				  map->btf_vmlinux_value_type_id,
1013 				  value, m);
1014 		seq_putc(m, '\n');
1015 	}
1016 
1017 	kfree(value);
1018 }
1019 
1020 static void __bpf_struct_ops_map_free(struct bpf_map *map)
1021 {
1022 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1023 
1024 	if (st_map->links)
1025 		bpf_struct_ops_map_put_progs(st_map);
1026 	if (st_map->ksyms)
1027 		bpf_struct_ops_map_free_ksyms(st_map);
1028 	bpf_map_area_free(st_map->links);
1029 	bpf_map_area_free(st_map->ksyms);
1030 	bpf_struct_ops_map_free_image(st_map);
1031 	bpf_map_area_free(st_map->uvalue);
1032 	bpf_map_area_free(st_map);
1033 }
1034 
1035 static void bpf_struct_ops_map_free_pre_rcu(struct bpf_map *map)
1036 {
1037 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1038 
1039 	bpf_struct_ops_map_del_ksyms(st_map);
1040 	bpf_struct_ops_map_dissoc_progs(st_map);
1041 }
1042 
1043 static void bpf_struct_ops_map_free(struct bpf_map *map)
1044 {
1045 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1046 	struct bpf_struct_ops *st_ops = st_map->st_ops_desc->st_ops;
1047 	bool tasks_rcu = st_ops->free_after_tasks_rcu_gp;
1048 
1049 	/* st_ops->owner was acquired during map_alloc to implicitly holds
1050 	 * the btf's refcnt. The acquire was only done when btf_is_module()
1051 	 * st_map->btf cannot be NULL here.
1052 	 */
1053 	if (btf_is_module(st_map->btf))
1054 		module_put(st_map->st_ops_desc->st_ops->owner);
1055 
1056 	if (tasks_rcu && IS_ENABLED(CONFIG_TASKS_RCU))
1057 		synchronize_rcu_tasks();
1058 
1059 	__bpf_struct_ops_map_free(map);
1060 }
1061 
1062 static int bpf_struct_ops_map_alloc_check(union bpf_attr *attr)
1063 {
1064 	if (attr->key_size != sizeof(unsigned int) || attr->max_entries != 1 ||
1065 	    (attr->map_flags & ~(BPF_F_LINK | BPF_F_VTYPE_BTF_OBJ_FD)) ||
1066 	    !attr->btf_vmlinux_value_type_id)
1067 		return -EINVAL;
1068 	return 0;
1069 }
1070 
1071 static u32 count_func_ptrs(const struct btf *btf, const struct btf_type *t)
1072 {
1073 	int i;
1074 	u32 count;
1075 	const struct btf_member *member;
1076 
1077 	count = 0;
1078 	for_each_member(i, t, member)
1079 		if (btf_type_resolve_func_ptr(btf, member->type, NULL))
1080 			count++;
1081 	return count;
1082 }
1083 
1084 static struct bpf_map *bpf_struct_ops_map_alloc(union bpf_attr *attr)
1085 {
1086 	const struct bpf_struct_ops_desc *st_ops_desc;
1087 	size_t st_map_size;
1088 	struct bpf_struct_ops_map *st_map;
1089 	const struct btf_type *t, *vt;
1090 	struct module *mod = NULL;
1091 	struct bpf_map *map;
1092 	struct btf *btf;
1093 	int ret;
1094 
1095 	if (attr->map_flags & BPF_F_VTYPE_BTF_OBJ_FD) {
1096 		/* The map holds btf for its whole life time. */
1097 		btf = btf_get_by_fd(attr->value_type_btf_obj_fd);
1098 		if (IS_ERR(btf))
1099 			return ERR_CAST(btf);
1100 		if (!btf_is_module(btf)) {
1101 			btf_put(btf);
1102 			return ERR_PTR(-EINVAL);
1103 		}
1104 
1105 		mod = btf_try_get_module(btf);
1106 		/* mod holds a refcnt to btf. We don't need an extra refcnt
1107 		 * here.
1108 		 */
1109 		btf_put(btf);
1110 		if (!mod)
1111 			return ERR_PTR(-EINVAL);
1112 	} else {
1113 		btf = bpf_get_btf_vmlinux();
1114 		if (IS_ERR(btf))
1115 			return ERR_CAST(btf);
1116 		if (!btf)
1117 			return ERR_PTR(-ENOTSUPP);
1118 	}
1119 
1120 	st_ops_desc = bpf_struct_ops_find_value(btf, attr->btf_vmlinux_value_type_id);
1121 	if (!st_ops_desc) {
1122 		ret = -ENOTSUPP;
1123 		goto errout;
1124 	}
1125 
1126 	if (st_ops_desc->st_ops->cgroup_atype && !(attr->map_flags & BPF_F_LINK)) {
1127 		ret = -EOPNOTSUPP;
1128 		goto errout;
1129 	}
1130 
1131 	vt = st_ops_desc->value_type;
1132 	if (attr->value_size != vt->size) {
1133 		ret = -EINVAL;
1134 		goto errout;
1135 	}
1136 
1137 	t = st_ops_desc->type;
1138 
1139 	st_map_size = sizeof(*st_map) +
1140 		/* kvalue stores the
1141 		 * struct bpf_struct_ops_tcp_congestions_ops
1142 		 */
1143 		(vt->size - sizeof(struct bpf_struct_ops_value));
1144 
1145 	st_map = bpf_map_area_alloc(st_map_size, NUMA_NO_NODE);
1146 	if (!st_map) {
1147 		ret = -ENOMEM;
1148 		goto errout;
1149 	}
1150 
1151 	st_map->st_ops_desc = st_ops_desc;
1152 	map = &st_map->map;
1153 
1154 	st_map->uvalue = bpf_map_area_alloc(vt->size, NUMA_NO_NODE);
1155 	st_map->funcs_cnt = count_func_ptrs(btf, t);
1156 	st_map->links =
1157 		bpf_map_area_alloc(st_map->funcs_cnt * sizeof(struct bpf_link *),
1158 				   NUMA_NO_NODE);
1159 
1160 	st_map->ksyms =
1161 		bpf_map_area_alloc(st_map->funcs_cnt * sizeof(struct bpf_ksym *),
1162 				   NUMA_NO_NODE);
1163 	if (!st_map->uvalue || !st_map->links || !st_map->ksyms) {
1164 		ret = -ENOMEM;
1165 		goto errout_free;
1166 	}
1167 	st_map->btf = btf;
1168 
1169 	mutex_init(&st_map->lock);
1170 	bpf_map_init_from_attr(map, attr);
1171 	/*
1172 	 * A prog dissociated in map_free_pre_rcu() may still run the struct_ops
1173 	 * from a bpf_wq callback or a sleepable prog, under RCU tasks trace.
1174 	 */
1175 	map->free_after_mult_rcu_gp = true;
1176 
1177 	return map;
1178 
1179 errout_free:
1180 	__bpf_struct_ops_map_free(map);
1181 errout:
1182 	module_put(mod);
1183 
1184 	return ERR_PTR(ret);
1185 }
1186 
1187 static u64 bpf_struct_ops_map_mem_usage(const struct bpf_map *map)
1188 {
1189 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1190 	const struct bpf_struct_ops_desc *st_ops_desc = st_map->st_ops_desc;
1191 	const struct btf_type *vt = st_ops_desc->value_type;
1192 	u64 usage;
1193 
1194 	usage = sizeof(*st_map) +
1195 			vt->size - sizeof(struct bpf_struct_ops_value);
1196 	usage += vt->size;
1197 	usage += st_map->funcs_cnt * sizeof(struct bpf_link *);
1198 	usage += st_map->funcs_cnt * sizeof(struct bpf_ksym *);
1199 	usage += PAGE_SIZE;
1200 	return usage;
1201 }
1202 
1203 BTF_ID_LIST_SINGLE(bpf_struct_ops_map_btf_ids, struct, bpf_struct_ops_map)
1204 const struct bpf_map_ops bpf_struct_ops_map_ops = {
1205 	.map_alloc_check = bpf_struct_ops_map_alloc_check,
1206 	.map_alloc = bpf_struct_ops_map_alloc,
1207 	.map_free = bpf_struct_ops_map_free,
1208 	.map_free_pre_rcu = bpf_struct_ops_map_free_pre_rcu,
1209 	.map_get_next_key = bpf_struct_ops_map_get_next_key,
1210 	.map_lookup_elem = bpf_struct_ops_map_lookup_elem,
1211 	.map_delete_elem = bpf_struct_ops_map_delete_elem,
1212 	.map_update_elem = bpf_struct_ops_map_update_elem,
1213 	.map_seq_show_elem = bpf_struct_ops_map_seq_show_elem,
1214 	.map_mem_usage = bpf_struct_ops_map_mem_usage,
1215 	.map_btf_id = &bpf_struct_ops_map_btf_ids[0],
1216 };
1217 
1218 /* "const void *" because some subsystem is
1219  * passing a const (e.g. const struct tcp_congestion_ops *)
1220  */
1221 bool bpf_struct_ops_get(const void *kdata)
1222 {
1223 	struct bpf_struct_ops_value *kvalue;
1224 	struct bpf_struct_ops_map *st_map;
1225 	struct bpf_map *map;
1226 
1227 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
1228 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
1229 
1230 	map = __bpf_map_inc_not_zero(&st_map->map, false);
1231 	return !IS_ERR(map);
1232 }
1233 EXPORT_SYMBOL_GPL(bpf_struct_ops_get);
1234 
1235 void bpf_struct_ops_put(const void *kdata)
1236 {
1237 	struct bpf_struct_ops_value *kvalue;
1238 	struct bpf_struct_ops_map *st_map;
1239 
1240 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
1241 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
1242 
1243 	bpf_map_put(&st_map->map);
1244 }
1245 EXPORT_SYMBOL_GPL(bpf_struct_ops_put);
1246 
1247 u32 bpf_struct_ops_id(const void *kdata)
1248 {
1249 	struct bpf_struct_ops_value *kvalue;
1250 	struct bpf_struct_ops_map *st_map;
1251 
1252 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
1253 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
1254 
1255 	return st_map->map.id;
1256 }
1257 EXPORT_SYMBOL_GPL(bpf_struct_ops_id);
1258 
1259 /**
1260  * bpf_struct_ops_for_each_prog - Invoke @cb for each member prog
1261  * @kdata: kernel-side struct_ops vmtable (the @kdata arg to ->reg/->update/->unreg)
1262  * @cb: callback invoked once per member prog; non-zero return stops iteration
1263  * @data: opaque argument passed to @cb
1264  *
1265  * Walks the struct_ops member progs registered on the map containing @kdata.
1266  * Intended for use from struct_ops ->reg() callbacks (and similar) that need to
1267  * inspect the loaded BPF programs (for example to discover maps they reference
1268  * via @prog->aux->used_maps).
1269  *
1270  * Return 0 if iteration completed, otherwise the first non-zero @cb return.
1271  */
1272 int bpf_struct_ops_for_each_prog(const void *kdata,
1273 				 int (*cb)(struct bpf_prog *prog, void *data),
1274 				 void *data)
1275 {
1276 	struct bpf_struct_ops_value *kvalue;
1277 	struct bpf_struct_ops_map *st_map;
1278 	u32 i;
1279 	int ret;
1280 
1281 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
1282 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
1283 
1284 	for (i = 0; i < st_map->funcs_cnt; i++) {
1285 		if (!st_map->links[i])
1286 			continue;
1287 		ret = cb(st_map->links[i]->prog, data);
1288 		if (ret)
1289 			return ret;
1290 	}
1291 	return 0;
1292 }
1293 EXPORT_SYMBOL_GPL(bpf_struct_ops_for_each_prog);
1294 
1295 void *bpf_struct_ops_map_kdata(struct bpf_map *map)
1296 {
1297 	struct bpf_struct_ops_map *st_map;
1298 
1299 	st_map = container_of(map, struct bpf_struct_ops_map, map);
1300 	return st_map->kvalue.data;
1301 }
1302 
1303 int bpf_struct_ops_map_cgroup_atype(struct bpf_map *map)
1304 {
1305 	struct bpf_struct_ops_map *st_map;
1306 
1307 	st_map = container_of(map, struct bpf_struct_ops_map, map);
1308 	return st_map->st_ops_desc->st_ops->cgroup_atype;
1309 }
1310 
1311 void *bpf_struct_ops_map_cfi_stubs(struct bpf_map *map)
1312 {
1313 	struct bpf_struct_ops_map *st_map;
1314 
1315 	st_map = container_of(map, struct bpf_struct_ops_map, map);
1316 	return st_map->st_ops_desc->st_ops->cfi_stubs;
1317 }
1318 
1319 bool bpf_struct_ops_valid_to_reg(struct bpf_map *map)
1320 {
1321 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1322 
1323 	return map->map_type == BPF_MAP_TYPE_STRUCT_OPS &&
1324 		map->map_flags & BPF_F_LINK &&
1325 		/* Pair with smp_store_release() during map_update */
1326 		smp_load_acquire(&st_map->kvalue.common.state) == BPF_STRUCT_OPS_STATE_READY;
1327 }
1328 
1329 static void bpf_struct_ops_map_link_dealloc(struct bpf_link *link)
1330 {
1331 	struct bpf_struct_ops_link *st_link;
1332 	struct bpf_struct_ops_map *st_map;
1333 
1334 	st_link = container_of(link, struct bpf_struct_ops_link, link);
1335 	st_map = (struct bpf_struct_ops_map *)st_link->map;
1336 	if (st_map) {
1337 		st_map->st_ops_desc->st_ops->unreg(&st_map->kvalue.data, link);
1338 		bpf_map_put(&st_map->map);
1339 	}
1340 	kfree(st_link);
1341 }
1342 
1343 static void bpf_struct_ops_map_link_show_fdinfo(const struct bpf_link *link,
1344 					    struct seq_file *seq)
1345 {
1346 	struct bpf_struct_ops_link *st_link;
1347 	struct bpf_map *map;
1348 
1349 	st_link = container_of(link, struct bpf_struct_ops_link, link);
1350 	mutex_lock(&update_mutex);
1351 	map = st_link->map;
1352 	if (map)
1353 		seq_printf(seq, "map_id:\t%d\n", map->id);
1354 	mutex_unlock(&update_mutex);
1355 }
1356 
1357 static int bpf_struct_ops_map_link_fill_link_info(const struct bpf_link *link,
1358 					       struct bpf_link_info *info)
1359 {
1360 	struct bpf_struct_ops_link *st_link;
1361 	struct bpf_map *map;
1362 
1363 	st_link = container_of(link, struct bpf_struct_ops_link, link);
1364 	mutex_lock(&update_mutex);
1365 	map = st_link->map;
1366 	if (map)
1367 		info->struct_ops.map_id = map->id;
1368 	mutex_unlock(&update_mutex);
1369 	return 0;
1370 }
1371 
1372 int bpf_struct_ops_link_update_check(struct bpf_map *new_map,
1373 				     struct bpf_map *old_map,
1374 				     struct bpf_map *expected_old_map)
1375 {
1376 	struct bpf_struct_ops_map *st_map, *old_st_map;
1377 
1378 	if (!old_map)
1379 		return -ENOLINK;
1380 	if (expected_old_map && old_map != expected_old_map)
1381 		return -EPERM;
1382 
1383 	st_map = container_of(new_map, struct bpf_struct_ops_map, map);
1384 	old_st_map = container_of(old_map, struct bpf_struct_ops_map, map);
1385 	/* The new and old struct_ops must be the same type. */
1386 	if (st_map->st_ops_desc != old_st_map->st_ops_desc)
1387 		return -EINVAL;
1388 
1389 	return 0;
1390 }
1391 
1392 static int bpf_struct_ops_map_link_update(struct bpf_link *link, struct bpf_map *new_map,
1393 					  struct bpf_map *expected_old_map)
1394 {
1395 	struct bpf_struct_ops_map *st_map, *old_st_map;
1396 	struct bpf_map *old_map;
1397 	struct bpf_struct_ops_link *st_link;
1398 	int err;
1399 
1400 	st_link = container_of(link, struct bpf_struct_ops_link, link);
1401 	st_map = container_of(new_map, struct bpf_struct_ops_map, map);
1402 
1403 	if (!bpf_struct_ops_valid_to_reg(new_map))
1404 		return -EINVAL;
1405 
1406 	if (!st_map->st_ops_desc->st_ops->update)
1407 		return -EOPNOTSUPP;
1408 
1409 	mutex_lock(&update_mutex);
1410 	old_map = st_link->map;
1411 	err = bpf_struct_ops_link_update_check(new_map, old_map, expected_old_map);
1412 	if (err)
1413 		goto err_out;
1414 
1415 	old_st_map = container_of(old_map, struct bpf_struct_ops_map, map);
1416 
1417 	err = st_map->st_ops_desc->st_ops->update(st_map->kvalue.data, old_st_map->kvalue.data, link);
1418 	if (err)
1419 		goto err_out;
1420 
1421 	bpf_map_inc(new_map);
1422 	WRITE_ONCE(st_link->map, new_map);
1423 	bpf_map_put(old_map);
1424 
1425 err_out:
1426 	mutex_unlock(&update_mutex);
1427 
1428 	return err;
1429 }
1430 
1431 static int bpf_struct_ops_map_link_detach(struct bpf_link *link)
1432 {
1433 	struct bpf_struct_ops_link *st_link = container_of(link, struct bpf_struct_ops_link, link);
1434 	struct bpf_struct_ops_map *st_map;
1435 	struct bpf_map *map;
1436 
1437 	mutex_lock(&update_mutex);
1438 
1439 	map = st_link->map;
1440 	if (!map) {
1441 		mutex_unlock(&update_mutex);
1442 		return 0;
1443 	}
1444 	st_map = container_of(map, struct bpf_struct_ops_map, map);
1445 
1446 	st_map->st_ops_desc->st_ops->unreg(&st_map->kvalue.data, link);
1447 
1448 	WRITE_ONCE(st_link->map, NULL);
1449 	/* Pair with bpf_map_get() in bpf_struct_ops_link_create() or
1450 	 * bpf_map_inc() in bpf_struct_ops_map_link_update().
1451 	 */
1452 	bpf_map_put(&st_map->map);
1453 
1454 	mutex_unlock(&update_mutex);
1455 
1456 	wake_up_interruptible_poll(&st_link->wait_hup, EPOLLHUP);
1457 
1458 	return 0;
1459 }
1460 
1461 static __poll_t bpf_struct_ops_map_link_poll(struct file *file,
1462 					     struct poll_table_struct *pts)
1463 {
1464 	struct bpf_struct_ops_link *st_link = file->private_data;
1465 
1466 	poll_wait(file, &st_link->wait_hup, pts);
1467 
1468 	return READ_ONCE(st_link->map) ? 0 : EPOLLHUP;
1469 }
1470 
1471 static const struct bpf_link_ops bpf_struct_ops_map_lops = {
1472 	.dealloc = bpf_struct_ops_map_link_dealloc,
1473 	.detach = bpf_struct_ops_map_link_detach,
1474 	.show_fdinfo = bpf_struct_ops_map_link_show_fdinfo,
1475 	.fill_link_info = bpf_struct_ops_map_link_fill_link_info,
1476 	.update_map = bpf_struct_ops_map_link_update,
1477 	.poll = bpf_struct_ops_map_link_poll,
1478 };
1479 
1480 int bpf_struct_ops_link_create(union bpf_attr *attr)
1481 {
1482 	struct bpf_struct_ops_link *link = NULL;
1483 	struct bpf_link_primer link_primer;
1484 	struct bpf_struct_ops_map *st_map;
1485 	struct bpf_map *map;
1486 	int cgroup_atype;
1487 	int err;
1488 
1489 	map = bpf_map_get(attr->link_create.map_fd);
1490 	if (IS_ERR(map))
1491 		return PTR_ERR(map);
1492 
1493 	st_map = (struct bpf_struct_ops_map *)map;
1494 
1495 	if (!bpf_struct_ops_valid_to_reg(map)) {
1496 		err = -EINVAL;
1497 		goto err_out;
1498 	}
1499 
1500 	cgroup_atype = st_map->st_ops_desc->st_ops->cgroup_atype;
1501 	if (cgroup_atype) {
1502 		err = cgroup_bpf_struct_ops_attach(map, attr);
1503 		bpf_map_put(map);
1504 		return err;
1505 	}
1506 
1507 	if (memchr_inv(&attr->link_create.cgroup, 0, sizeof(attr->link_create.cgroup)) ||
1508 	    attr->link_create.target_fd) {
1509 		err = -EINVAL;
1510 		goto err_out;
1511 	}
1512 
1513 	link = kzalloc_obj(*link, GFP_USER);
1514 	if (!link) {
1515 		err = -ENOMEM;
1516 		goto err_out;
1517 	}
1518 	bpf_link_init(&link->link, BPF_LINK_TYPE_STRUCT_OPS, &bpf_struct_ops_map_lops, NULL,
1519 		      attr->link_create.attach_type);
1520 
1521 	err = bpf_link_prime(&link->link, &link_primer);
1522 	if (err)
1523 		goto err_out;
1524 
1525 	init_waitqueue_head(&link->wait_hup);
1526 
1527 	/* Hold the update_mutex such that the subsystem cannot
1528 	 * do link->ops->detach() before the link is fully initialized.
1529 	 */
1530 	mutex_lock(&update_mutex);
1531 	err = st_map->st_ops_desc->st_ops->reg(st_map->kvalue.data, &link->link);
1532 	if (err) {
1533 		mutex_unlock(&update_mutex);
1534 		bpf_link_cleanup(&link_primer);
1535 		link = NULL;
1536 		goto err_out;
1537 	}
1538 	link->map = map;
1539 	mutex_unlock(&update_mutex);
1540 
1541 	return bpf_link_settle(&link_primer);
1542 
1543 err_out:
1544 	bpf_map_put(map);
1545 	kfree(link);
1546 	return err;
1547 }
1548 
1549 int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_map *map)
1550 {
1551 	struct bpf_map *st_ops_assoc;
1552 
1553 	guard(spinlock_irqsave)(&prog->aux->st_ops_assoc_lock);
1554 
1555 	st_ops_assoc = rcu_dereference_protected(prog->aux->st_ops_assoc,
1556 						 lockdep_is_held(&prog->aux->st_ops_assoc_lock));
1557 	if (st_ops_assoc && st_ops_assoc == map)
1558 		return 0;
1559 
1560 	if (st_ops_assoc) {
1561 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1562 			return -EBUSY;
1563 
1564 		rcu_assign_pointer(prog->aux->st_ops_assoc, BPF_PTR_POISON);
1565 	} else {
1566 		/*
1567 		 * struct_ops map does not track associated non-struct_ops programs.
1568 		 * Bump the refcount to make sure st_ops_assoc is always valid.
1569 		 */
1570 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1571 			bpf_map_inc(map);
1572 
1573 		rcu_assign_pointer(prog->aux->st_ops_assoc, map);
1574 	}
1575 
1576 	return 0;
1577 }
1578 
1579 void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog)
1580 {
1581 	struct bpf_prog_aux *aux = prog->aux;
1582 	struct bpf_map *st_ops_assoc;
1583 
1584 	scoped_guard(spinlock_irqsave, &aux->st_ops_assoc_lock) {
1585 		st_ops_assoc = rcu_dereference_protected(aux->st_ops_assoc,
1586 							 lockdep_is_held(&aux->st_ops_assoc_lock));
1587 		if (!st_ops_assoc || st_ops_assoc == BPF_PTR_POISON)
1588 			return;
1589 
1590 		RCU_INIT_POINTER(aux->st_ops_assoc, NULL);
1591 	}
1592 
1593 	if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1594 		bpf_map_put(st_ops_assoc);
1595 }
1596 
1597 /*
1598  * Get a reference to the struct_ops struct (i.e., kdata) associated with a
1599  * program. Should only be called in BPF program context (e.g., in a kfunc).
1600  *
1601  * If the returned pointer is not NULL, it must points to a valid @st_ops.
1602  * The struct_ops map is not guaranteed to be initialized nor attached.
1603  * Kernel struct_ops implementers are responsible for tracking and checking
1604  * the state of the struct_ops if the use case requires an initialized or
1605  * attached struct_ops.
1606  */
1607 void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux,
1608 				    const struct bpf_struct_ops *st_ops)
1609 {
1610 	struct bpf_struct_ops_map *st_map;
1611 	struct bpf_map *st_ops_assoc;
1612 
1613 	st_ops_assoc = rcu_dereference_check(aux->st_ops_assoc, bpf_rcu_lock_held());
1614 	if (!st_ops_assoc || st_ops_assoc == BPF_PTR_POISON)
1615 		return NULL;
1616 
1617 	st_map = (struct bpf_struct_ops_map *)st_ops_assoc;
1618 	if (st_map->st_ops_desc->st_ops != st_ops)
1619 		return NULL;
1620 
1621 	return &st_map->kvalue.data;
1622 }
1623 EXPORT_SYMBOL_GPL(bpf_prog_get_assoc_struct_ops);
1624 
1625 void bpf_map_struct_ops_info_fill(struct bpf_map_info *info, struct bpf_map *map)
1626 {
1627 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1628 
1629 	info->btf_vmlinux_id = btf_obj_id(st_map->btf);
1630 }
1631