xref: /linux/net/bpf/test_run.c (revision f898c16a0624e7f2dcb0b1cda6916c9be6489197)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2017 Facebook
3  */
4 #include <linux/bpf.h>
5 #include <linux/btf.h>
6 #include <linux/btf_ids.h>
7 #include <linux/slab.h>
8 #include <linux/init.h>
9 #include <linux/vmalloc.h>
10 #include <linux/etherdevice.h>
11 #include <linux/filter.h>
12 #include <linux/rcupdate_trace.h>
13 #include <linux/sched/signal.h>
14 #include <net/bpf_sk_storage.h>
15 #include <net/hotdata.h>
16 #include <net/sock.h>
17 #include <net/tcp.h>
18 #include <net/net_namespace.h>
19 #include <net/page_pool/helpers.h>
20 #include <linux/error-injection.h>
21 #include <linux/smp.h>
22 #include <linux/sock_diag.h>
23 #include <linux/netfilter.h>
24 #include <net/netdev_rx_queue.h>
25 #include <net/xdp.h>
26 #include <net/netfilter/nf_bpf_link.h>
27 
28 #define CREATE_TRACE_POINTS
29 #include <trace/events/bpf_test_run.h>
30 
31 struct bpf_test_timer {
32 	enum { NO_PREEMPT, NO_MIGRATE } mode;
33 	u32 i;
34 	u64 time_start, time_spent;
35 };
36 
37 static void bpf_test_timer_enter(struct bpf_test_timer *t)
38 	__acquires(rcu)
39 {
40 	rcu_read_lock();
41 	if (t->mode == NO_PREEMPT)
42 		preempt_disable();
43 	else
44 		migrate_disable();
45 
46 	t->time_start = ktime_get_ns();
47 }
48 
49 static void bpf_test_timer_leave(struct bpf_test_timer *t)
50 	__releases(rcu)
51 {
52 	t->time_start = 0;
53 
54 	if (t->mode == NO_PREEMPT)
55 		preempt_enable();
56 	else
57 		migrate_enable();
58 	rcu_read_unlock();
59 }
60 
61 static bool bpf_test_timer_continue(struct bpf_test_timer *t, int iterations,
62 				    u32 repeat, int *err, u32 *duration)
63 	__must_hold(rcu)
64 {
65 	t->i += iterations;
66 	if (t->i >= repeat) {
67 		/* We're done. */
68 		t->time_spent += ktime_get_ns() - t->time_start;
69 		do_div(t->time_spent, t->i);
70 		*duration = t->time_spent > U32_MAX ? U32_MAX : (u32)t->time_spent;
71 		*err = 0;
72 		goto reset;
73 	}
74 
75 	if (signal_pending(current)) {
76 		/* During iteration: we've been cancelled, abort. */
77 		*err = -EINTR;
78 		goto reset;
79 	}
80 
81 	if (need_resched()) {
82 		/* During iteration: we need to reschedule between runs. */
83 		t->time_spent += ktime_get_ns() - t->time_start;
84 		bpf_test_timer_leave(t);
85 		cond_resched();
86 		bpf_test_timer_enter(t);
87 	}
88 
89 	/* Do another round. */
90 	return true;
91 
92 reset:
93 	t->i = 0;
94 	return false;
95 }
96 
97 /* We put this struct at the head of each page with a context and frame
98  * initialised when the page is allocated, so we don't have to do this on each
99  * repetition of the test run.
100  */
101 struct xdp_page_head {
102 	struct xdp_buff orig_ctx;
103 	struct xdp_buff ctx;
104 	union {
105 		/* ::data_hard_start starts here */
106 		DECLARE_FLEX_ARRAY(struct xdp_frame, frame);
107 		DECLARE_FLEX_ARRAY(u8, data);
108 	};
109 };
110 
111 struct xdp_test_data {
112 	struct xdp_buff *orig_ctx;
113 	struct xdp_rxq_info rxq;
114 	struct net_device *dev;
115 	struct page_pool *pp;
116 	struct xdp_frame **frames;
117 	struct sk_buff **skbs;
118 	struct xdp_mem_info mem;
119 	u32 batch_size;
120 	u32 frame_cnt;
121 };
122 
123 /* tools/testing/selftests/bpf/prog_tests/xdp_do_redirect.c:%MAX_PKT_SIZE
124  * must be updated accordingly this gets changed, otherwise BPF selftests
125  * will fail.
126  */
127 #define TEST_XDP_FRAME_SIZE (PAGE_SIZE - sizeof(struct xdp_page_head))
128 #define TEST_XDP_MAX_BATCH 256
129 
130 static void xdp_test_run_init_page(struct page *page, void *arg)
131 {
132 	struct xdp_page_head *head = phys_to_virt(page_to_phys(page));
133 	struct xdp_buff *new_ctx, *orig_ctx;
134 	u32 headroom = XDP_PACKET_HEADROOM;
135 	struct xdp_test_data *xdp = arg;
136 	size_t frm_len, meta_len;
137 	struct xdp_frame *frm;
138 	void *data;
139 
140 	orig_ctx = xdp->orig_ctx;
141 	frm_len = orig_ctx->data_end - orig_ctx->data_meta;
142 	meta_len = orig_ctx->data - orig_ctx->data_meta;
143 	headroom -= meta_len;
144 
145 	new_ctx = &head->ctx;
146 	frm = head->frame;
147 	data = head->data;
148 	memcpy(data + headroom, orig_ctx->data_meta, frm_len);
149 
150 	xdp_init_buff(new_ctx, TEST_XDP_FRAME_SIZE, &xdp->rxq);
151 	xdp_prepare_buff(new_ctx, data, headroom, frm_len, true);
152 	new_ctx->data = new_ctx->data_meta + meta_len;
153 
154 	xdp_update_frame_from_buff(new_ctx, frm);
155 	frm->mem = new_ctx->rxq->mem;
156 
157 	memcpy(&head->orig_ctx, new_ctx, sizeof(head->orig_ctx));
158 }
159 
160 static int xdp_test_run_setup(struct xdp_test_data *xdp, struct xdp_buff *orig_ctx)
161 {
162 	struct page_pool *pp;
163 	int err = -ENOMEM;
164 	struct page_pool_params pp_params = {
165 		.order = 0,
166 		.flags = 0,
167 		.pool_size = xdp->batch_size,
168 		.nid = NUMA_NO_NODE,
169 		.init_callback = xdp_test_run_init_page,
170 		.init_arg = xdp,
171 	};
172 
173 	xdp->frames = kvmalloc_array(xdp->batch_size, sizeof(void *), GFP_KERNEL);
174 	if (!xdp->frames)
175 		return -ENOMEM;
176 
177 	xdp->skbs = kvmalloc_array(xdp->batch_size, sizeof(void *), GFP_KERNEL);
178 	if (!xdp->skbs)
179 		goto err_skbs;
180 
181 	pp = page_pool_create(&pp_params);
182 	if (IS_ERR(pp)) {
183 		err = PTR_ERR(pp);
184 		goto err_pp;
185 	}
186 
187 	/* will copy 'mem.id' into pp->xdp_mem_id */
188 	err = xdp_reg_mem_model(&xdp->mem, MEM_TYPE_PAGE_POOL, pp);
189 	if (err)
190 		goto err_mmodel;
191 
192 	xdp->pp = pp;
193 
194 	/* We create a 'fake' RXQ referencing the original dev, but with an
195 	 * xdp_mem_info pointing to our page_pool
196 	 */
197 	xdp_rxq_info_reg(&xdp->rxq, orig_ctx->rxq->dev, 0, 0);
198 	xdp->rxq.mem.type = MEM_TYPE_PAGE_POOL;
199 	xdp->rxq.mem.id = pp->xdp_mem_id;
200 	xdp->dev = orig_ctx->rxq->dev;
201 	xdp->orig_ctx = orig_ctx;
202 
203 	return 0;
204 
205 err_mmodel:
206 	page_pool_destroy(pp);
207 err_pp:
208 	kvfree(xdp->skbs);
209 err_skbs:
210 	kvfree(xdp->frames);
211 	return err;
212 }
213 
214 static void xdp_test_run_teardown(struct xdp_test_data *xdp)
215 {
216 	xdp_unreg_mem_model(&xdp->mem);
217 	page_pool_destroy(xdp->pp);
218 	kfree(xdp->frames);
219 	kfree(xdp->skbs);
220 }
221 
222 static bool frame_was_changed(const struct xdp_page_head *head)
223 {
224 	/* xdp_scrub_frame() zeroes the data pointer, flags is the last field,
225 	 * i.e. has the highest chances to be overwritten. If those two are
226 	 * untouched, it's most likely safe to skip the context reset.
227 	 */
228 	return head->frame->data != head->orig_ctx.data ||
229 	       head->frame->flags != head->orig_ctx.flags;
230 }
231 
232 static bool ctx_was_changed(struct xdp_page_head *head)
233 {
234 	return head->orig_ctx.data != head->ctx.data ||
235 		head->orig_ctx.data_meta != head->ctx.data_meta ||
236 		head->orig_ctx.data_end != head->ctx.data_end;
237 }
238 
239 static void reset_ctx(struct xdp_page_head *head)
240 {
241 	if (likely(!frame_was_changed(head) && !ctx_was_changed(head)))
242 		return;
243 
244 	head->ctx.data = head->orig_ctx.data;
245 	head->ctx.data_meta = head->orig_ctx.data_meta;
246 	head->ctx.data_end = head->orig_ctx.data_end;
247 	xdp_update_frame_from_buff(&head->ctx, head->frame);
248 }
249 
250 static int xdp_recv_frames(struct xdp_frame **frames, int nframes,
251 			   struct sk_buff **skbs,
252 			   struct net_device *dev)
253 {
254 	gfp_t gfp = __GFP_ZERO | GFP_ATOMIC;
255 	int i, n;
256 	LIST_HEAD(list);
257 
258 	n = kmem_cache_alloc_bulk(net_hotdata.skbuff_cache, gfp, nframes,
259 				  (void **)skbs);
260 	if (unlikely(n == 0)) {
261 		for (i = 0; i < nframes; i++)
262 			xdp_return_frame(frames[i]);
263 		return -ENOMEM;
264 	}
265 
266 	for (i = 0; i < nframes; i++) {
267 		struct xdp_frame *xdpf = frames[i];
268 		struct sk_buff *skb = skbs[i];
269 
270 		skb = __xdp_build_skb_from_frame(xdpf, skb, dev);
271 		if (!skb) {
272 			xdp_return_frame(xdpf);
273 			continue;
274 		}
275 
276 		list_add_tail(&skb->list, &list);
277 	}
278 	netif_receive_skb_list(&list);
279 
280 	return 0;
281 }
282 
283 static int xdp_test_run_batch(struct xdp_test_data *xdp, struct bpf_prog *prog,
284 			      u32 repeat)
285 {
286 	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
287 	int err = 0, act, ret, i, nframes = 0, batch_sz;
288 	struct xdp_frame **frames = xdp->frames;
289 	struct bpf_redirect_info *ri;
290 	struct xdp_page_head *head;
291 	struct xdp_frame *frm;
292 	bool redirect = false;
293 	struct xdp_buff *ctx;
294 	struct page *page;
295 
296 	batch_sz = min_t(u32, repeat, xdp->batch_size);
297 
298 	local_bh_disable();
299 	bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
300 	ri = bpf_net_ctx_get_ri();
301 	xdp_set_return_frame_no_direct();
302 
303 	for (i = 0; i < batch_sz; i++) {
304 		page = page_pool_dev_alloc_pages(xdp->pp);
305 		if (!page) {
306 			err = -ENOMEM;
307 			goto out;
308 		}
309 
310 		head = phys_to_virt(page_to_phys(page));
311 		reset_ctx(head);
312 		ctx = &head->ctx;
313 		frm = head->frame;
314 		xdp->frame_cnt++;
315 
316 		act = bpf_prog_run_xdp(prog, ctx);
317 
318 		/* if program changed pkt bounds we need to update the xdp_frame */
319 		if (unlikely(ctx_was_changed(head))) {
320 			ret = xdp_update_frame_from_buff(ctx, frm);
321 			if (ret) {
322 				xdp_return_buff(ctx);
323 				continue;
324 			}
325 		}
326 
327 		switch (act) {
328 		case XDP_TX:
329 			/* we can't do a real XDP_TX since we're not in the
330 			 * driver, so turn it into a REDIRECT back to the same
331 			 * index
332 			 */
333 			ri->tgt_index = xdp->dev->ifindex;
334 			ri->map_id = INT_MAX;
335 			ri->map_type = BPF_MAP_TYPE_UNSPEC;
336 			fallthrough;
337 		case XDP_REDIRECT:
338 			redirect = true;
339 			ret = xdp_do_redirect_frame(xdp->dev, ctx, frm, prog);
340 			if (ret)
341 				xdp_return_buff(ctx);
342 			break;
343 		case XDP_PASS:
344 			frames[nframes++] = frm;
345 			break;
346 		default:
347 			bpf_warn_invalid_xdp_action(NULL, prog, act);
348 			fallthrough;
349 		case XDP_DROP:
350 			xdp_return_buff(ctx);
351 			break;
352 		}
353 	}
354 
355 out:
356 	if (redirect)
357 		xdp_do_flush();
358 	if (nframes) {
359 		ret = xdp_recv_frames(frames, nframes, xdp->skbs, xdp->dev);
360 		if (ret)
361 			err = ret;
362 	}
363 
364 	xdp_clear_return_frame_no_direct();
365 	bpf_net_ctx_clear(bpf_net_ctx);
366 	local_bh_enable();
367 	return err;
368 }
369 
370 static int bpf_test_run_xdp_live(struct bpf_prog *prog, struct xdp_buff *ctx,
371 				 u32 repeat, u32 batch_size, u32 *time)
372 
373 {
374 	struct xdp_test_data xdp = { .batch_size = batch_size };
375 	struct bpf_test_timer t = { .mode = NO_MIGRATE };
376 	int ret;
377 
378 	if (!repeat)
379 		repeat = 1;
380 
381 	ret = xdp_test_run_setup(&xdp, ctx);
382 	if (ret)
383 		return ret;
384 
385 	bpf_test_timer_enter(&t);
386 	do {
387 		xdp.frame_cnt = 0;
388 		ret = xdp_test_run_batch(&xdp, prog, repeat - t.i);
389 		if (unlikely(ret < 0))
390 			break;
391 	} while (bpf_test_timer_continue(&t, xdp.frame_cnt, repeat, &ret, time));
392 	bpf_test_timer_leave(&t);
393 
394 	xdp_test_run_teardown(&xdp);
395 	return ret;
396 }
397 
398 static int bpf_test_run(struct bpf_prog *prog, void *ctx, u32 repeat,
399 			u32 *retval, u32 *time, bool xdp)
400 {
401 	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
402 	struct bpf_prog_array_item item = {.prog = prog};
403 	struct bpf_run_ctx *old_ctx;
404 	struct bpf_cg_run_ctx run_ctx;
405 	struct bpf_test_timer t = { NO_MIGRATE };
406 	enum bpf_cgroup_storage_type stype;
407 	int ret;
408 
409 	for_each_cgroup_storage_type(stype) {
410 		item.cgroup_storage[stype] = bpf_cgroup_storage_alloc(prog, stype);
411 		if (IS_ERR(item.cgroup_storage[stype])) {
412 			item.cgroup_storage[stype] = NULL;
413 			for_each_cgroup_storage_type(stype)
414 				bpf_cgroup_storage_free(item.cgroup_storage[stype]);
415 			return -ENOMEM;
416 		}
417 	}
418 
419 	if (!repeat)
420 		repeat = 1;
421 
422 	bpf_test_timer_enter(&t);
423 	old_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
424 	do {
425 		run_ctx.prog_item = &item;
426 		local_bh_disable();
427 		bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
428 
429 		if (xdp)
430 			*retval = bpf_prog_run_xdp(prog, ctx);
431 		else
432 			*retval = bpf_prog_run(prog, ctx);
433 
434 		bpf_net_ctx_clear(bpf_net_ctx);
435 		local_bh_enable();
436 	} while (bpf_test_timer_continue(&t, 1, repeat, &ret, time));
437 	bpf_reset_run_ctx(old_ctx);
438 	bpf_test_timer_leave(&t);
439 
440 	for_each_cgroup_storage_type(stype)
441 		bpf_cgroup_storage_free(item.cgroup_storage[stype]);
442 
443 	return ret;
444 }
445 
446 static int bpf_test_finish(const union bpf_attr *kattr,
447 			   union bpf_attr __user *uattr, const void *data,
448 			   struct skb_shared_info *sinfo, u32 size,
449 			   u32 retval, u32 duration)
450 {
451 	void __user *data_out = u64_to_user_ptr(kattr->test.data_out);
452 	int err = -EFAULT;
453 	u32 copy_size = size;
454 
455 	/* Clamp copy if the user has provided a size hint, but copy the full
456 	 * buffer if not to retain old behaviour.
457 	 */
458 	if (kattr->test.data_size_out &&
459 	    copy_size > kattr->test.data_size_out) {
460 		copy_size = kattr->test.data_size_out;
461 		err = -ENOSPC;
462 	}
463 
464 	if (data_out) {
465 		int len = sinfo ? copy_size - sinfo->xdp_frags_size : copy_size;
466 
467 		if (len < 0) {
468 			err = -ENOSPC;
469 			goto out;
470 		}
471 
472 		if (copy_to_user(data_out, data, len))
473 			goto out;
474 
475 		if (sinfo) {
476 			int i, offset = len;
477 			u32 data_len;
478 
479 			for (i = 0; i < sinfo->nr_frags; i++) {
480 				skb_frag_t *frag = &sinfo->frags[i];
481 
482 				if (offset >= copy_size) {
483 					err = -ENOSPC;
484 					break;
485 				}
486 
487 				data_len = min_t(u32, copy_size - offset,
488 						 skb_frag_size(frag));
489 
490 				if (copy_to_user(data_out + offset,
491 						 skb_frag_address(frag),
492 						 data_len))
493 					goto out;
494 
495 				offset += data_len;
496 			}
497 		}
498 	}
499 
500 	if (copy_to_user(&uattr->test.data_size_out, &size, sizeof(size)))
501 		goto out;
502 	if (copy_to_user(&uattr->test.retval, &retval, sizeof(retval)))
503 		goto out;
504 	if (copy_to_user(&uattr->test.duration, &duration, sizeof(duration)))
505 		goto out;
506 	if (err != -ENOSPC)
507 		err = 0;
508 out:
509 	trace_bpf_test_finish(&err);
510 	return err;
511 }
512 
513 /* Integer types of various sizes and pointer combinations cover variety of
514  * architecture dependent calling conventions. 7+ can be supported in the
515  * future.
516  */
517 __bpf_kfunc_start_defs();
518 
519 __bpf_kfunc int bpf_fentry_test1(int a)
520 {
521 	return a + 1;
522 }
523 EXPORT_SYMBOL_GPL(bpf_fentry_test1);
524 
525 int noinline bpf_fentry_test2(int a, u64 b)
526 {
527 	return a + b;
528 }
529 
530 int noinline bpf_fentry_test3(char a, int b, u64 c)
531 {
532 	return a + b + c;
533 }
534 
535 int noinline bpf_fentry_test4(void *a, char b, int c, u64 d)
536 {
537 	return (long)a + b + c + d;
538 }
539 
540 int noinline bpf_fentry_test5(u64 a, void *b, short c, int d, u64 e)
541 {
542 	return a + (long)b + c + d + e;
543 }
544 
545 int noinline bpf_fentry_test6(u64 a, void *b, short c, int d, void *e, u64 f)
546 {
547 	return a + (long)b + c + d + (long)e + f;
548 }
549 
550 struct bpf_fentry_test_t {
551 	struct bpf_fentry_test_t *a;
552 };
553 
554 int noinline bpf_fentry_test7(struct bpf_fentry_test_t *arg)
555 {
556 	asm volatile ("": "+r"(arg));
557 	return (long)arg;
558 }
559 
560 int noinline bpf_fentry_test8(struct bpf_fentry_test_t *arg)
561 {
562 	return (long)arg->a;
563 }
564 
565 __bpf_kfunc u32 bpf_fentry_test9(u32 *a)
566 {
567 	return *a;
568 }
569 
570 void noinline bpf_fentry_test_sinfo(struct skb_shared_info *sinfo)
571 {
572 }
573 
574 __bpf_kfunc int bpf_modify_return_test(int a, int *b)
575 {
576 	*b += 1;
577 	return a + *b;
578 }
579 
580 __bpf_kfunc int bpf_modify_return_test2(int a, int *b, short c, int d,
581 					void *e, char f, int g)
582 {
583 	*b += 1;
584 	return a + *b + c + d + (long)e + f + g;
585 }
586 
587 __bpf_kfunc int bpf_modify_return_test_tp(int nonce)
588 {
589 	trace_bpf_trigger_tp(nonce);
590 
591 	return nonce;
592 }
593 
594 int noinline bpf_fentry_shadow_test(int a)
595 {
596 	return a + 1;
597 }
598 
599 struct prog_test_member1 {
600 	int a;
601 };
602 
603 struct prog_test_member {
604 	struct prog_test_member1 m;
605 	int c;
606 };
607 
608 struct prog_test_ref_kfunc {
609 	int a;
610 	int b;
611 	struct prog_test_member memb;
612 	struct prog_test_ref_kfunc *next;
613 	refcount_t cnt;
614 };
615 
616 __bpf_kfunc void bpf_kfunc_call_test_release(struct prog_test_ref_kfunc *p)
617 {
618 	refcount_dec(&p->cnt);
619 }
620 
621 __bpf_kfunc void bpf_kfunc_call_test_release_dtor(void *p)
622 {
623 	bpf_kfunc_call_test_release(p);
624 }
625 CFI_NOSEAL(bpf_kfunc_call_test_release_dtor);
626 
627 __bpf_kfunc void bpf_kfunc_call_memb_release(struct prog_test_member *p)
628 {
629 }
630 
631 __bpf_kfunc void bpf_kfunc_call_memb_release_dtor(void *p)
632 {
633 }
634 CFI_NOSEAL(bpf_kfunc_call_memb_release_dtor);
635 
636 __bpf_kfunc_end_defs();
637 
638 BTF_KFUNCS_START(bpf_test_modify_return_ids)
639 BTF_ID_FLAGS(func, bpf_modify_return_test)
640 BTF_ID_FLAGS(func, bpf_modify_return_test2)
641 BTF_ID_FLAGS(func, bpf_modify_return_test_tp)
642 BTF_ID_FLAGS(func, bpf_fentry_test1, KF_SLEEPABLE)
643 BTF_KFUNCS_END(bpf_test_modify_return_ids)
644 
645 static const struct btf_kfunc_id_set bpf_test_modify_return_set = {
646 	.owner = THIS_MODULE,
647 	.set   = &bpf_test_modify_return_ids,
648 };
649 
650 BTF_KFUNCS_START(test_sk_check_kfunc_ids)
651 BTF_ID_FLAGS(func, bpf_kfunc_call_test_release, KF_RELEASE)
652 BTF_ID_FLAGS(func, bpf_kfunc_call_memb_release, KF_RELEASE)
653 BTF_KFUNCS_END(test_sk_check_kfunc_ids)
654 
655 static void *bpf_test_init(const union bpf_attr *kattr, u32 user_size,
656 			   u32 size, u32 headroom, u32 tailroom)
657 {
658 	void __user *data_in = u64_to_user_ptr(kattr->test.data_in);
659 	void *data;
660 
661 	if (size < ETH_HLEN || size > PAGE_SIZE - headroom - tailroom)
662 		return ERR_PTR(-EINVAL);
663 
664 	if (user_size > size)
665 		return ERR_PTR(-EMSGSIZE);
666 
667 	size = SKB_DATA_ALIGN(size);
668 	data = kzalloc(size + headroom + tailroom, GFP_USER);
669 	if (!data)
670 		return ERR_PTR(-ENOMEM);
671 
672 	if (copy_from_user(data + headroom, data_in, user_size)) {
673 		kfree(data);
674 		return ERR_PTR(-EFAULT);
675 	}
676 
677 	return data;
678 }
679 
680 int bpf_prog_test_run_tracing(struct bpf_prog *prog,
681 			      const union bpf_attr *kattr,
682 			      union bpf_attr __user *uattr)
683 {
684 	struct bpf_fentry_test_t arg = {};
685 	u16 side_effect = 0, ret = 0;
686 	int b = 2, err = -EFAULT;
687 	u32 retval = 0;
688 
689 	if (kattr->test.flags || kattr->test.cpu || kattr->test.batch_size)
690 		return -EINVAL;
691 
692 	switch (prog->expected_attach_type) {
693 	case BPF_TRACE_FENTRY:
694 	case BPF_TRACE_FEXIT:
695 		if (bpf_fentry_test1(1) != 2 ||
696 		    bpf_fentry_test2(2, 3) != 5 ||
697 		    bpf_fentry_test3(4, 5, 6) != 15 ||
698 		    bpf_fentry_test4((void *)7, 8, 9, 10) != 34 ||
699 		    bpf_fentry_test5(11, (void *)12, 13, 14, 15) != 65 ||
700 		    bpf_fentry_test6(16, (void *)17, 18, 19, (void *)20, 21) != 111 ||
701 		    bpf_fentry_test7((struct bpf_fentry_test_t *)0) != 0 ||
702 		    bpf_fentry_test8(&arg) != 0 ||
703 		    bpf_fentry_test9(&retval) != 0)
704 			goto out;
705 		break;
706 	case BPF_MODIFY_RETURN:
707 		ret = bpf_modify_return_test(1, &b);
708 		if (b != 2)
709 			side_effect++;
710 		b = 2;
711 		ret += bpf_modify_return_test2(1, &b, 3, 4, (void *)5, 6, 7);
712 		if (b != 2)
713 			side_effect++;
714 		break;
715 	default:
716 		goto out;
717 	}
718 
719 	retval = ((u32)side_effect << 16) | ret;
720 	if (copy_to_user(&uattr->test.retval, &retval, sizeof(retval)))
721 		goto out;
722 
723 	err = 0;
724 out:
725 	trace_bpf_test_finish(&err);
726 	return err;
727 }
728 
729 struct bpf_raw_tp_test_run_info {
730 	struct bpf_prog *prog;
731 	void *ctx;
732 	u32 retval;
733 };
734 
735 static void
736 __bpf_prog_test_run_raw_tp(void *data)
737 {
738 	struct bpf_raw_tp_test_run_info *info = data;
739 	struct bpf_trace_run_ctx run_ctx = {};
740 	struct bpf_run_ctx *old_run_ctx;
741 
742 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
743 
744 	rcu_read_lock();
745 	info->retval = bpf_prog_run(info->prog, info->ctx);
746 	rcu_read_unlock();
747 
748 	bpf_reset_run_ctx(old_run_ctx);
749 }
750 
751 int bpf_prog_test_run_raw_tp(struct bpf_prog *prog,
752 			     const union bpf_attr *kattr,
753 			     union bpf_attr __user *uattr)
754 {
755 	void __user *ctx_in = u64_to_user_ptr(kattr->test.ctx_in);
756 	__u32 ctx_size_in = kattr->test.ctx_size_in;
757 	struct bpf_raw_tp_test_run_info info;
758 	int cpu = kattr->test.cpu, err = 0;
759 	int current_cpu;
760 
761 	/* doesn't support data_in/out, ctx_out, duration, or repeat */
762 	if (kattr->test.data_in || kattr->test.data_out ||
763 	    kattr->test.ctx_out || kattr->test.duration ||
764 	    kattr->test.repeat || kattr->test.batch_size)
765 		return -EINVAL;
766 
767 	if (ctx_size_in < prog->aux->max_ctx_offset ||
768 	    ctx_size_in > MAX_BPF_FUNC_ARGS * sizeof(u64))
769 		return -EINVAL;
770 
771 	if ((kattr->test.flags & BPF_F_TEST_RUN_ON_CPU) == 0 && cpu != 0)
772 		return -EINVAL;
773 
774 	if (ctx_size_in) {
775 		info.ctx = memdup_user(ctx_in, ctx_size_in);
776 		if (IS_ERR(info.ctx))
777 			return PTR_ERR(info.ctx);
778 	} else {
779 		info.ctx = NULL;
780 	}
781 
782 	info.prog = prog;
783 
784 	current_cpu = get_cpu();
785 	if ((kattr->test.flags & BPF_F_TEST_RUN_ON_CPU) == 0 ||
786 	    cpu == current_cpu) {
787 		__bpf_prog_test_run_raw_tp(&info);
788 	} else if (cpu >= nr_cpu_ids || !cpu_online(cpu)) {
789 		/* smp_call_function_single() also checks cpu_online()
790 		 * after csd_lock(). However, since cpu is from user
791 		 * space, let's do an extra quick check to filter out
792 		 * invalid value before smp_call_function_single().
793 		 */
794 		err = -ENXIO;
795 	} else {
796 		err = smp_call_function_single(cpu, __bpf_prog_test_run_raw_tp,
797 					       &info, 1);
798 	}
799 	put_cpu();
800 
801 	if (!err &&
802 	    copy_to_user(&uattr->test.retval, &info.retval, sizeof(u32)))
803 		err = -EFAULT;
804 
805 	kfree(info.ctx);
806 	return err;
807 }
808 
809 static void *bpf_ctx_init(const union bpf_attr *kattr, u32 max_size)
810 {
811 	void __user *data_in = u64_to_user_ptr(kattr->test.ctx_in);
812 	void __user *data_out = u64_to_user_ptr(kattr->test.ctx_out);
813 	u32 size = kattr->test.ctx_size_in;
814 	void *data;
815 	int err;
816 
817 	if (!data_in && !data_out)
818 		return NULL;
819 
820 	data = kzalloc(max_size, GFP_USER);
821 	if (!data)
822 		return ERR_PTR(-ENOMEM);
823 
824 	if (data_in) {
825 		err = bpf_check_uarg_tail_zero(USER_BPFPTR(data_in), max_size, size);
826 		if (err) {
827 			kfree(data);
828 			return ERR_PTR(err);
829 		}
830 
831 		size = min_t(u32, max_size, size);
832 		if (copy_from_user(data, data_in, size)) {
833 			kfree(data);
834 			return ERR_PTR(-EFAULT);
835 		}
836 	}
837 	return data;
838 }
839 
840 static int bpf_ctx_finish(const union bpf_attr *kattr,
841 			  union bpf_attr __user *uattr, const void *data,
842 			  u32 size)
843 {
844 	void __user *data_out = u64_to_user_ptr(kattr->test.ctx_out);
845 	int err = -EFAULT;
846 	u32 copy_size = size;
847 
848 	if (!data || !data_out)
849 		return 0;
850 
851 	if (copy_size > kattr->test.ctx_size_out) {
852 		copy_size = kattr->test.ctx_size_out;
853 		err = -ENOSPC;
854 	}
855 
856 	if (copy_to_user(data_out, data, copy_size))
857 		goto out;
858 	if (copy_to_user(&uattr->test.ctx_size_out, &size, sizeof(size)))
859 		goto out;
860 	if (err != -ENOSPC)
861 		err = 0;
862 out:
863 	return err;
864 }
865 
866 /**
867  * range_is_zero - test whether buffer is initialized
868  * @buf: buffer to check
869  * @from: check from this position
870  * @to: check up until (excluding) this position
871  *
872  * This function returns true if the there is a non-zero byte
873  * in the buf in the range [from,to).
874  */
875 static inline bool range_is_zero(void *buf, size_t from, size_t to)
876 {
877 	return !memchr_inv((u8 *)buf + from, 0, to - from);
878 }
879 
880 static int convert___skb_to_skb(struct sk_buff *skb, struct __sk_buff *__skb)
881 {
882 	struct qdisc_skb_cb *cb = (struct qdisc_skb_cb *)skb->cb;
883 
884 	if (!__skb)
885 		return 0;
886 
887 	/* make sure the fields we don't use are zeroed */
888 	if (!range_is_zero(__skb, 0, offsetof(struct __sk_buff, mark)))
889 		return -EINVAL;
890 
891 	/* mark is allowed */
892 
893 	if (!range_is_zero(__skb, offsetofend(struct __sk_buff, mark),
894 			   offsetof(struct __sk_buff, priority)))
895 		return -EINVAL;
896 
897 	/* priority is allowed */
898 	/* ingress_ifindex is allowed */
899 	/* ifindex is allowed */
900 
901 	if (!range_is_zero(__skb, offsetofend(struct __sk_buff, ifindex),
902 			   offsetof(struct __sk_buff, cb)))
903 		return -EINVAL;
904 
905 	/* cb is allowed */
906 
907 	if (!range_is_zero(__skb, offsetofend(struct __sk_buff, cb),
908 			   offsetof(struct __sk_buff, tstamp)))
909 		return -EINVAL;
910 
911 	/* tstamp is allowed */
912 	/* wire_len is allowed */
913 	/* gso_segs is allowed */
914 
915 	if (!range_is_zero(__skb, offsetofend(struct __sk_buff, gso_segs),
916 			   offsetof(struct __sk_buff, gso_size)))
917 		return -EINVAL;
918 
919 	/* gso_size is allowed */
920 
921 	if (!range_is_zero(__skb, offsetofend(struct __sk_buff, gso_size),
922 			   offsetof(struct __sk_buff, hwtstamp)))
923 		return -EINVAL;
924 
925 	/* hwtstamp is allowed */
926 
927 	if (!range_is_zero(__skb, offsetofend(struct __sk_buff, hwtstamp),
928 			   sizeof(struct __sk_buff)))
929 		return -EINVAL;
930 
931 	skb->mark = __skb->mark;
932 	skb->priority = __skb->priority;
933 	skb->skb_iif = __skb->ingress_ifindex;
934 	skb->tstamp = __skb->tstamp;
935 	memcpy(&cb->data, __skb->cb, QDISC_CB_PRIV_LEN);
936 
937 	if (__skb->wire_len == 0) {
938 		cb->pkt_len = skb->len;
939 	} else {
940 		if (__skb->wire_len < skb->len ||
941 		    __skb->wire_len > GSO_LEGACY_MAX_SIZE)
942 			return -EINVAL;
943 		cb->pkt_len = __skb->wire_len;
944 	}
945 
946 	if (__skb->gso_segs > GSO_MAX_SEGS)
947 		return -EINVAL;
948 	skb_shinfo(skb)->gso_segs = __skb->gso_segs;
949 	skb_shinfo(skb)->gso_size = __skb->gso_size;
950 	skb_shinfo(skb)->hwtstamps.hwtstamp = __skb->hwtstamp;
951 
952 	return 0;
953 }
954 
955 static void convert_skb_to___skb(struct sk_buff *skb, struct __sk_buff *__skb)
956 {
957 	struct qdisc_skb_cb *cb = (struct qdisc_skb_cb *)skb->cb;
958 
959 	if (!__skb)
960 		return;
961 
962 	__skb->mark = skb->mark;
963 	__skb->priority = skb->priority;
964 	__skb->ingress_ifindex = skb->skb_iif;
965 	__skb->ifindex = skb->dev->ifindex;
966 	__skb->tstamp = skb->tstamp;
967 	memcpy(__skb->cb, &cb->data, QDISC_CB_PRIV_LEN);
968 	__skb->wire_len = cb->pkt_len;
969 	__skb->gso_segs = skb_shinfo(skb)->gso_segs;
970 	__skb->hwtstamp = skb_shinfo(skb)->hwtstamps.hwtstamp;
971 }
972 
973 static struct proto bpf_dummy_proto = {
974 	.name   = "bpf_dummy",
975 	.owner  = THIS_MODULE,
976 	.obj_size = sizeof(struct sock),
977 };
978 
979 int bpf_prog_test_run_skb(struct bpf_prog *prog, const union bpf_attr *kattr,
980 			  union bpf_attr __user *uattr)
981 {
982 	bool is_l2 = false, is_direct_pkt_access = false;
983 	struct net *net = current->nsproxy->net_ns;
984 	struct net_device *dev = net->loopback_dev;
985 	u32 size = kattr->test.data_size_in;
986 	u32 repeat = kattr->test.repeat;
987 	struct __sk_buff *ctx = NULL;
988 	u32 retval, duration;
989 	int hh_len = ETH_HLEN;
990 	struct sk_buff *skb;
991 	struct sock *sk;
992 	void *data;
993 	int ret;
994 
995 	if (kattr->test.flags || kattr->test.cpu || kattr->test.batch_size)
996 		return -EINVAL;
997 
998 	data = bpf_test_init(kattr, kattr->test.data_size_in,
999 			     size, NET_SKB_PAD + NET_IP_ALIGN,
1000 			     SKB_DATA_ALIGN(sizeof(struct skb_shared_info)));
1001 	if (IS_ERR(data))
1002 		return PTR_ERR(data);
1003 
1004 	ctx = bpf_ctx_init(kattr, sizeof(struct __sk_buff));
1005 	if (IS_ERR(ctx)) {
1006 		kfree(data);
1007 		return PTR_ERR(ctx);
1008 	}
1009 
1010 	switch (prog->type) {
1011 	case BPF_PROG_TYPE_SCHED_CLS:
1012 	case BPF_PROG_TYPE_SCHED_ACT:
1013 		is_l2 = true;
1014 		fallthrough;
1015 	case BPF_PROG_TYPE_LWT_IN:
1016 	case BPF_PROG_TYPE_LWT_OUT:
1017 	case BPF_PROG_TYPE_LWT_XMIT:
1018 		is_direct_pkt_access = true;
1019 		break;
1020 	default:
1021 		break;
1022 	}
1023 
1024 	sk = sk_alloc(net, AF_UNSPEC, GFP_USER, &bpf_dummy_proto, 1);
1025 	if (!sk) {
1026 		kfree(data);
1027 		kfree(ctx);
1028 		return -ENOMEM;
1029 	}
1030 	sock_init_data(NULL, sk);
1031 
1032 	skb = slab_build_skb(data);
1033 	if (!skb) {
1034 		kfree(data);
1035 		kfree(ctx);
1036 		sk_free(sk);
1037 		return -ENOMEM;
1038 	}
1039 	skb->sk = sk;
1040 
1041 	skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
1042 	__skb_put(skb, size);
1043 	if (ctx && ctx->ifindex > 1) {
1044 		dev = dev_get_by_index(net, ctx->ifindex);
1045 		if (!dev) {
1046 			ret = -ENODEV;
1047 			goto out;
1048 		}
1049 	}
1050 	skb->protocol = eth_type_trans(skb, dev);
1051 	skb_reset_network_header(skb);
1052 
1053 	switch (skb->protocol) {
1054 	case htons(ETH_P_IP):
1055 		sk->sk_family = AF_INET;
1056 		if (sizeof(struct iphdr) <= skb_headlen(skb)) {
1057 			sk->sk_rcv_saddr = ip_hdr(skb)->saddr;
1058 			sk->sk_daddr = ip_hdr(skb)->daddr;
1059 		}
1060 		break;
1061 #if IS_ENABLED(CONFIG_IPV6)
1062 	case htons(ETH_P_IPV6):
1063 		sk->sk_family = AF_INET6;
1064 		if (sizeof(struct ipv6hdr) <= skb_headlen(skb)) {
1065 			sk->sk_v6_rcv_saddr = ipv6_hdr(skb)->saddr;
1066 			sk->sk_v6_daddr = ipv6_hdr(skb)->daddr;
1067 		}
1068 		break;
1069 #endif
1070 	default:
1071 		break;
1072 	}
1073 
1074 	if (is_l2)
1075 		__skb_push(skb, hh_len);
1076 	if (is_direct_pkt_access)
1077 		bpf_compute_data_pointers(skb);
1078 	ret = convert___skb_to_skb(skb, ctx);
1079 	if (ret)
1080 		goto out;
1081 	ret = bpf_test_run(prog, skb, repeat, &retval, &duration, false);
1082 	if (ret)
1083 		goto out;
1084 	if (!is_l2) {
1085 		if (skb_headroom(skb) < hh_len) {
1086 			int nhead = HH_DATA_ALIGN(hh_len - skb_headroom(skb));
1087 
1088 			if (pskb_expand_head(skb, nhead, 0, GFP_USER)) {
1089 				ret = -ENOMEM;
1090 				goto out;
1091 			}
1092 		}
1093 		memset(__skb_push(skb, hh_len), 0, hh_len);
1094 	}
1095 	convert_skb_to___skb(skb, ctx);
1096 
1097 	size = skb->len;
1098 	/* bpf program can never convert linear skb to non-linear */
1099 	if (WARN_ON_ONCE(skb_is_nonlinear(skb)))
1100 		size = skb_headlen(skb);
1101 	ret = bpf_test_finish(kattr, uattr, skb->data, NULL, size, retval,
1102 			      duration);
1103 	if (!ret)
1104 		ret = bpf_ctx_finish(kattr, uattr, ctx,
1105 				     sizeof(struct __sk_buff));
1106 out:
1107 	if (dev && dev != net->loopback_dev)
1108 		dev_put(dev);
1109 	kfree_skb(skb);
1110 	sk_free(sk);
1111 	kfree(ctx);
1112 	return ret;
1113 }
1114 
1115 static int xdp_convert_md_to_buff(struct xdp_md *xdp_md, struct xdp_buff *xdp)
1116 {
1117 	unsigned int ingress_ifindex, rx_queue_index;
1118 	struct netdev_rx_queue *rxqueue;
1119 	struct net_device *device;
1120 
1121 	if (!xdp_md)
1122 		return 0;
1123 
1124 	if (xdp_md->egress_ifindex != 0)
1125 		return -EINVAL;
1126 
1127 	ingress_ifindex = xdp_md->ingress_ifindex;
1128 	rx_queue_index = xdp_md->rx_queue_index;
1129 
1130 	if (!ingress_ifindex && rx_queue_index)
1131 		return -EINVAL;
1132 
1133 	if (ingress_ifindex) {
1134 		device = dev_get_by_index(current->nsproxy->net_ns,
1135 					  ingress_ifindex);
1136 		if (!device)
1137 			return -ENODEV;
1138 
1139 		if (rx_queue_index >= device->real_num_rx_queues)
1140 			goto free_dev;
1141 
1142 		rxqueue = __netif_get_rx_queue(device, rx_queue_index);
1143 
1144 		if (!xdp_rxq_info_is_reg(&rxqueue->xdp_rxq))
1145 			goto free_dev;
1146 
1147 		xdp->rxq = &rxqueue->xdp_rxq;
1148 		/* The device is now tracked in the xdp->rxq for later
1149 		 * dev_put()
1150 		 */
1151 	}
1152 
1153 	xdp->data = xdp->data_meta + xdp_md->data;
1154 	return 0;
1155 
1156 free_dev:
1157 	dev_put(device);
1158 	return -EINVAL;
1159 }
1160 
1161 static void xdp_convert_buff_to_md(struct xdp_buff *xdp, struct xdp_md *xdp_md)
1162 {
1163 	if (!xdp_md)
1164 		return;
1165 
1166 	xdp_md->data = xdp->data - xdp->data_meta;
1167 	xdp_md->data_end = xdp->data_end - xdp->data_meta;
1168 
1169 	if (xdp_md->ingress_ifindex)
1170 		dev_put(xdp->rxq->dev);
1171 }
1172 
1173 int bpf_prog_test_run_xdp(struct bpf_prog *prog, const union bpf_attr *kattr,
1174 			  union bpf_attr __user *uattr)
1175 {
1176 	bool do_live = (kattr->test.flags & BPF_F_TEST_XDP_LIVE_FRAMES);
1177 	u32 tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1178 	u32 batch_size = kattr->test.batch_size;
1179 	u32 retval = 0, duration, max_data_sz;
1180 	u32 size = kattr->test.data_size_in;
1181 	u32 headroom = XDP_PACKET_HEADROOM;
1182 	u32 repeat = kattr->test.repeat;
1183 	struct netdev_rx_queue *rxqueue;
1184 	struct skb_shared_info *sinfo;
1185 	struct xdp_buff xdp = {};
1186 	int i, ret = -EINVAL;
1187 	struct xdp_md *ctx;
1188 	void *data;
1189 
1190 	if (prog->expected_attach_type == BPF_XDP_DEVMAP ||
1191 	    prog->expected_attach_type == BPF_XDP_CPUMAP)
1192 		return -EINVAL;
1193 
1194 	if (kattr->test.flags & ~BPF_F_TEST_XDP_LIVE_FRAMES)
1195 		return -EINVAL;
1196 
1197 	if (bpf_prog_is_dev_bound(prog->aux))
1198 		return -EINVAL;
1199 
1200 	if (do_live) {
1201 		if (!batch_size)
1202 			batch_size = NAPI_POLL_WEIGHT;
1203 		else if (batch_size > TEST_XDP_MAX_BATCH)
1204 			return -E2BIG;
1205 
1206 		headroom += sizeof(struct xdp_page_head);
1207 	} else if (batch_size) {
1208 		return -EINVAL;
1209 	}
1210 
1211 	ctx = bpf_ctx_init(kattr, sizeof(struct xdp_md));
1212 	if (IS_ERR(ctx))
1213 		return PTR_ERR(ctx);
1214 
1215 	if (ctx) {
1216 		/* There can't be user provided data before the meta data */
1217 		if (ctx->data_meta || ctx->data_end != size ||
1218 		    ctx->data > ctx->data_end ||
1219 		    unlikely(xdp_metalen_invalid(ctx->data)) ||
1220 		    (do_live && (kattr->test.data_out || kattr->test.ctx_out)))
1221 			goto free_ctx;
1222 		/* Meta data is allocated from the headroom */
1223 		headroom -= ctx->data;
1224 	}
1225 
1226 	max_data_sz = 4096 - headroom - tailroom;
1227 	if (size > max_data_sz) {
1228 		/* disallow live data mode for jumbo frames */
1229 		if (do_live)
1230 			goto free_ctx;
1231 		size = max_data_sz;
1232 	}
1233 
1234 	data = bpf_test_init(kattr, size, max_data_sz, headroom, tailroom);
1235 	if (IS_ERR(data)) {
1236 		ret = PTR_ERR(data);
1237 		goto free_ctx;
1238 	}
1239 
1240 	rxqueue = __netif_get_rx_queue(current->nsproxy->net_ns->loopback_dev, 0);
1241 	rxqueue->xdp_rxq.frag_size = headroom + max_data_sz + tailroom;
1242 	xdp_init_buff(&xdp, rxqueue->xdp_rxq.frag_size, &rxqueue->xdp_rxq);
1243 	xdp_prepare_buff(&xdp, data, headroom, size, true);
1244 	sinfo = xdp_get_shared_info_from_buff(&xdp);
1245 
1246 	ret = xdp_convert_md_to_buff(ctx, &xdp);
1247 	if (ret)
1248 		goto free_data;
1249 
1250 	if (unlikely(kattr->test.data_size_in > size)) {
1251 		void __user *data_in = u64_to_user_ptr(kattr->test.data_in);
1252 
1253 		while (size < kattr->test.data_size_in) {
1254 			struct page *page;
1255 			skb_frag_t *frag;
1256 			u32 data_len;
1257 
1258 			if (sinfo->nr_frags == MAX_SKB_FRAGS) {
1259 				ret = -ENOMEM;
1260 				goto out;
1261 			}
1262 
1263 			page = alloc_page(GFP_KERNEL);
1264 			if (!page) {
1265 				ret = -ENOMEM;
1266 				goto out;
1267 			}
1268 
1269 			frag = &sinfo->frags[sinfo->nr_frags++];
1270 
1271 			data_len = min_t(u32, kattr->test.data_size_in - size,
1272 					 PAGE_SIZE);
1273 			skb_frag_fill_page_desc(frag, page, 0, data_len);
1274 
1275 			if (copy_from_user(page_address(page), data_in + size,
1276 					   data_len)) {
1277 				ret = -EFAULT;
1278 				goto out;
1279 			}
1280 			sinfo->xdp_frags_size += data_len;
1281 			size += data_len;
1282 		}
1283 		xdp_buff_set_frags_flag(&xdp);
1284 	}
1285 
1286 	if (repeat > 1)
1287 		bpf_prog_change_xdp(NULL, prog);
1288 
1289 	if (do_live)
1290 		ret = bpf_test_run_xdp_live(prog, &xdp, repeat, batch_size, &duration);
1291 	else
1292 		ret = bpf_test_run(prog, &xdp, repeat, &retval, &duration, true);
1293 	/* We convert the xdp_buff back to an xdp_md before checking the return
1294 	 * code so the reference count of any held netdevice will be decremented
1295 	 * even if the test run failed.
1296 	 */
1297 	xdp_convert_buff_to_md(&xdp, ctx);
1298 	if (ret)
1299 		goto out;
1300 
1301 	size = xdp.data_end - xdp.data_meta + sinfo->xdp_frags_size;
1302 	ret = bpf_test_finish(kattr, uattr, xdp.data_meta, sinfo, size,
1303 			      retval, duration);
1304 	if (!ret)
1305 		ret = bpf_ctx_finish(kattr, uattr, ctx,
1306 				     sizeof(struct xdp_md));
1307 
1308 out:
1309 	if (repeat > 1)
1310 		bpf_prog_change_xdp(prog, NULL);
1311 free_data:
1312 	for (i = 0; i < sinfo->nr_frags; i++)
1313 		__free_page(skb_frag_page(&sinfo->frags[i]));
1314 	kfree(data);
1315 free_ctx:
1316 	kfree(ctx);
1317 	return ret;
1318 }
1319 
1320 static int verify_user_bpf_flow_keys(struct bpf_flow_keys *ctx)
1321 {
1322 	/* make sure the fields we don't use are zeroed */
1323 	if (!range_is_zero(ctx, 0, offsetof(struct bpf_flow_keys, flags)))
1324 		return -EINVAL;
1325 
1326 	/* flags is allowed */
1327 
1328 	if (!range_is_zero(ctx, offsetofend(struct bpf_flow_keys, flags),
1329 			   sizeof(struct bpf_flow_keys)))
1330 		return -EINVAL;
1331 
1332 	return 0;
1333 }
1334 
1335 int bpf_prog_test_run_flow_dissector(struct bpf_prog *prog,
1336 				     const union bpf_attr *kattr,
1337 				     union bpf_attr __user *uattr)
1338 {
1339 	struct bpf_test_timer t = { NO_PREEMPT };
1340 	u32 size = kattr->test.data_size_in;
1341 	struct bpf_flow_dissector ctx = {};
1342 	u32 repeat = kattr->test.repeat;
1343 	struct bpf_flow_keys *user_ctx;
1344 	struct bpf_flow_keys flow_keys;
1345 	const struct ethhdr *eth;
1346 	unsigned int flags = 0;
1347 	u32 retval, duration;
1348 	void *data;
1349 	int ret;
1350 
1351 	if (kattr->test.flags || kattr->test.cpu || kattr->test.batch_size)
1352 		return -EINVAL;
1353 
1354 	if (size < ETH_HLEN)
1355 		return -EINVAL;
1356 
1357 	data = bpf_test_init(kattr, kattr->test.data_size_in, size, 0, 0);
1358 	if (IS_ERR(data))
1359 		return PTR_ERR(data);
1360 
1361 	eth = (struct ethhdr *)data;
1362 
1363 	if (!repeat)
1364 		repeat = 1;
1365 
1366 	user_ctx = bpf_ctx_init(kattr, sizeof(struct bpf_flow_keys));
1367 	if (IS_ERR(user_ctx)) {
1368 		kfree(data);
1369 		return PTR_ERR(user_ctx);
1370 	}
1371 	if (user_ctx) {
1372 		ret = verify_user_bpf_flow_keys(user_ctx);
1373 		if (ret)
1374 			goto out;
1375 		flags = user_ctx->flags;
1376 	}
1377 
1378 	ctx.flow_keys = &flow_keys;
1379 	ctx.data = data;
1380 	ctx.data_end = (__u8 *)data + size;
1381 
1382 	bpf_test_timer_enter(&t);
1383 	do {
1384 		retval = bpf_flow_dissect(prog, &ctx, eth->h_proto, ETH_HLEN,
1385 					  size, flags);
1386 	} while (bpf_test_timer_continue(&t, 1, repeat, &ret, &duration));
1387 	bpf_test_timer_leave(&t);
1388 
1389 	if (ret < 0)
1390 		goto out;
1391 
1392 	ret = bpf_test_finish(kattr, uattr, &flow_keys, NULL,
1393 			      sizeof(flow_keys), retval, duration);
1394 	if (!ret)
1395 		ret = bpf_ctx_finish(kattr, uattr, user_ctx,
1396 				     sizeof(struct bpf_flow_keys));
1397 
1398 out:
1399 	kfree(user_ctx);
1400 	kfree(data);
1401 	return ret;
1402 }
1403 
1404 int bpf_prog_test_run_sk_lookup(struct bpf_prog *prog, const union bpf_attr *kattr,
1405 				union bpf_attr __user *uattr)
1406 {
1407 	struct bpf_test_timer t = { NO_PREEMPT };
1408 	struct bpf_prog_array *progs = NULL;
1409 	struct bpf_sk_lookup_kern ctx = {};
1410 	u32 repeat = kattr->test.repeat;
1411 	struct bpf_sk_lookup *user_ctx;
1412 	u32 retval, duration;
1413 	int ret = -EINVAL;
1414 
1415 	if (kattr->test.flags || kattr->test.cpu || kattr->test.batch_size)
1416 		return -EINVAL;
1417 
1418 	if (kattr->test.data_in || kattr->test.data_size_in || kattr->test.data_out ||
1419 	    kattr->test.data_size_out)
1420 		return -EINVAL;
1421 
1422 	if (!repeat)
1423 		repeat = 1;
1424 
1425 	user_ctx = bpf_ctx_init(kattr, sizeof(*user_ctx));
1426 	if (IS_ERR(user_ctx))
1427 		return PTR_ERR(user_ctx);
1428 
1429 	if (!user_ctx)
1430 		return -EINVAL;
1431 
1432 	if (user_ctx->sk)
1433 		goto out;
1434 
1435 	if (!range_is_zero(user_ctx, offsetofend(typeof(*user_ctx), local_port), sizeof(*user_ctx)))
1436 		goto out;
1437 
1438 	if (user_ctx->local_port > U16_MAX) {
1439 		ret = -ERANGE;
1440 		goto out;
1441 	}
1442 
1443 	ctx.family = (u16)user_ctx->family;
1444 	ctx.protocol = (u16)user_ctx->protocol;
1445 	ctx.dport = (u16)user_ctx->local_port;
1446 	ctx.sport = user_ctx->remote_port;
1447 
1448 	switch (ctx.family) {
1449 	case AF_INET:
1450 		ctx.v4.daddr = (__force __be32)user_ctx->local_ip4;
1451 		ctx.v4.saddr = (__force __be32)user_ctx->remote_ip4;
1452 		break;
1453 
1454 #if IS_ENABLED(CONFIG_IPV6)
1455 	case AF_INET6:
1456 		ctx.v6.daddr = (struct in6_addr *)user_ctx->local_ip6;
1457 		ctx.v6.saddr = (struct in6_addr *)user_ctx->remote_ip6;
1458 		break;
1459 #endif
1460 
1461 	default:
1462 		ret = -EAFNOSUPPORT;
1463 		goto out;
1464 	}
1465 
1466 	progs = bpf_prog_array_alloc(1, GFP_KERNEL);
1467 	if (!progs) {
1468 		ret = -ENOMEM;
1469 		goto out;
1470 	}
1471 
1472 	progs->items[0].prog = prog;
1473 
1474 	bpf_test_timer_enter(&t);
1475 	do {
1476 		ctx.selected_sk = NULL;
1477 		retval = BPF_PROG_SK_LOOKUP_RUN_ARRAY(progs, ctx, bpf_prog_run);
1478 	} while (bpf_test_timer_continue(&t, 1, repeat, &ret, &duration));
1479 	bpf_test_timer_leave(&t);
1480 
1481 	if (ret < 0)
1482 		goto out;
1483 
1484 	user_ctx->cookie = 0;
1485 	if (ctx.selected_sk) {
1486 		if (ctx.selected_sk->sk_reuseport && !ctx.no_reuseport) {
1487 			ret = -EOPNOTSUPP;
1488 			goto out;
1489 		}
1490 
1491 		user_ctx->cookie = sock_gen_cookie(ctx.selected_sk);
1492 	}
1493 
1494 	ret = bpf_test_finish(kattr, uattr, NULL, NULL, 0, retval, duration);
1495 	if (!ret)
1496 		ret = bpf_ctx_finish(kattr, uattr, user_ctx, sizeof(*user_ctx));
1497 
1498 out:
1499 	bpf_prog_array_free(progs);
1500 	kfree(user_ctx);
1501 	return ret;
1502 }
1503 
1504 int bpf_prog_test_run_syscall(struct bpf_prog *prog,
1505 			      const union bpf_attr *kattr,
1506 			      union bpf_attr __user *uattr)
1507 {
1508 	void __user *ctx_in = u64_to_user_ptr(kattr->test.ctx_in);
1509 	__u32 ctx_size_in = kattr->test.ctx_size_in;
1510 	void *ctx = NULL;
1511 	u32 retval;
1512 	int err = 0;
1513 
1514 	/* doesn't support data_in/out, ctx_out, duration, or repeat or flags */
1515 	if (kattr->test.data_in || kattr->test.data_out ||
1516 	    kattr->test.ctx_out || kattr->test.duration ||
1517 	    kattr->test.repeat || kattr->test.flags ||
1518 	    kattr->test.batch_size)
1519 		return -EINVAL;
1520 
1521 	if (ctx_size_in < prog->aux->max_ctx_offset ||
1522 	    ctx_size_in > U16_MAX)
1523 		return -EINVAL;
1524 
1525 	if (ctx_size_in) {
1526 		ctx = memdup_user(ctx_in, ctx_size_in);
1527 		if (IS_ERR(ctx))
1528 			return PTR_ERR(ctx);
1529 	}
1530 
1531 	rcu_read_lock_trace();
1532 	retval = bpf_prog_run_pin_on_cpu(prog, ctx);
1533 	rcu_read_unlock_trace();
1534 
1535 	if (copy_to_user(&uattr->test.retval, &retval, sizeof(u32))) {
1536 		err = -EFAULT;
1537 		goto out;
1538 	}
1539 	if (ctx_size_in)
1540 		if (copy_to_user(ctx_in, ctx, ctx_size_in))
1541 			err = -EFAULT;
1542 out:
1543 	kfree(ctx);
1544 	return err;
1545 }
1546 
1547 static int verify_and_copy_hook_state(struct nf_hook_state *state,
1548 				      const struct nf_hook_state *user,
1549 				      struct net_device *dev)
1550 {
1551 	if (user->in || user->out)
1552 		return -EINVAL;
1553 
1554 	if (user->net || user->sk || user->okfn)
1555 		return -EINVAL;
1556 
1557 	switch (user->pf) {
1558 	case NFPROTO_IPV4:
1559 	case NFPROTO_IPV6:
1560 		switch (state->hook) {
1561 		case NF_INET_PRE_ROUTING:
1562 			state->in = dev;
1563 			break;
1564 		case NF_INET_LOCAL_IN:
1565 			state->in = dev;
1566 			break;
1567 		case NF_INET_FORWARD:
1568 			state->in = dev;
1569 			state->out = dev;
1570 			break;
1571 		case NF_INET_LOCAL_OUT:
1572 			state->out = dev;
1573 			break;
1574 		case NF_INET_POST_ROUTING:
1575 			state->out = dev;
1576 			break;
1577 		}
1578 
1579 		break;
1580 	default:
1581 		return -EINVAL;
1582 	}
1583 
1584 	state->pf = user->pf;
1585 	state->hook = user->hook;
1586 
1587 	return 0;
1588 }
1589 
1590 static __be16 nfproto_eth(int nfproto)
1591 {
1592 	switch (nfproto) {
1593 	case NFPROTO_IPV4:
1594 		return htons(ETH_P_IP);
1595 	case NFPROTO_IPV6:
1596 		break;
1597 	}
1598 
1599 	return htons(ETH_P_IPV6);
1600 }
1601 
1602 int bpf_prog_test_run_nf(struct bpf_prog *prog,
1603 			 const union bpf_attr *kattr,
1604 			 union bpf_attr __user *uattr)
1605 {
1606 	struct net *net = current->nsproxy->net_ns;
1607 	struct net_device *dev = net->loopback_dev;
1608 	struct nf_hook_state *user_ctx, hook_state = {
1609 		.pf = NFPROTO_IPV4,
1610 		.hook = NF_INET_LOCAL_OUT,
1611 	};
1612 	u32 size = kattr->test.data_size_in;
1613 	u32 repeat = kattr->test.repeat;
1614 	struct bpf_nf_ctx ctx = {
1615 		.state = &hook_state,
1616 	};
1617 	struct sk_buff *skb = NULL;
1618 	u32 retval, duration;
1619 	void *data;
1620 	int ret;
1621 
1622 	if (kattr->test.flags || kattr->test.cpu || kattr->test.batch_size)
1623 		return -EINVAL;
1624 
1625 	if (size < sizeof(struct iphdr))
1626 		return -EINVAL;
1627 
1628 	data = bpf_test_init(kattr, kattr->test.data_size_in, size,
1629 			     NET_SKB_PAD + NET_IP_ALIGN,
1630 			     SKB_DATA_ALIGN(sizeof(struct skb_shared_info)));
1631 	if (IS_ERR(data))
1632 		return PTR_ERR(data);
1633 
1634 	if (!repeat)
1635 		repeat = 1;
1636 
1637 	user_ctx = bpf_ctx_init(kattr, sizeof(struct nf_hook_state));
1638 	if (IS_ERR(user_ctx)) {
1639 		kfree(data);
1640 		return PTR_ERR(user_ctx);
1641 	}
1642 
1643 	if (user_ctx) {
1644 		ret = verify_and_copy_hook_state(&hook_state, user_ctx, dev);
1645 		if (ret)
1646 			goto out;
1647 	}
1648 
1649 	skb = slab_build_skb(data);
1650 	if (!skb) {
1651 		ret = -ENOMEM;
1652 		goto out;
1653 	}
1654 
1655 	data = NULL; /* data released via kfree_skb */
1656 
1657 	skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
1658 	__skb_put(skb, size);
1659 
1660 	ret = -EINVAL;
1661 
1662 	if (hook_state.hook != NF_INET_LOCAL_OUT) {
1663 		if (size < ETH_HLEN + sizeof(struct iphdr))
1664 			goto out;
1665 
1666 		skb->protocol = eth_type_trans(skb, dev);
1667 		switch (skb->protocol) {
1668 		case htons(ETH_P_IP):
1669 			if (hook_state.pf == NFPROTO_IPV4)
1670 				break;
1671 			goto out;
1672 		case htons(ETH_P_IPV6):
1673 			if (size < ETH_HLEN + sizeof(struct ipv6hdr))
1674 				goto out;
1675 			if (hook_state.pf == NFPROTO_IPV6)
1676 				break;
1677 			goto out;
1678 		default:
1679 			ret = -EPROTO;
1680 			goto out;
1681 		}
1682 
1683 		skb_reset_network_header(skb);
1684 	} else {
1685 		skb->protocol = nfproto_eth(hook_state.pf);
1686 	}
1687 
1688 	ctx.skb = skb;
1689 
1690 	ret = bpf_test_run(prog, &ctx, repeat, &retval, &duration, false);
1691 	if (ret)
1692 		goto out;
1693 
1694 	ret = bpf_test_finish(kattr, uattr, NULL, NULL, 0, retval, duration);
1695 
1696 out:
1697 	kfree(user_ctx);
1698 	kfree_skb(skb);
1699 	kfree(data);
1700 	return ret;
1701 }
1702 
1703 static const struct btf_kfunc_id_set bpf_prog_test_kfunc_set = {
1704 	.owner = THIS_MODULE,
1705 	.set   = &test_sk_check_kfunc_ids,
1706 };
1707 
1708 BTF_ID_LIST(bpf_prog_test_dtor_kfunc_ids)
1709 BTF_ID(struct, prog_test_ref_kfunc)
1710 BTF_ID(func, bpf_kfunc_call_test_release_dtor)
1711 BTF_ID(struct, prog_test_member)
1712 BTF_ID(func, bpf_kfunc_call_memb_release_dtor)
1713 
1714 static int __init bpf_prog_test_run_init(void)
1715 {
1716 	const struct btf_id_dtor_kfunc bpf_prog_test_dtor_kfunc[] = {
1717 		{
1718 		  .btf_id       = bpf_prog_test_dtor_kfunc_ids[0],
1719 		  .kfunc_btf_id = bpf_prog_test_dtor_kfunc_ids[1]
1720 		},
1721 		{
1722 		  .btf_id	= bpf_prog_test_dtor_kfunc_ids[2],
1723 		  .kfunc_btf_id = bpf_prog_test_dtor_kfunc_ids[3],
1724 		},
1725 	};
1726 	int ret;
1727 
1728 	ret = register_btf_fmodret_id_set(&bpf_test_modify_return_set);
1729 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &bpf_prog_test_kfunc_set);
1730 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_prog_test_kfunc_set);
1731 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, &bpf_prog_test_kfunc_set);
1732 	return ret ?: register_btf_id_dtor_kfuncs(bpf_prog_test_dtor_kfunc,
1733 						  ARRAY_SIZE(bpf_prog_test_dtor_kfunc),
1734 						  THIS_MODULE);
1735 }
1736 late_initcall(bpf_prog_test_run_init);
1737