xref: /linux-6.15/kernel/bpf/bpf_struct_ops.c (revision e3f87fdf)
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 
16 enum bpf_struct_ops_state {
17 	BPF_STRUCT_OPS_STATE_INIT,
18 	BPF_STRUCT_OPS_STATE_INUSE,
19 	BPF_STRUCT_OPS_STATE_TOBEFREE,
20 	BPF_STRUCT_OPS_STATE_READY,
21 };
22 
23 #define BPF_STRUCT_OPS_COMMON_VALUE			\
24 	refcount_t refcnt;				\
25 	enum bpf_struct_ops_state state
26 
27 struct bpf_struct_ops_value {
28 	BPF_STRUCT_OPS_COMMON_VALUE;
29 	char data[] ____cacheline_aligned_in_smp;
30 };
31 
32 struct bpf_struct_ops_map {
33 	struct bpf_map map;
34 	struct rcu_head rcu;
35 	const struct bpf_struct_ops_desc *st_ops_desc;
36 	/* protect map_update */
37 	struct mutex lock;
38 	/* link has all the bpf_links that is populated
39 	 * to the func ptr of the kernel's struct
40 	 * (in kvalue.data).
41 	 */
42 	struct bpf_link **links;
43 	u32 links_cnt;
44 	/* image is a page that has all the trampolines
45 	 * that stores the func args before calling the bpf_prog.
46 	 * A PAGE_SIZE "image" is enough to store all trampoline for
47 	 * "links[]".
48 	 */
49 	void *image;
50 	/* The owner moduler's btf. */
51 	struct btf *btf;
52 	/* uvalue->data stores the kernel struct
53 	 * (e.g. tcp_congestion_ops) that is more useful
54 	 * to userspace than the kvalue.  For example,
55 	 * the bpf_prog's id is stored instead of the kernel
56 	 * address of a func ptr.
57 	 */
58 	struct bpf_struct_ops_value *uvalue;
59 	/* kvalue.data stores the actual kernel's struct
60 	 * (e.g. tcp_congestion_ops) that will be
61 	 * registered to the kernel subsystem.
62 	 */
63 	struct bpf_struct_ops_value kvalue;
64 };
65 
66 struct bpf_struct_ops_link {
67 	struct bpf_link link;
68 	struct bpf_map __rcu *map;
69 };
70 
71 static DEFINE_MUTEX(update_mutex);
72 
73 #define VALUE_PREFIX "bpf_struct_ops_"
74 #define VALUE_PREFIX_LEN (sizeof(VALUE_PREFIX) - 1)
75 
76 /* bpf_struct_ops_##_name (e.g. bpf_struct_ops_tcp_congestion_ops) is
77  * the map's value exposed to the userspace and its btf-type-id is
78  * stored at the map->btf_vmlinux_value_type_id.
79  *
80  */
81 #define BPF_STRUCT_OPS_TYPE(_name)				\
82 extern struct bpf_struct_ops bpf_##_name;			\
83 								\
84 struct bpf_struct_ops_##_name {						\
85 	BPF_STRUCT_OPS_COMMON_VALUE;				\
86 	struct _name data ____cacheline_aligned_in_smp;		\
87 };
88 #include "bpf_struct_ops_types.h"
89 #undef BPF_STRUCT_OPS_TYPE
90 
91 enum {
92 #define BPF_STRUCT_OPS_TYPE(_name) BPF_STRUCT_OPS_TYPE_##_name,
93 #include "bpf_struct_ops_types.h"
94 #undef BPF_STRUCT_OPS_TYPE
95 	__NR_BPF_STRUCT_OPS_TYPE,
96 };
97 
98 static struct bpf_struct_ops_desc bpf_struct_ops[] = {
99 #define BPF_STRUCT_OPS_TYPE(_name)				\
100 	[BPF_STRUCT_OPS_TYPE_##_name] = { .st_ops = &bpf_##_name },
101 #include "bpf_struct_ops_types.h"
102 #undef BPF_STRUCT_OPS_TYPE
103 };
104 
105 const struct bpf_verifier_ops bpf_struct_ops_verifier_ops = {
106 };
107 
108 const struct bpf_prog_ops bpf_struct_ops_prog_ops = {
109 #ifdef CONFIG_NET
110 	.test_run = bpf_struct_ops_test_run,
111 #endif
112 };
113 
114 BTF_ID_LIST(st_ops_ids)
115 BTF_ID(struct, module)
116 
117 enum {
118 	IDX_MODULE_ID,
119 };
120 
121 static void bpf_struct_ops_desc_init(struct bpf_struct_ops_desc *st_ops_desc,
122 				     struct btf *btf,
123 				     struct bpf_verifier_log *log)
124 {
125 	struct bpf_struct_ops *st_ops = st_ops_desc->st_ops;
126 	const struct btf_member *member;
127 	const struct btf_type *t;
128 	s32 type_id, value_id;
129 	char value_name[128];
130 	const char *mname;
131 	int i;
132 
133 	if (strlen(st_ops->name) + VALUE_PREFIX_LEN >=
134 	    sizeof(value_name)) {
135 		pr_warn("struct_ops name %s is too long\n",
136 			st_ops->name);
137 		return;
138 	}
139 	sprintf(value_name, "%s%s", VALUE_PREFIX, st_ops->name);
140 
141 	value_id = btf_find_by_name_kind(btf, value_name,
142 					 BTF_KIND_STRUCT);
143 	if (value_id < 0) {
144 		pr_warn("Cannot find struct %s in %s\n",
145 			value_name, btf_get_name(btf));
146 		return;
147 	}
148 
149 	type_id = btf_find_by_name_kind(btf, st_ops->name,
150 					BTF_KIND_STRUCT);
151 	if (type_id < 0) {
152 		pr_warn("Cannot find struct %s in %s\n",
153 			st_ops->name, btf_get_name(btf));
154 		return;
155 	}
156 	t = btf_type_by_id(btf, type_id);
157 	if (btf_type_vlen(t) > BPF_STRUCT_OPS_MAX_NR_MEMBERS) {
158 		pr_warn("Cannot support #%u members in struct %s\n",
159 			btf_type_vlen(t), st_ops->name);
160 		return;
161 	}
162 
163 	for_each_member(i, t, member) {
164 		const struct btf_type *func_proto;
165 
166 		mname = btf_name_by_offset(btf, member->name_off);
167 		if (!*mname) {
168 			pr_warn("anon member in struct %s is not supported\n",
169 				st_ops->name);
170 			break;
171 		}
172 
173 		if (__btf_member_bitfield_size(t, member)) {
174 			pr_warn("bit field member %s in struct %s is not supported\n",
175 				mname, st_ops->name);
176 			break;
177 		}
178 
179 		func_proto = btf_type_resolve_func_ptr(btf,
180 						       member->type,
181 						       NULL);
182 		if (func_proto &&
183 		    btf_distill_func_proto(log, btf,
184 					   func_proto, mname,
185 					   &st_ops->func_models[i])) {
186 			pr_warn("Error in parsing func ptr %s in struct %s\n",
187 				mname, st_ops->name);
188 			break;
189 		}
190 	}
191 
192 	if (i == btf_type_vlen(t)) {
193 		if (st_ops->init(btf)) {
194 			pr_warn("Error in init bpf_struct_ops %s\n",
195 				st_ops->name);
196 		} else {
197 			st_ops_desc->type_id = type_id;
198 			st_ops_desc->type = t;
199 			st_ops_desc->value_id = value_id;
200 			st_ops_desc->value_type = btf_type_by_id(btf,
201 								 value_id);
202 		}
203 	}
204 }
205 
206 void bpf_struct_ops_init(struct btf *btf, struct bpf_verifier_log *log)
207 {
208 	struct bpf_struct_ops_desc *st_ops_desc;
209 	u32 i;
210 
211 	/* Ensure BTF type is emitted for "struct bpf_struct_ops_##_name" */
212 #define BPF_STRUCT_OPS_TYPE(_name) BTF_TYPE_EMIT(struct bpf_struct_ops_##_name);
213 #include "bpf_struct_ops_types.h"
214 #undef BPF_STRUCT_OPS_TYPE
215 
216 	for (i = 0; i < ARRAY_SIZE(bpf_struct_ops); i++) {
217 		st_ops_desc = &bpf_struct_ops[i];
218 		bpf_struct_ops_desc_init(st_ops_desc, btf, log);
219 	}
220 }
221 
222 extern struct btf *btf_vmlinux;
223 
224 static const struct bpf_struct_ops_desc *
225 bpf_struct_ops_find_value(struct btf *btf, u32 value_id)
226 {
227 	unsigned int i;
228 
229 	if (!value_id || !btf)
230 		return NULL;
231 
232 	for (i = 0; i < ARRAY_SIZE(bpf_struct_ops); i++) {
233 		if (bpf_struct_ops[i].value_id == value_id)
234 			return &bpf_struct_ops[i];
235 	}
236 
237 	return NULL;
238 }
239 
240 const struct bpf_struct_ops_desc *
241 bpf_struct_ops_find(struct btf *btf, u32 type_id)
242 {
243 	unsigned int i;
244 
245 	if (!type_id || !btf)
246 		return NULL;
247 
248 	for (i = 0; i < ARRAY_SIZE(bpf_struct_ops); i++) {
249 		if (bpf_struct_ops[i].type_id == type_id)
250 			return &bpf_struct_ops[i];
251 	}
252 
253 	return NULL;
254 }
255 
256 static int bpf_struct_ops_map_get_next_key(struct bpf_map *map, void *key,
257 					   void *next_key)
258 {
259 	if (key && *(u32 *)key == 0)
260 		return -ENOENT;
261 
262 	*(u32 *)next_key = 0;
263 	return 0;
264 }
265 
266 int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map, void *key,
267 				       void *value)
268 {
269 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
270 	struct bpf_struct_ops_value *uvalue, *kvalue;
271 	enum bpf_struct_ops_state state;
272 	s64 refcnt;
273 
274 	if (unlikely(*(u32 *)key != 0))
275 		return -ENOENT;
276 
277 	kvalue = &st_map->kvalue;
278 	/* Pair with smp_store_release() during map_update */
279 	state = smp_load_acquire(&kvalue->state);
280 	if (state == BPF_STRUCT_OPS_STATE_INIT) {
281 		memset(value, 0, map->value_size);
282 		return 0;
283 	}
284 
285 	/* No lock is needed.  state and refcnt do not need
286 	 * to be updated together under atomic context.
287 	 */
288 	uvalue = value;
289 	memcpy(uvalue, st_map->uvalue, map->value_size);
290 	uvalue->state = state;
291 
292 	/* This value offers the user space a general estimate of how
293 	 * many sockets are still utilizing this struct_ops for TCP
294 	 * congestion control. The number might not be exact, but it
295 	 * should sufficiently meet our present goals.
296 	 */
297 	refcnt = atomic64_read(&map->refcnt) - atomic64_read(&map->usercnt);
298 	refcount_set(&uvalue->refcnt, max_t(s64, refcnt, 0));
299 
300 	return 0;
301 }
302 
303 static void *bpf_struct_ops_map_lookup_elem(struct bpf_map *map, void *key)
304 {
305 	return ERR_PTR(-EINVAL);
306 }
307 
308 static void bpf_struct_ops_map_put_progs(struct bpf_struct_ops_map *st_map)
309 {
310 	u32 i;
311 
312 	for (i = 0; i < st_map->links_cnt; i++) {
313 		if (st_map->links[i]) {
314 			bpf_link_put(st_map->links[i]);
315 			st_map->links[i] = NULL;
316 		}
317 	}
318 }
319 
320 static int check_zero_holes(const struct btf *btf, const struct btf_type *t, void *data)
321 {
322 	const struct btf_member *member;
323 	u32 i, moff, msize, prev_mend = 0;
324 	const struct btf_type *mtype;
325 
326 	for_each_member(i, t, member) {
327 		moff = __btf_member_bit_offset(t, member) / 8;
328 		if (moff > prev_mend &&
329 		    memchr_inv(data + prev_mend, 0, moff - prev_mend))
330 			return -EINVAL;
331 
332 		mtype = btf_type_by_id(btf, member->type);
333 		mtype = btf_resolve_size(btf, mtype, &msize);
334 		if (IS_ERR(mtype))
335 			return PTR_ERR(mtype);
336 		prev_mend = moff + msize;
337 	}
338 
339 	if (t->size > prev_mend &&
340 	    memchr_inv(data + prev_mend, 0, t->size - prev_mend))
341 		return -EINVAL;
342 
343 	return 0;
344 }
345 
346 static void bpf_struct_ops_link_release(struct bpf_link *link)
347 {
348 }
349 
350 static void bpf_struct_ops_link_dealloc(struct bpf_link *link)
351 {
352 	struct bpf_tramp_link *tlink = container_of(link, struct bpf_tramp_link, link);
353 
354 	kfree(tlink);
355 }
356 
357 const struct bpf_link_ops bpf_struct_ops_link_lops = {
358 	.release = bpf_struct_ops_link_release,
359 	.dealloc = bpf_struct_ops_link_dealloc,
360 };
361 
362 int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_links *tlinks,
363 				      struct bpf_tramp_link *link,
364 				      const struct btf_func_model *model,
365 				      void *stub_func, void *image, void *image_end)
366 {
367 	u32 flags = BPF_TRAMP_F_INDIRECT;
368 	int size;
369 
370 	tlinks[BPF_TRAMP_FENTRY].links[0] = link;
371 	tlinks[BPF_TRAMP_FENTRY].nr_links = 1;
372 
373 	if (model->ret_size > 0)
374 		flags |= BPF_TRAMP_F_RET_FENTRY_RET;
375 
376 	size = arch_bpf_trampoline_size(model, flags, tlinks, NULL);
377 	if (size < 0)
378 		return size;
379 	if (size > (unsigned long)image_end - (unsigned long)image)
380 		return -E2BIG;
381 	return arch_prepare_bpf_trampoline(NULL, image, image_end,
382 					   model, flags, tlinks, stub_func);
383 }
384 
385 static long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key,
386 					   void *value, u64 flags)
387 {
388 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
389 	const struct bpf_struct_ops_desc *st_ops_desc = st_map->st_ops_desc;
390 	const struct bpf_struct_ops *st_ops = st_ops_desc->st_ops;
391 	struct bpf_struct_ops_value *uvalue, *kvalue;
392 	const struct btf_type *module_type;
393 	const struct btf_member *member;
394 	const struct btf_type *t = st_ops_desc->type;
395 	struct bpf_tramp_links *tlinks;
396 	void *udata, *kdata;
397 	int prog_fd, err;
398 	void *image, *image_end;
399 	u32 i;
400 
401 	if (flags)
402 		return -EINVAL;
403 
404 	if (*(u32 *)key != 0)
405 		return -E2BIG;
406 
407 	err = check_zero_holes(st_map->btf, st_ops_desc->value_type, value);
408 	if (err)
409 		return err;
410 
411 	uvalue = value;
412 	err = check_zero_holes(st_map->btf, t, uvalue->data);
413 	if (err)
414 		return err;
415 
416 	if (uvalue->state || refcount_read(&uvalue->refcnt))
417 		return -EINVAL;
418 
419 	tlinks = kcalloc(BPF_TRAMP_MAX, sizeof(*tlinks), GFP_KERNEL);
420 	if (!tlinks)
421 		return -ENOMEM;
422 
423 	uvalue = (struct bpf_struct_ops_value *)st_map->uvalue;
424 	kvalue = (struct bpf_struct_ops_value *)&st_map->kvalue;
425 
426 	mutex_lock(&st_map->lock);
427 
428 	if (kvalue->state != BPF_STRUCT_OPS_STATE_INIT) {
429 		err = -EBUSY;
430 		goto unlock;
431 	}
432 
433 	memcpy(uvalue, value, map->value_size);
434 
435 	udata = &uvalue->data;
436 	kdata = &kvalue->data;
437 	image = st_map->image;
438 	image_end = st_map->image + PAGE_SIZE;
439 
440 	module_type = btf_type_by_id(btf_vmlinux, st_ops_ids[IDX_MODULE_ID]);
441 	for_each_member(i, t, member) {
442 		const struct btf_type *mtype, *ptype;
443 		struct bpf_prog *prog;
444 		struct bpf_tramp_link *link;
445 		u32 moff;
446 
447 		moff = __btf_member_bit_offset(t, member) / 8;
448 		ptype = btf_type_resolve_ptr(st_map->btf, member->type, NULL);
449 		if (ptype == module_type) {
450 			if (*(void **)(udata + moff))
451 				goto reset_unlock;
452 			*(void **)(kdata + moff) = BPF_MODULE_OWNER;
453 			continue;
454 		}
455 
456 		err = st_ops->init_member(t, member, kdata, udata);
457 		if (err < 0)
458 			goto reset_unlock;
459 
460 		/* The ->init_member() has handled this member */
461 		if (err > 0)
462 			continue;
463 
464 		/* If st_ops->init_member does not handle it,
465 		 * we will only handle func ptrs and zero-ed members
466 		 * here.  Reject everything else.
467 		 */
468 
469 		/* All non func ptr member must be 0 */
470 		if (!ptype || !btf_type_is_func_proto(ptype)) {
471 			u32 msize;
472 
473 			mtype = btf_type_by_id(st_map->btf, member->type);
474 			mtype = btf_resolve_size(st_map->btf, mtype, &msize);
475 			if (IS_ERR(mtype)) {
476 				err = PTR_ERR(mtype);
477 				goto reset_unlock;
478 			}
479 
480 			if (memchr_inv(udata + moff, 0, msize)) {
481 				err = -EINVAL;
482 				goto reset_unlock;
483 			}
484 
485 			continue;
486 		}
487 
488 		prog_fd = (int)(*(unsigned long *)(udata + moff));
489 		/* Similar check as the attr->attach_prog_fd */
490 		if (!prog_fd)
491 			continue;
492 
493 		prog = bpf_prog_get(prog_fd);
494 		if (IS_ERR(prog)) {
495 			err = PTR_ERR(prog);
496 			goto reset_unlock;
497 		}
498 
499 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
500 		    prog->aux->attach_btf_id != st_ops_desc->type_id ||
501 		    prog->expected_attach_type != i) {
502 			bpf_prog_put(prog);
503 			err = -EINVAL;
504 			goto reset_unlock;
505 		}
506 
507 		link = kzalloc(sizeof(*link), GFP_USER);
508 		if (!link) {
509 			bpf_prog_put(prog);
510 			err = -ENOMEM;
511 			goto reset_unlock;
512 		}
513 		bpf_link_init(&link->link, BPF_LINK_TYPE_STRUCT_OPS,
514 			      &bpf_struct_ops_link_lops, prog);
515 		st_map->links[i] = &link->link;
516 
517 		err = bpf_struct_ops_prepare_trampoline(tlinks, link,
518 							&st_ops->func_models[i],
519 							*(void **)(st_ops->cfi_stubs + moff),
520 							image, image_end);
521 		if (err < 0)
522 			goto reset_unlock;
523 
524 		*(void **)(kdata + moff) = image + cfi_get_offset();
525 		image += err;
526 
527 		/* put prog_id to udata */
528 		*(unsigned long *)(udata + moff) = prog->aux->id;
529 	}
530 
531 	if (st_map->map.map_flags & BPF_F_LINK) {
532 		err = 0;
533 		if (st_ops->validate) {
534 			err = st_ops->validate(kdata);
535 			if (err)
536 				goto reset_unlock;
537 		}
538 		arch_protect_bpf_trampoline(st_map->image, PAGE_SIZE);
539 		/* Let bpf_link handle registration & unregistration.
540 		 *
541 		 * Pair with smp_load_acquire() during lookup_elem().
542 		 */
543 		smp_store_release(&kvalue->state, BPF_STRUCT_OPS_STATE_READY);
544 		goto unlock;
545 	}
546 
547 	arch_protect_bpf_trampoline(st_map->image, PAGE_SIZE);
548 	err = st_ops->reg(kdata);
549 	if (likely(!err)) {
550 		/* This refcnt increment on the map here after
551 		 * 'st_ops->reg()' is secure since the state of the
552 		 * map must be set to INIT at this moment, and thus
553 		 * bpf_struct_ops_map_delete_elem() can't unregister
554 		 * or transition it to TOBEFREE concurrently.
555 		 */
556 		bpf_map_inc(map);
557 		/* Pair with smp_load_acquire() during lookup_elem().
558 		 * It ensures the above udata updates (e.g. prog->aux->id)
559 		 * can be seen once BPF_STRUCT_OPS_STATE_INUSE is set.
560 		 */
561 		smp_store_release(&kvalue->state, BPF_STRUCT_OPS_STATE_INUSE);
562 		goto unlock;
563 	}
564 
565 	/* Error during st_ops->reg(). Can happen if this struct_ops needs to be
566 	 * verified as a whole, after all init_member() calls. Can also happen if
567 	 * there was a race in registering the struct_ops (under the same name) to
568 	 * a sub-system through different struct_ops's maps.
569 	 */
570 	arch_unprotect_bpf_trampoline(st_map->image, PAGE_SIZE);
571 
572 reset_unlock:
573 	bpf_struct_ops_map_put_progs(st_map);
574 	memset(uvalue, 0, map->value_size);
575 	memset(kvalue, 0, map->value_size);
576 unlock:
577 	kfree(tlinks);
578 	mutex_unlock(&st_map->lock);
579 	return err;
580 }
581 
582 static long bpf_struct_ops_map_delete_elem(struct bpf_map *map, void *key)
583 {
584 	enum bpf_struct_ops_state prev_state;
585 	struct bpf_struct_ops_map *st_map;
586 
587 	st_map = (struct bpf_struct_ops_map *)map;
588 	if (st_map->map.map_flags & BPF_F_LINK)
589 		return -EOPNOTSUPP;
590 
591 	prev_state = cmpxchg(&st_map->kvalue.state,
592 			     BPF_STRUCT_OPS_STATE_INUSE,
593 			     BPF_STRUCT_OPS_STATE_TOBEFREE);
594 	switch (prev_state) {
595 	case BPF_STRUCT_OPS_STATE_INUSE:
596 		st_map->st_ops_desc->st_ops->unreg(&st_map->kvalue.data);
597 		bpf_map_put(map);
598 		return 0;
599 	case BPF_STRUCT_OPS_STATE_TOBEFREE:
600 		return -EINPROGRESS;
601 	case BPF_STRUCT_OPS_STATE_INIT:
602 		return -ENOENT;
603 	default:
604 		WARN_ON_ONCE(1);
605 		/* Should never happen.  Treat it as not found. */
606 		return -ENOENT;
607 	}
608 }
609 
610 static void bpf_struct_ops_map_seq_show_elem(struct bpf_map *map, void *key,
611 					     struct seq_file *m)
612 {
613 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
614 	void *value;
615 	int err;
616 
617 	value = kmalloc(map->value_size, GFP_USER | __GFP_NOWARN);
618 	if (!value)
619 		return;
620 
621 	err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
622 	if (!err) {
623 		btf_type_seq_show(st_map->btf,
624 				  map->btf_vmlinux_value_type_id,
625 				  value, m);
626 		seq_puts(m, "\n");
627 	}
628 
629 	kfree(value);
630 }
631 
632 static void __bpf_struct_ops_map_free(struct bpf_map *map)
633 {
634 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
635 
636 	if (st_map->links)
637 		bpf_struct_ops_map_put_progs(st_map);
638 	bpf_map_area_free(st_map->links);
639 	if (st_map->image) {
640 		arch_free_bpf_trampoline(st_map->image, PAGE_SIZE);
641 		bpf_jit_uncharge_modmem(PAGE_SIZE);
642 	}
643 	bpf_map_area_free(st_map->uvalue);
644 	bpf_map_area_free(st_map);
645 }
646 
647 static void bpf_struct_ops_map_free(struct bpf_map *map)
648 {
649 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
650 
651 	/* st_ops->owner was acquired during map_alloc to implicitly holds
652 	 * the btf's refcnt. The acquire was only done when btf_is_module()
653 	 * st_map->btf cannot be NULL here.
654 	 */
655 	if (btf_is_module(st_map->btf))
656 		module_put(st_map->st_ops_desc->st_ops->owner);
657 
658 	/* The struct_ops's function may switch to another struct_ops.
659 	 *
660 	 * For example, bpf_tcp_cc_x->init() may switch to
661 	 * another tcp_cc_y by calling
662 	 * setsockopt(TCP_CONGESTION, "tcp_cc_y").
663 	 * During the switch,  bpf_struct_ops_put(tcp_cc_x) is called
664 	 * and its refcount may reach 0 which then free its
665 	 * trampoline image while tcp_cc_x is still running.
666 	 *
667 	 * A vanilla rcu gp is to wait for all bpf-tcp-cc prog
668 	 * to finish. bpf-tcp-cc prog is non sleepable.
669 	 * A rcu_tasks gp is to wait for the last few insn
670 	 * in the tramopline image to finish before releasing
671 	 * the trampoline image.
672 	 */
673 	synchronize_rcu_mult(call_rcu, call_rcu_tasks);
674 
675 	__bpf_struct_ops_map_free(map);
676 }
677 
678 static int bpf_struct_ops_map_alloc_check(union bpf_attr *attr)
679 {
680 	if (attr->key_size != sizeof(unsigned int) || attr->max_entries != 1 ||
681 	    (attr->map_flags & ~(BPF_F_LINK | BPF_F_VTYPE_BTF_OBJ_FD)) ||
682 	    !attr->btf_vmlinux_value_type_id)
683 		return -EINVAL;
684 	return 0;
685 }
686 
687 static struct bpf_map *bpf_struct_ops_map_alloc(union bpf_attr *attr)
688 {
689 	const struct bpf_struct_ops_desc *st_ops_desc;
690 	size_t st_map_size;
691 	struct bpf_struct_ops_map *st_map;
692 	const struct btf_type *t, *vt;
693 	struct module *mod = NULL;
694 	struct bpf_map *map;
695 	struct btf *btf;
696 	int ret;
697 
698 	if (attr->map_flags & BPF_F_VTYPE_BTF_OBJ_FD) {
699 		/* The map holds btf for its whole life time. */
700 		btf = btf_get_by_fd(attr->value_type_btf_obj_fd);
701 		if (IS_ERR(btf))
702 			return ERR_CAST(btf);
703 		if (!btf_is_module(btf)) {
704 			btf_put(btf);
705 			return ERR_PTR(-EINVAL);
706 		}
707 
708 		mod = btf_try_get_module(btf);
709 		/* mod holds a refcnt to btf. We don't need an extra refcnt
710 		 * here.
711 		 */
712 		btf_put(btf);
713 		if (!mod)
714 			return ERR_PTR(-EINVAL);
715 	} else {
716 		btf = bpf_get_btf_vmlinux();
717 		if (IS_ERR(btf))
718 			return ERR_CAST(btf);
719 	}
720 
721 	st_ops_desc = bpf_struct_ops_find_value(btf, attr->btf_vmlinux_value_type_id);
722 	if (!st_ops_desc) {
723 		ret = -ENOTSUPP;
724 		goto errout;
725 	}
726 
727 	vt = st_ops_desc->value_type;
728 	if (attr->value_size != vt->size) {
729 		ret = -EINVAL;
730 		goto errout;
731 	}
732 
733 	t = st_ops_desc->type;
734 
735 	st_map_size = sizeof(*st_map) +
736 		/* kvalue stores the
737 		 * struct bpf_struct_ops_tcp_congestions_ops
738 		 */
739 		(vt->size - sizeof(struct bpf_struct_ops_value));
740 
741 	st_map = bpf_map_area_alloc(st_map_size, NUMA_NO_NODE);
742 	if (!st_map) {
743 		ret = -ENOMEM;
744 		goto errout;
745 	}
746 
747 	st_map->st_ops_desc = st_ops_desc;
748 	map = &st_map->map;
749 
750 	ret = bpf_jit_charge_modmem(PAGE_SIZE);
751 	if (ret)
752 		goto errout_free;
753 
754 	st_map->image = arch_alloc_bpf_trampoline(PAGE_SIZE);
755 	if (!st_map->image) {
756 		/* __bpf_struct_ops_map_free() uses st_map->image as flag
757 		 * for "charged or not". In this case, we need to unchange
758 		 * here.
759 		 */
760 		bpf_jit_uncharge_modmem(PAGE_SIZE);
761 		ret = -ENOMEM;
762 		goto errout_free;
763 	}
764 	st_map->uvalue = bpf_map_area_alloc(vt->size, NUMA_NO_NODE);
765 	st_map->links_cnt = btf_type_vlen(t);
766 	st_map->links =
767 		bpf_map_area_alloc(st_map->links_cnt * sizeof(struct bpf_links *),
768 				   NUMA_NO_NODE);
769 	if (!st_map->uvalue || !st_map->links) {
770 		ret = -ENOMEM;
771 		goto errout_free;
772 	}
773 	st_map->btf = btf;
774 
775 	mutex_init(&st_map->lock);
776 	bpf_map_init_from_attr(map, attr);
777 
778 	return map;
779 
780 errout_free:
781 	__bpf_struct_ops_map_free(map);
782 errout:
783 	module_put(mod);
784 
785 	return ERR_PTR(ret);
786 }
787 
788 static u64 bpf_struct_ops_map_mem_usage(const struct bpf_map *map)
789 {
790 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
791 	const struct bpf_struct_ops_desc *st_ops_desc = st_map->st_ops_desc;
792 	const struct btf_type *vt = st_ops_desc->value_type;
793 	u64 usage;
794 
795 	usage = sizeof(*st_map) +
796 			vt->size - sizeof(struct bpf_struct_ops_value);
797 	usage += vt->size;
798 	usage += btf_type_vlen(vt) * sizeof(struct bpf_links *);
799 	usage += PAGE_SIZE;
800 	return usage;
801 }
802 
803 BTF_ID_LIST_SINGLE(bpf_struct_ops_map_btf_ids, struct, bpf_struct_ops_map)
804 const struct bpf_map_ops bpf_struct_ops_map_ops = {
805 	.map_alloc_check = bpf_struct_ops_map_alloc_check,
806 	.map_alloc = bpf_struct_ops_map_alloc,
807 	.map_free = bpf_struct_ops_map_free,
808 	.map_get_next_key = bpf_struct_ops_map_get_next_key,
809 	.map_lookup_elem = bpf_struct_ops_map_lookup_elem,
810 	.map_delete_elem = bpf_struct_ops_map_delete_elem,
811 	.map_update_elem = bpf_struct_ops_map_update_elem,
812 	.map_seq_show_elem = bpf_struct_ops_map_seq_show_elem,
813 	.map_mem_usage = bpf_struct_ops_map_mem_usage,
814 	.map_btf_id = &bpf_struct_ops_map_btf_ids[0],
815 };
816 
817 /* "const void *" because some subsystem is
818  * passing a const (e.g. const struct tcp_congestion_ops *)
819  */
820 bool bpf_struct_ops_get(const void *kdata)
821 {
822 	struct bpf_struct_ops_value *kvalue;
823 	struct bpf_struct_ops_map *st_map;
824 	struct bpf_map *map;
825 
826 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
827 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
828 
829 	map = __bpf_map_inc_not_zero(&st_map->map, false);
830 	return !IS_ERR(map);
831 }
832 
833 void bpf_struct_ops_put(const void *kdata)
834 {
835 	struct bpf_struct_ops_value *kvalue;
836 	struct bpf_struct_ops_map *st_map;
837 
838 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
839 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
840 
841 	bpf_map_put(&st_map->map);
842 }
843 
844 static bool bpf_struct_ops_valid_to_reg(struct bpf_map *map)
845 {
846 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
847 
848 	return map->map_type == BPF_MAP_TYPE_STRUCT_OPS &&
849 		map->map_flags & BPF_F_LINK &&
850 		/* Pair with smp_store_release() during map_update */
851 		smp_load_acquire(&st_map->kvalue.state) == BPF_STRUCT_OPS_STATE_READY;
852 }
853 
854 static void bpf_struct_ops_map_link_dealloc(struct bpf_link *link)
855 {
856 	struct bpf_struct_ops_link *st_link;
857 	struct bpf_struct_ops_map *st_map;
858 
859 	st_link = container_of(link, struct bpf_struct_ops_link, link);
860 	st_map = (struct bpf_struct_ops_map *)
861 		rcu_dereference_protected(st_link->map, true);
862 	if (st_map) {
863 		/* st_link->map can be NULL if
864 		 * bpf_struct_ops_link_create() fails to register.
865 		 */
866 		st_map->st_ops_desc->st_ops->unreg(&st_map->kvalue.data);
867 		bpf_map_put(&st_map->map);
868 	}
869 	kfree(st_link);
870 }
871 
872 static void bpf_struct_ops_map_link_show_fdinfo(const struct bpf_link *link,
873 					    struct seq_file *seq)
874 {
875 	struct bpf_struct_ops_link *st_link;
876 	struct bpf_map *map;
877 
878 	st_link = container_of(link, struct bpf_struct_ops_link, link);
879 	rcu_read_lock();
880 	map = rcu_dereference(st_link->map);
881 	seq_printf(seq, "map_id:\t%d\n", map->id);
882 	rcu_read_unlock();
883 }
884 
885 static int bpf_struct_ops_map_link_fill_link_info(const struct bpf_link *link,
886 					       struct bpf_link_info *info)
887 {
888 	struct bpf_struct_ops_link *st_link;
889 	struct bpf_map *map;
890 
891 	st_link = container_of(link, struct bpf_struct_ops_link, link);
892 	rcu_read_lock();
893 	map = rcu_dereference(st_link->map);
894 	info->struct_ops.map_id = map->id;
895 	rcu_read_unlock();
896 	return 0;
897 }
898 
899 static int bpf_struct_ops_map_link_update(struct bpf_link *link, struct bpf_map *new_map,
900 					  struct bpf_map *expected_old_map)
901 {
902 	struct bpf_struct_ops_map *st_map, *old_st_map;
903 	struct bpf_map *old_map;
904 	struct bpf_struct_ops_link *st_link;
905 	int err;
906 
907 	st_link = container_of(link, struct bpf_struct_ops_link, link);
908 	st_map = container_of(new_map, struct bpf_struct_ops_map, map);
909 
910 	if (!bpf_struct_ops_valid_to_reg(new_map))
911 		return -EINVAL;
912 
913 	if (!st_map->st_ops_desc->st_ops->update)
914 		return -EOPNOTSUPP;
915 
916 	mutex_lock(&update_mutex);
917 
918 	old_map = rcu_dereference_protected(st_link->map, lockdep_is_held(&update_mutex));
919 	if (expected_old_map && old_map != expected_old_map) {
920 		err = -EPERM;
921 		goto err_out;
922 	}
923 
924 	old_st_map = container_of(old_map, struct bpf_struct_ops_map, map);
925 	/* The new and old struct_ops must be the same type. */
926 	if (st_map->st_ops_desc != old_st_map->st_ops_desc) {
927 		err = -EINVAL;
928 		goto err_out;
929 	}
930 
931 	err = st_map->st_ops_desc->st_ops->update(st_map->kvalue.data, old_st_map->kvalue.data);
932 	if (err)
933 		goto err_out;
934 
935 	bpf_map_inc(new_map);
936 	rcu_assign_pointer(st_link->map, new_map);
937 	bpf_map_put(old_map);
938 
939 err_out:
940 	mutex_unlock(&update_mutex);
941 
942 	return err;
943 }
944 
945 static const struct bpf_link_ops bpf_struct_ops_map_lops = {
946 	.dealloc = bpf_struct_ops_map_link_dealloc,
947 	.show_fdinfo = bpf_struct_ops_map_link_show_fdinfo,
948 	.fill_link_info = bpf_struct_ops_map_link_fill_link_info,
949 	.update_map = bpf_struct_ops_map_link_update,
950 };
951 
952 int bpf_struct_ops_link_create(union bpf_attr *attr)
953 {
954 	struct bpf_struct_ops_link *link = NULL;
955 	struct bpf_link_primer link_primer;
956 	struct bpf_struct_ops_map *st_map;
957 	struct bpf_map *map;
958 	int err;
959 
960 	map = bpf_map_get(attr->link_create.map_fd);
961 	if (IS_ERR(map))
962 		return PTR_ERR(map);
963 
964 	st_map = (struct bpf_struct_ops_map *)map;
965 
966 	if (!bpf_struct_ops_valid_to_reg(map)) {
967 		err = -EINVAL;
968 		goto err_out;
969 	}
970 
971 	link = kzalloc(sizeof(*link), GFP_USER);
972 	if (!link) {
973 		err = -ENOMEM;
974 		goto err_out;
975 	}
976 	bpf_link_init(&link->link, BPF_LINK_TYPE_STRUCT_OPS, &bpf_struct_ops_map_lops, NULL);
977 
978 	err = bpf_link_prime(&link->link, &link_primer);
979 	if (err)
980 		goto err_out;
981 
982 	err = st_map->st_ops_desc->st_ops->reg(st_map->kvalue.data);
983 	if (err) {
984 		bpf_link_cleanup(&link_primer);
985 		link = NULL;
986 		goto err_out;
987 	}
988 	RCU_INIT_POINTER(link->map, map);
989 
990 	return bpf_link_settle(&link_primer);
991 
992 err_out:
993 	bpf_map_put(map);
994 	kfree(link);
995 	return err;
996 }
997 
998 void bpf_map_struct_ops_info_fill(struct bpf_map_info *info, struct bpf_map *map)
999 {
1000 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
1001 
1002 	info->btf_vmlinux_id = btf_obj_id(st_map->btf);
1003 }
1004