xref: /linux-6.15/kernel/bpf/bpf_struct_ops.c (revision fcc2c1fb)
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 	/* image is a page that has all the trampolines
44 	 * that stores the func args before calling the bpf_prog.
45 	 * A PAGE_SIZE "image" is enough to store all trampoline for
46 	 * "links[]".
47 	 */
48 	void *image;
49 	/* The owner moduler's btf. */
50 	struct btf *btf;
51 	/* uvalue->data stores the kernel struct
52 	 * (e.g. tcp_congestion_ops) that is more useful
53 	 * to userspace than the kvalue.  For example,
54 	 * the bpf_prog's id is stored instead of the kernel
55 	 * address of a func ptr.
56 	 */
57 	struct bpf_struct_ops_value *uvalue;
58 	/* kvalue.data stores the actual kernel's struct
59 	 * (e.g. tcp_congestion_ops) that will be
60 	 * registered to the kernel subsystem.
61 	 */
62 	struct bpf_struct_ops_value kvalue;
63 };
64 
65 struct bpf_struct_ops_link {
66 	struct bpf_link link;
67 	struct bpf_map __rcu *map;
68 };
69 
70 static DEFINE_MUTEX(update_mutex);
71 
72 #define VALUE_PREFIX "bpf_struct_ops_"
73 #define VALUE_PREFIX_LEN (sizeof(VALUE_PREFIX) - 1)
74 
75 /* bpf_struct_ops_##_name (e.g. bpf_struct_ops_tcp_congestion_ops) is
76  * the map's value exposed to the userspace and its btf-type-id is
77  * stored at the map->btf_vmlinux_value_type_id.
78  *
79  */
80 #define BPF_STRUCT_OPS_TYPE(_name)				\
81 extern struct bpf_struct_ops bpf_##_name;			\
82 								\
83 struct bpf_struct_ops_##_name {						\
84 	BPF_STRUCT_OPS_COMMON_VALUE;				\
85 	struct _name data ____cacheline_aligned_in_smp;		\
86 };
87 #include "bpf_struct_ops_types.h"
88 #undef BPF_STRUCT_OPS_TYPE
89 
90 enum {
91 #define BPF_STRUCT_OPS_TYPE(_name) BPF_STRUCT_OPS_TYPE_##_name,
92 #include "bpf_struct_ops_types.h"
93 #undef BPF_STRUCT_OPS_TYPE
94 	__NR_BPF_STRUCT_OPS_TYPE,
95 };
96 
97 static struct bpf_struct_ops_desc bpf_struct_ops[] = {
98 #define BPF_STRUCT_OPS_TYPE(_name)				\
99 	[BPF_STRUCT_OPS_TYPE_##_name] = { .st_ops = &bpf_##_name },
100 #include "bpf_struct_ops_types.h"
101 #undef BPF_STRUCT_OPS_TYPE
102 };
103 
104 const struct bpf_verifier_ops bpf_struct_ops_verifier_ops = {
105 };
106 
107 const struct bpf_prog_ops bpf_struct_ops_prog_ops = {
108 #ifdef CONFIG_NET
109 	.test_run = bpf_struct_ops_test_run,
110 #endif
111 };
112 
113 BTF_ID_LIST(st_ops_ids)
114 BTF_ID(struct, module)
115 
116 enum {
117 	IDX_MODULE_ID,
118 };
119 
120 static void bpf_struct_ops_desc_init(struct bpf_struct_ops_desc *st_ops_desc,
121 				     struct btf *btf,
122 				     struct bpf_verifier_log *log)
123 {
124 	struct bpf_struct_ops *st_ops = st_ops_desc->st_ops;
125 	const struct btf_member *member;
126 	const struct btf_type *t;
127 	s32 type_id, value_id;
128 	char value_name[128];
129 	const char *mname;
130 	int i;
131 
132 	if (strlen(st_ops->name) + VALUE_PREFIX_LEN >=
133 	    sizeof(value_name)) {
134 		pr_warn("struct_ops name %s is too long\n",
135 			st_ops->name);
136 		return;
137 	}
138 	sprintf(value_name, "%s%s", VALUE_PREFIX, st_ops->name);
139 
140 	value_id = btf_find_by_name_kind(btf, value_name,
141 					 BTF_KIND_STRUCT);
142 	if (value_id < 0) {
143 		pr_warn("Cannot find struct %s in %s\n",
144 			value_name, btf_get_name(btf));
145 		return;
146 	}
147 
148 	type_id = btf_find_by_name_kind(btf, st_ops->name,
149 					BTF_KIND_STRUCT);
150 	if (type_id < 0) {
151 		pr_warn("Cannot find struct %s in %s\n",
152 			st_ops->name, btf_get_name(btf));
153 		return;
154 	}
155 	t = btf_type_by_id(btf, type_id);
156 	if (btf_type_vlen(t) > BPF_STRUCT_OPS_MAX_NR_MEMBERS) {
157 		pr_warn("Cannot support #%u members in struct %s\n",
158 			btf_type_vlen(t), st_ops->name);
159 		return;
160 	}
161 
162 	for_each_member(i, t, member) {
163 		const struct btf_type *func_proto;
164 
165 		mname = btf_name_by_offset(btf, member->name_off);
166 		if (!*mname) {
167 			pr_warn("anon member in struct %s is not supported\n",
168 				st_ops->name);
169 			break;
170 		}
171 
172 		if (__btf_member_bitfield_size(t, member)) {
173 			pr_warn("bit field member %s in struct %s is not supported\n",
174 				mname, st_ops->name);
175 			break;
176 		}
177 
178 		func_proto = btf_type_resolve_func_ptr(btf,
179 						       member->type,
180 						       NULL);
181 		if (func_proto &&
182 		    btf_distill_func_proto(log, btf,
183 					   func_proto, mname,
184 					   &st_ops->func_models[i])) {
185 			pr_warn("Error in parsing func ptr %s in struct %s\n",
186 				mname, st_ops->name);
187 			break;
188 		}
189 	}
190 
191 	if (i == btf_type_vlen(t)) {
192 		if (st_ops->init(btf)) {
193 			pr_warn("Error in init bpf_struct_ops %s\n",
194 				st_ops->name);
195 		} else {
196 			st_ops_desc->type_id = type_id;
197 			st_ops_desc->type = t;
198 			st_ops_desc->value_id = value_id;
199 			st_ops_desc->value_type = btf_type_by_id(btf,
200 								 value_id);
201 		}
202 	}
203 }
204 
205 void bpf_struct_ops_init(struct btf *btf, struct bpf_verifier_log *log)
206 {
207 	struct bpf_struct_ops_desc *st_ops_desc;
208 	u32 i;
209 
210 	/* Ensure BTF type is emitted for "struct bpf_struct_ops_##_name" */
211 #define BPF_STRUCT_OPS_TYPE(_name) BTF_TYPE_EMIT(struct bpf_struct_ops_##_name);
212 #include "bpf_struct_ops_types.h"
213 #undef BPF_STRUCT_OPS_TYPE
214 
215 	for (i = 0; i < ARRAY_SIZE(bpf_struct_ops); i++) {
216 		st_ops_desc = &bpf_struct_ops[i];
217 		bpf_struct_ops_desc_init(st_ops_desc, btf, log);
218 	}
219 }
220 
221 extern struct btf *btf_vmlinux;
222 
223 static const struct bpf_struct_ops_desc *
224 bpf_struct_ops_find_value(struct btf *btf, u32 value_id)
225 {
226 	unsigned int i;
227 
228 	if (!value_id || !btf)
229 		return NULL;
230 
231 	for (i = 0; i < ARRAY_SIZE(bpf_struct_ops); i++) {
232 		if (bpf_struct_ops[i].value_id == value_id)
233 			return &bpf_struct_ops[i];
234 	}
235 
236 	return NULL;
237 }
238 
239 const struct bpf_struct_ops_desc *
240 bpf_struct_ops_find(struct btf *btf, u32 type_id)
241 {
242 	unsigned int i;
243 
244 	if (!type_id || !btf)
245 		return NULL;
246 
247 	for (i = 0; i < ARRAY_SIZE(bpf_struct_ops); i++) {
248 		if (bpf_struct_ops[i].type_id == type_id)
249 			return &bpf_struct_ops[i];
250 	}
251 
252 	return NULL;
253 }
254 
255 static int bpf_struct_ops_map_get_next_key(struct bpf_map *map, void *key,
256 					   void *next_key)
257 {
258 	if (key && *(u32 *)key == 0)
259 		return -ENOENT;
260 
261 	*(u32 *)next_key = 0;
262 	return 0;
263 }
264 
265 int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map, void *key,
266 				       void *value)
267 {
268 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
269 	struct bpf_struct_ops_value *uvalue, *kvalue;
270 	enum bpf_struct_ops_state state;
271 	s64 refcnt;
272 
273 	if (unlikely(*(u32 *)key != 0))
274 		return -ENOENT;
275 
276 	kvalue = &st_map->kvalue;
277 	/* Pair with smp_store_release() during map_update */
278 	state = smp_load_acquire(&kvalue->state);
279 	if (state == BPF_STRUCT_OPS_STATE_INIT) {
280 		memset(value, 0, map->value_size);
281 		return 0;
282 	}
283 
284 	/* No lock is needed.  state and refcnt do not need
285 	 * to be updated together under atomic context.
286 	 */
287 	uvalue = value;
288 	memcpy(uvalue, st_map->uvalue, map->value_size);
289 	uvalue->state = state;
290 
291 	/* This value offers the user space a general estimate of how
292 	 * many sockets are still utilizing this struct_ops for TCP
293 	 * congestion control. The number might not be exact, but it
294 	 * should sufficiently meet our present goals.
295 	 */
296 	refcnt = atomic64_read(&map->refcnt) - atomic64_read(&map->usercnt);
297 	refcount_set(&uvalue->refcnt, max_t(s64, refcnt, 0));
298 
299 	return 0;
300 }
301 
302 static void *bpf_struct_ops_map_lookup_elem(struct bpf_map *map, void *key)
303 {
304 	return ERR_PTR(-EINVAL);
305 }
306 
307 static void bpf_struct_ops_map_put_progs(struct bpf_struct_ops_map *st_map)
308 {
309 	const struct btf_type *t = st_map->st_ops_desc->type;
310 	u32 i;
311 
312 	for (i = 0; i < btf_type_vlen(t); 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 	btf_put(st_map->btf);
645 	bpf_map_area_free(st_map);
646 }
647 
648 static void bpf_struct_ops_map_free(struct bpf_map *map)
649 {
650 	/* The struct_ops's function may switch to another struct_ops.
651 	 *
652 	 * For example, bpf_tcp_cc_x->init() may switch to
653 	 * another tcp_cc_y by calling
654 	 * setsockopt(TCP_CONGESTION, "tcp_cc_y").
655 	 * During the switch,  bpf_struct_ops_put(tcp_cc_x) is called
656 	 * and its refcount may reach 0 which then free its
657 	 * trampoline image while tcp_cc_x is still running.
658 	 *
659 	 * A vanilla rcu gp is to wait for all bpf-tcp-cc prog
660 	 * to finish. bpf-tcp-cc prog is non sleepable.
661 	 * A rcu_tasks gp is to wait for the last few insn
662 	 * in the tramopline image to finish before releasing
663 	 * the trampoline image.
664 	 */
665 	synchronize_rcu_mult(call_rcu, call_rcu_tasks);
666 
667 	__bpf_struct_ops_map_free(map);
668 }
669 
670 static int bpf_struct_ops_map_alloc_check(union bpf_attr *attr)
671 {
672 	if (attr->key_size != sizeof(unsigned int) || attr->max_entries != 1 ||
673 	    (attr->map_flags & ~(BPF_F_LINK | BPF_F_VTYPE_BTF_OBJ_FD)) ||
674 	    !attr->btf_vmlinux_value_type_id)
675 		return -EINVAL;
676 	return 0;
677 }
678 
679 static struct bpf_map *bpf_struct_ops_map_alloc(union bpf_attr *attr)
680 {
681 	const struct bpf_struct_ops_desc *st_ops_desc;
682 	size_t st_map_size;
683 	struct bpf_struct_ops_map *st_map;
684 	const struct btf_type *t, *vt;
685 	struct bpf_map *map;
686 	struct btf *btf;
687 	int ret;
688 
689 	if (attr->map_flags & BPF_F_VTYPE_BTF_OBJ_FD) {
690 		/* The map holds btf for its whole life time. */
691 		btf = btf_get_by_fd(attr->value_type_btf_obj_fd);
692 		if (IS_ERR(btf))
693 			return ERR_CAST(btf);
694 		if (!btf_is_module(btf)) {
695 			btf_put(btf);
696 			return ERR_PTR(-EINVAL);
697 		}
698 	} else {
699 		btf = bpf_get_btf_vmlinux();
700 		if (IS_ERR(btf))
701 			return ERR_CAST(btf);
702 		btf_get(btf);
703 	}
704 
705 	st_ops_desc = bpf_struct_ops_find_value(btf, attr->btf_vmlinux_value_type_id);
706 	if (!st_ops_desc) {
707 		ret = -ENOTSUPP;
708 		goto errout;
709 	}
710 
711 	vt = st_ops_desc->value_type;
712 	if (attr->value_size != vt->size) {
713 		ret = -EINVAL;
714 		goto errout;
715 	}
716 
717 	t = st_ops_desc->type;
718 
719 	st_map_size = sizeof(*st_map) +
720 		/* kvalue stores the
721 		 * struct bpf_struct_ops_tcp_congestions_ops
722 		 */
723 		(vt->size - sizeof(struct bpf_struct_ops_value));
724 
725 	st_map = bpf_map_area_alloc(st_map_size, NUMA_NO_NODE);
726 	if (!st_map) {
727 		ret = -ENOMEM;
728 		goto errout;
729 	}
730 
731 	st_map->st_ops_desc = st_ops_desc;
732 	map = &st_map->map;
733 
734 	ret = bpf_jit_charge_modmem(PAGE_SIZE);
735 	if (ret)
736 		goto errout_free;
737 
738 	st_map->image = arch_alloc_bpf_trampoline(PAGE_SIZE);
739 	if (!st_map->image) {
740 		/* __bpf_struct_ops_map_free() uses st_map->image as flag
741 		 * for "charged or not". In this case, we need to unchange
742 		 * here.
743 		 */
744 		bpf_jit_uncharge_modmem(PAGE_SIZE);
745 		ret = -ENOMEM;
746 		goto errout_free;
747 	}
748 	st_map->uvalue = bpf_map_area_alloc(vt->size, NUMA_NO_NODE);
749 	st_map->links =
750 		bpf_map_area_alloc(btf_type_vlen(t) * sizeof(struct bpf_links *),
751 				   NUMA_NO_NODE);
752 	if (!st_map->uvalue || !st_map->links) {
753 		ret = -ENOMEM;
754 		goto errout_free;
755 	}
756 	st_map->btf = btf;
757 
758 	mutex_init(&st_map->lock);
759 	bpf_map_init_from_attr(map, attr);
760 
761 	return map;
762 
763 errout_free:
764 	__bpf_struct_ops_map_free(map);
765 errout:
766 	btf_put(btf);
767 
768 	return ERR_PTR(ret);
769 }
770 
771 static u64 bpf_struct_ops_map_mem_usage(const struct bpf_map *map)
772 {
773 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
774 	const struct bpf_struct_ops_desc *st_ops_desc = st_map->st_ops_desc;
775 	const struct btf_type *vt = st_ops_desc->value_type;
776 	u64 usage;
777 
778 	usage = sizeof(*st_map) +
779 			vt->size - sizeof(struct bpf_struct_ops_value);
780 	usage += vt->size;
781 	usage += btf_type_vlen(vt) * sizeof(struct bpf_links *);
782 	usage += PAGE_SIZE;
783 	return usage;
784 }
785 
786 BTF_ID_LIST_SINGLE(bpf_struct_ops_map_btf_ids, struct, bpf_struct_ops_map)
787 const struct bpf_map_ops bpf_struct_ops_map_ops = {
788 	.map_alloc_check = bpf_struct_ops_map_alloc_check,
789 	.map_alloc = bpf_struct_ops_map_alloc,
790 	.map_free = bpf_struct_ops_map_free,
791 	.map_get_next_key = bpf_struct_ops_map_get_next_key,
792 	.map_lookup_elem = bpf_struct_ops_map_lookup_elem,
793 	.map_delete_elem = bpf_struct_ops_map_delete_elem,
794 	.map_update_elem = bpf_struct_ops_map_update_elem,
795 	.map_seq_show_elem = bpf_struct_ops_map_seq_show_elem,
796 	.map_mem_usage = bpf_struct_ops_map_mem_usage,
797 	.map_btf_id = &bpf_struct_ops_map_btf_ids[0],
798 };
799 
800 /* "const void *" because some subsystem is
801  * passing a const (e.g. const struct tcp_congestion_ops *)
802  */
803 bool bpf_struct_ops_get(const void *kdata)
804 {
805 	struct bpf_struct_ops_value *kvalue;
806 	struct bpf_struct_ops_map *st_map;
807 	struct bpf_map *map;
808 
809 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
810 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
811 
812 	map = __bpf_map_inc_not_zero(&st_map->map, false);
813 	return !IS_ERR(map);
814 }
815 
816 void bpf_struct_ops_put(const void *kdata)
817 {
818 	struct bpf_struct_ops_value *kvalue;
819 	struct bpf_struct_ops_map *st_map;
820 
821 	kvalue = container_of(kdata, struct bpf_struct_ops_value, data);
822 	st_map = container_of(kvalue, struct bpf_struct_ops_map, kvalue);
823 
824 	bpf_map_put(&st_map->map);
825 }
826 
827 static bool bpf_struct_ops_valid_to_reg(struct bpf_map *map)
828 {
829 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
830 
831 	return map->map_type == BPF_MAP_TYPE_STRUCT_OPS &&
832 		map->map_flags & BPF_F_LINK &&
833 		/* Pair with smp_store_release() during map_update */
834 		smp_load_acquire(&st_map->kvalue.state) == BPF_STRUCT_OPS_STATE_READY;
835 }
836 
837 static void bpf_struct_ops_map_link_dealloc(struct bpf_link *link)
838 {
839 	struct bpf_struct_ops_link *st_link;
840 	struct bpf_struct_ops_map *st_map;
841 
842 	st_link = container_of(link, struct bpf_struct_ops_link, link);
843 	st_map = (struct bpf_struct_ops_map *)
844 		rcu_dereference_protected(st_link->map, true);
845 	if (st_map) {
846 		/* st_link->map can be NULL if
847 		 * bpf_struct_ops_link_create() fails to register.
848 		 */
849 		st_map->st_ops_desc->st_ops->unreg(&st_map->kvalue.data);
850 		bpf_map_put(&st_map->map);
851 	}
852 	kfree(st_link);
853 }
854 
855 static void bpf_struct_ops_map_link_show_fdinfo(const struct bpf_link *link,
856 					    struct seq_file *seq)
857 {
858 	struct bpf_struct_ops_link *st_link;
859 	struct bpf_map *map;
860 
861 	st_link = container_of(link, struct bpf_struct_ops_link, link);
862 	rcu_read_lock();
863 	map = rcu_dereference(st_link->map);
864 	seq_printf(seq, "map_id:\t%d\n", map->id);
865 	rcu_read_unlock();
866 }
867 
868 static int bpf_struct_ops_map_link_fill_link_info(const struct bpf_link *link,
869 					       struct bpf_link_info *info)
870 {
871 	struct bpf_struct_ops_link *st_link;
872 	struct bpf_map *map;
873 
874 	st_link = container_of(link, struct bpf_struct_ops_link, link);
875 	rcu_read_lock();
876 	map = rcu_dereference(st_link->map);
877 	info->struct_ops.map_id = map->id;
878 	rcu_read_unlock();
879 	return 0;
880 }
881 
882 static int bpf_struct_ops_map_link_update(struct bpf_link *link, struct bpf_map *new_map,
883 					  struct bpf_map *expected_old_map)
884 {
885 	struct bpf_struct_ops_map *st_map, *old_st_map;
886 	struct bpf_map *old_map;
887 	struct bpf_struct_ops_link *st_link;
888 	int err;
889 
890 	st_link = container_of(link, struct bpf_struct_ops_link, link);
891 	st_map = container_of(new_map, struct bpf_struct_ops_map, map);
892 
893 	if (!bpf_struct_ops_valid_to_reg(new_map))
894 		return -EINVAL;
895 
896 	if (!st_map->st_ops_desc->st_ops->update)
897 		return -EOPNOTSUPP;
898 
899 	mutex_lock(&update_mutex);
900 
901 	old_map = rcu_dereference_protected(st_link->map, lockdep_is_held(&update_mutex));
902 	if (expected_old_map && old_map != expected_old_map) {
903 		err = -EPERM;
904 		goto err_out;
905 	}
906 
907 	old_st_map = container_of(old_map, struct bpf_struct_ops_map, map);
908 	/* The new and old struct_ops must be the same type. */
909 	if (st_map->st_ops_desc != old_st_map->st_ops_desc) {
910 		err = -EINVAL;
911 		goto err_out;
912 	}
913 
914 	err = st_map->st_ops_desc->st_ops->update(st_map->kvalue.data, old_st_map->kvalue.data);
915 	if (err)
916 		goto err_out;
917 
918 	bpf_map_inc(new_map);
919 	rcu_assign_pointer(st_link->map, new_map);
920 	bpf_map_put(old_map);
921 
922 err_out:
923 	mutex_unlock(&update_mutex);
924 
925 	return err;
926 }
927 
928 static const struct bpf_link_ops bpf_struct_ops_map_lops = {
929 	.dealloc = bpf_struct_ops_map_link_dealloc,
930 	.show_fdinfo = bpf_struct_ops_map_link_show_fdinfo,
931 	.fill_link_info = bpf_struct_ops_map_link_fill_link_info,
932 	.update_map = bpf_struct_ops_map_link_update,
933 };
934 
935 int bpf_struct_ops_link_create(union bpf_attr *attr)
936 {
937 	struct bpf_struct_ops_link *link = NULL;
938 	struct bpf_link_primer link_primer;
939 	struct bpf_struct_ops_map *st_map;
940 	struct bpf_map *map;
941 	int err;
942 
943 	map = bpf_map_get(attr->link_create.map_fd);
944 	if (IS_ERR(map))
945 		return PTR_ERR(map);
946 
947 	st_map = (struct bpf_struct_ops_map *)map;
948 
949 	if (!bpf_struct_ops_valid_to_reg(map)) {
950 		err = -EINVAL;
951 		goto err_out;
952 	}
953 
954 	link = kzalloc(sizeof(*link), GFP_USER);
955 	if (!link) {
956 		err = -ENOMEM;
957 		goto err_out;
958 	}
959 	bpf_link_init(&link->link, BPF_LINK_TYPE_STRUCT_OPS, &bpf_struct_ops_map_lops, NULL);
960 
961 	err = bpf_link_prime(&link->link, &link_primer);
962 	if (err)
963 		goto err_out;
964 
965 	err = st_map->st_ops_desc->st_ops->reg(st_map->kvalue.data);
966 	if (err) {
967 		bpf_link_cleanup(&link_primer);
968 		link = NULL;
969 		goto err_out;
970 	}
971 	RCU_INIT_POINTER(link->map, map);
972 
973 	return bpf_link_settle(&link_primer);
974 
975 err_out:
976 	bpf_map_put(map);
977 	kfree(link);
978 	return err;
979 }
980 
981 void bpf_map_struct_ops_info_fill(struct bpf_map_info *info, struct bpf_map *map)
982 {
983 	struct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;
984 
985 	info->btf_vmlinux_id = btf_obj_id(st_map->btf);
986 }
987