xref: /openbmc/linux/net/core/filter.c (revision 83268fa6)
1 /*
2  * Linux Socket Filter - Kernel level socket filtering
3  *
4  * Based on the design of the Berkeley Packet Filter. The new
5  * internal format has been designed by PLUMgrid:
6  *
7  *	Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
8  *
9  * Authors:
10  *
11  *	Jay Schulist <jschlst@samba.org>
12  *	Alexei Starovoitov <ast@plumgrid.com>
13  *	Daniel Borkmann <dborkman@redhat.com>
14  *
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * as published by the Free Software Foundation; either version
18  * 2 of the License, or (at your option) any later version.
19  *
20  * Andi Kleen - Fix a few bad bugs and races.
21  * Kris Katterjohn - Added many additional checks in bpf_check_classic()
22  */
23 
24 #include <linux/module.h>
25 #include <linux/types.h>
26 #include <linux/mm.h>
27 #include <linux/fcntl.h>
28 #include <linux/socket.h>
29 #include <linux/sock_diag.h>
30 #include <linux/in.h>
31 #include <linux/inet.h>
32 #include <linux/netdevice.h>
33 #include <linux/if_packet.h>
34 #include <linux/if_arp.h>
35 #include <linux/gfp.h>
36 #include <net/inet_common.h>
37 #include <net/ip.h>
38 #include <net/protocol.h>
39 #include <net/netlink.h>
40 #include <linux/skbuff.h>
41 #include <linux/skmsg.h>
42 #include <net/sock.h>
43 #include <net/flow_dissector.h>
44 #include <linux/errno.h>
45 #include <linux/timer.h>
46 #include <linux/uaccess.h>
47 #include <asm/unaligned.h>
48 #include <asm/cmpxchg.h>
49 #include <linux/filter.h>
50 #include <linux/ratelimit.h>
51 #include <linux/seccomp.h>
52 #include <linux/if_vlan.h>
53 #include <linux/bpf.h>
54 #include <net/sch_generic.h>
55 #include <net/cls_cgroup.h>
56 #include <net/dst_metadata.h>
57 #include <net/dst.h>
58 #include <net/sock_reuseport.h>
59 #include <net/busy_poll.h>
60 #include <net/tcp.h>
61 #include <net/xfrm.h>
62 #include <net/udp.h>
63 #include <linux/bpf_trace.h>
64 #include <net/xdp_sock.h>
65 #include <linux/inetdevice.h>
66 #include <net/inet_hashtables.h>
67 #include <net/inet6_hashtables.h>
68 #include <net/ip_fib.h>
69 #include <net/flow.h>
70 #include <net/arp.h>
71 #include <net/ipv6.h>
72 #include <net/net_namespace.h>
73 #include <linux/seg6_local.h>
74 #include <net/seg6.h>
75 #include <net/seg6_local.h>
76 
77 /**
78  *	sk_filter_trim_cap - run a packet through a socket filter
79  *	@sk: sock associated with &sk_buff
80  *	@skb: buffer to filter
81  *	@cap: limit on how short the eBPF program may trim the packet
82  *
83  * Run the eBPF program and then cut skb->data to correct size returned by
84  * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
85  * than pkt_len we keep whole skb->data. This is the socket level
86  * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
87  * be accepted or -EPERM if the packet should be tossed.
88  *
89  */
90 int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
91 {
92 	int err;
93 	struct sk_filter *filter;
94 
95 	/*
96 	 * If the skb was allocated from pfmemalloc reserves, only
97 	 * allow SOCK_MEMALLOC sockets to use it as this socket is
98 	 * helping free memory
99 	 */
100 	if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
101 		NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
102 		return -ENOMEM;
103 	}
104 	err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
105 	if (err)
106 		return err;
107 
108 	err = security_sock_rcv_skb(sk, skb);
109 	if (err)
110 		return err;
111 
112 	rcu_read_lock();
113 	filter = rcu_dereference(sk->sk_filter);
114 	if (filter) {
115 		struct sock *save_sk = skb->sk;
116 		unsigned int pkt_len;
117 
118 		skb->sk = sk;
119 		pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
120 		skb->sk = save_sk;
121 		err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
122 	}
123 	rcu_read_unlock();
124 
125 	return err;
126 }
127 EXPORT_SYMBOL(sk_filter_trim_cap);
128 
129 BPF_CALL_1(bpf_skb_get_pay_offset, struct sk_buff *, skb)
130 {
131 	return skb_get_poff(skb);
132 }
133 
134 BPF_CALL_3(bpf_skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
135 {
136 	struct nlattr *nla;
137 
138 	if (skb_is_nonlinear(skb))
139 		return 0;
140 
141 	if (skb->len < sizeof(struct nlattr))
142 		return 0;
143 
144 	if (a > skb->len - sizeof(struct nlattr))
145 		return 0;
146 
147 	nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
148 	if (nla)
149 		return (void *) nla - (void *) skb->data;
150 
151 	return 0;
152 }
153 
154 BPF_CALL_3(bpf_skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
155 {
156 	struct nlattr *nla;
157 
158 	if (skb_is_nonlinear(skb))
159 		return 0;
160 
161 	if (skb->len < sizeof(struct nlattr))
162 		return 0;
163 
164 	if (a > skb->len - sizeof(struct nlattr))
165 		return 0;
166 
167 	nla = (struct nlattr *) &skb->data[a];
168 	if (nla->nla_len > skb->len - a)
169 		return 0;
170 
171 	nla = nla_find_nested(nla, x);
172 	if (nla)
173 		return (void *) nla - (void *) skb->data;
174 
175 	return 0;
176 }
177 
178 BPF_CALL_4(bpf_skb_load_helper_8, const struct sk_buff *, skb, const void *,
179 	   data, int, headlen, int, offset)
180 {
181 	u8 tmp, *ptr;
182 	const int len = sizeof(tmp);
183 
184 	if (offset >= 0) {
185 		if (headlen - offset >= len)
186 			return *(u8 *)(data + offset);
187 		if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
188 			return tmp;
189 	} else {
190 		ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
191 		if (likely(ptr))
192 			return *(u8 *)ptr;
193 	}
194 
195 	return -EFAULT;
196 }
197 
198 BPF_CALL_2(bpf_skb_load_helper_8_no_cache, const struct sk_buff *, skb,
199 	   int, offset)
200 {
201 	return ____bpf_skb_load_helper_8(skb, skb->data, skb->len - skb->data_len,
202 					 offset);
203 }
204 
205 BPF_CALL_4(bpf_skb_load_helper_16, const struct sk_buff *, skb, const void *,
206 	   data, int, headlen, int, offset)
207 {
208 	u16 tmp, *ptr;
209 	const int len = sizeof(tmp);
210 
211 	if (offset >= 0) {
212 		if (headlen - offset >= len)
213 			return get_unaligned_be16(data + offset);
214 		if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
215 			return be16_to_cpu(tmp);
216 	} else {
217 		ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
218 		if (likely(ptr))
219 			return get_unaligned_be16(ptr);
220 	}
221 
222 	return -EFAULT;
223 }
224 
225 BPF_CALL_2(bpf_skb_load_helper_16_no_cache, const struct sk_buff *, skb,
226 	   int, offset)
227 {
228 	return ____bpf_skb_load_helper_16(skb, skb->data, skb->len - skb->data_len,
229 					  offset);
230 }
231 
232 BPF_CALL_4(bpf_skb_load_helper_32, const struct sk_buff *, skb, const void *,
233 	   data, int, headlen, int, offset)
234 {
235 	u32 tmp, *ptr;
236 	const int len = sizeof(tmp);
237 
238 	if (likely(offset >= 0)) {
239 		if (headlen - offset >= len)
240 			return get_unaligned_be32(data + offset);
241 		if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
242 			return be32_to_cpu(tmp);
243 	} else {
244 		ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
245 		if (likely(ptr))
246 			return get_unaligned_be32(ptr);
247 	}
248 
249 	return -EFAULT;
250 }
251 
252 BPF_CALL_2(bpf_skb_load_helper_32_no_cache, const struct sk_buff *, skb,
253 	   int, offset)
254 {
255 	return ____bpf_skb_load_helper_32(skb, skb->data, skb->len - skb->data_len,
256 					  offset);
257 }
258 
259 BPF_CALL_0(bpf_get_raw_cpu_id)
260 {
261 	return raw_smp_processor_id();
262 }
263 
264 static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
265 	.func		= bpf_get_raw_cpu_id,
266 	.gpl_only	= false,
267 	.ret_type	= RET_INTEGER,
268 };
269 
270 static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
271 			      struct bpf_insn *insn_buf)
272 {
273 	struct bpf_insn *insn = insn_buf;
274 
275 	switch (skb_field) {
276 	case SKF_AD_MARK:
277 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);
278 
279 		*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
280 				      offsetof(struct sk_buff, mark));
281 		break;
282 
283 	case SKF_AD_PKTTYPE:
284 		*insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET());
285 		*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
286 #ifdef __BIG_ENDIAN_BITFIELD
287 		*insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
288 #endif
289 		break;
290 
291 	case SKF_AD_QUEUE:
292 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2);
293 
294 		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
295 				      offsetof(struct sk_buff, queue_mapping));
296 		break;
297 
298 	case SKF_AD_VLAN_TAG:
299 	case SKF_AD_VLAN_TAG_PRESENT:
300 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_tci) != 2);
301 		BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);
302 
303 		/* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
304 		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
305 				      offsetof(struct sk_buff, vlan_tci));
306 		if (skb_field == SKF_AD_VLAN_TAG) {
307 			*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg,
308 						~VLAN_TAG_PRESENT);
309 		} else {
310 			/* dst_reg >>= 12 */
311 			*insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 12);
312 			/* dst_reg &= 1 */
313 			*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1);
314 		}
315 		break;
316 	}
317 
318 	return insn - insn_buf;
319 }
320 
321 static bool convert_bpf_extensions(struct sock_filter *fp,
322 				   struct bpf_insn **insnp)
323 {
324 	struct bpf_insn *insn = *insnp;
325 	u32 cnt;
326 
327 	switch (fp->k) {
328 	case SKF_AD_OFF + SKF_AD_PROTOCOL:
329 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);
330 
331 		/* A = *(u16 *) (CTX + offsetof(protocol)) */
332 		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
333 				      offsetof(struct sk_buff, protocol));
334 		/* A = ntohs(A) [emitting a nop or swap16] */
335 		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
336 		break;
337 
338 	case SKF_AD_OFF + SKF_AD_PKTTYPE:
339 		cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
340 		insn += cnt - 1;
341 		break;
342 
343 	case SKF_AD_OFF + SKF_AD_IFINDEX:
344 	case SKF_AD_OFF + SKF_AD_HATYPE:
345 		BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
346 		BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, type) != 2);
347 
348 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
349 				      BPF_REG_TMP, BPF_REG_CTX,
350 				      offsetof(struct sk_buff, dev));
351 		/* if (tmp != 0) goto pc + 1 */
352 		*insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
353 		*insn++ = BPF_EXIT_INSN();
354 		if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
355 			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
356 					    offsetof(struct net_device, ifindex));
357 		else
358 			*insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
359 					    offsetof(struct net_device, type));
360 		break;
361 
362 	case SKF_AD_OFF + SKF_AD_MARK:
363 		cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
364 		insn += cnt - 1;
365 		break;
366 
367 	case SKF_AD_OFF + SKF_AD_RXHASH:
368 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);
369 
370 		*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
371 				    offsetof(struct sk_buff, hash));
372 		break;
373 
374 	case SKF_AD_OFF + SKF_AD_QUEUE:
375 		cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
376 		insn += cnt - 1;
377 		break;
378 
379 	case SKF_AD_OFF + SKF_AD_VLAN_TAG:
380 		cnt = convert_skb_access(SKF_AD_VLAN_TAG,
381 					 BPF_REG_A, BPF_REG_CTX, insn);
382 		insn += cnt - 1;
383 		break;
384 
385 	case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
386 		cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
387 					 BPF_REG_A, BPF_REG_CTX, insn);
388 		insn += cnt - 1;
389 		break;
390 
391 	case SKF_AD_OFF + SKF_AD_VLAN_TPID:
392 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);
393 
394 		/* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
395 		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
396 				      offsetof(struct sk_buff, vlan_proto));
397 		/* A = ntohs(A) [emitting a nop or swap16] */
398 		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
399 		break;
400 
401 	case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
402 	case SKF_AD_OFF + SKF_AD_NLATTR:
403 	case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
404 	case SKF_AD_OFF + SKF_AD_CPU:
405 	case SKF_AD_OFF + SKF_AD_RANDOM:
406 		/* arg1 = CTX */
407 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
408 		/* arg2 = A */
409 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
410 		/* arg3 = X */
411 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
412 		/* Emit call(arg1=CTX, arg2=A, arg3=X) */
413 		switch (fp->k) {
414 		case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
415 			*insn = BPF_EMIT_CALL(bpf_skb_get_pay_offset);
416 			break;
417 		case SKF_AD_OFF + SKF_AD_NLATTR:
418 			*insn = BPF_EMIT_CALL(bpf_skb_get_nlattr);
419 			break;
420 		case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
421 			*insn = BPF_EMIT_CALL(bpf_skb_get_nlattr_nest);
422 			break;
423 		case SKF_AD_OFF + SKF_AD_CPU:
424 			*insn = BPF_EMIT_CALL(bpf_get_raw_cpu_id);
425 			break;
426 		case SKF_AD_OFF + SKF_AD_RANDOM:
427 			*insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
428 			bpf_user_rnd_init_once();
429 			break;
430 		}
431 		break;
432 
433 	case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
434 		/* A ^= X */
435 		*insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
436 		break;
437 
438 	default:
439 		/* This is just a dummy call to avoid letting the compiler
440 		 * evict __bpf_call_base() as an optimization. Placed here
441 		 * where no-one bothers.
442 		 */
443 		BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
444 		return false;
445 	}
446 
447 	*insnp = insn;
448 	return true;
449 }
450 
451 static bool convert_bpf_ld_abs(struct sock_filter *fp, struct bpf_insn **insnp)
452 {
453 	const bool unaligned_ok = IS_BUILTIN(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS);
454 	int size = bpf_size_to_bytes(BPF_SIZE(fp->code));
455 	bool endian = BPF_SIZE(fp->code) == BPF_H ||
456 		      BPF_SIZE(fp->code) == BPF_W;
457 	bool indirect = BPF_MODE(fp->code) == BPF_IND;
458 	const int ip_align = NET_IP_ALIGN;
459 	struct bpf_insn *insn = *insnp;
460 	int offset = fp->k;
461 
462 	if (!indirect &&
463 	    ((unaligned_ok && offset >= 0) ||
464 	     (!unaligned_ok && offset >= 0 &&
465 	      offset + ip_align >= 0 &&
466 	      offset + ip_align % size == 0))) {
467 		bool ldx_off_ok = offset <= S16_MAX;
468 
469 		*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_H);
470 		*insn++ = BPF_ALU64_IMM(BPF_SUB, BPF_REG_TMP, offset);
471 		*insn++ = BPF_JMP_IMM(BPF_JSLT, BPF_REG_TMP,
472 				      size, 2 + endian + (!ldx_off_ok * 2));
473 		if (ldx_off_ok) {
474 			*insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
475 					      BPF_REG_D, offset);
476 		} else {
477 			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_D);
478 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_TMP, offset);
479 			*insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
480 					      BPF_REG_TMP, 0);
481 		}
482 		if (endian)
483 			*insn++ = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, size * 8);
484 		*insn++ = BPF_JMP_A(8);
485 	}
486 
487 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
488 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_D);
489 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_H);
490 	if (!indirect) {
491 		*insn++ = BPF_MOV64_IMM(BPF_REG_ARG4, offset);
492 	} else {
493 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG4, BPF_REG_X);
494 		if (fp->k)
495 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_ARG4, offset);
496 	}
497 
498 	switch (BPF_SIZE(fp->code)) {
499 	case BPF_B:
500 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8);
501 		break;
502 	case BPF_H:
503 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16);
504 		break;
505 	case BPF_W:
506 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32);
507 		break;
508 	default:
509 		return false;
510 	}
511 
512 	*insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_A, 0, 2);
513 	*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
514 	*insn   = BPF_EXIT_INSN();
515 
516 	*insnp = insn;
517 	return true;
518 }
519 
520 /**
521  *	bpf_convert_filter - convert filter program
522  *	@prog: the user passed filter program
523  *	@len: the length of the user passed filter program
524  *	@new_prog: allocated 'struct bpf_prog' or NULL
525  *	@new_len: pointer to store length of converted program
526  *	@seen_ld_abs: bool whether we've seen ld_abs/ind
527  *
528  * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
529  * style extended BPF (eBPF).
530  * Conversion workflow:
531  *
532  * 1) First pass for calculating the new program length:
533  *   bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs)
534  *
535  * 2) 2nd pass to remap in two passes: 1st pass finds new
536  *    jump offsets, 2nd pass remapping:
537  *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len, &seen_ld_abs)
538  */
539 static int bpf_convert_filter(struct sock_filter *prog, int len,
540 			      struct bpf_prog *new_prog, int *new_len,
541 			      bool *seen_ld_abs)
542 {
543 	int new_flen = 0, pass = 0, target, i, stack_off;
544 	struct bpf_insn *new_insn, *first_insn = NULL;
545 	struct sock_filter *fp;
546 	int *addrs = NULL;
547 	u8 bpf_src;
548 
549 	BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
550 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
551 
552 	if (len <= 0 || len > BPF_MAXINSNS)
553 		return -EINVAL;
554 
555 	if (new_prog) {
556 		first_insn = new_prog->insnsi;
557 		addrs = kcalloc(len, sizeof(*addrs),
558 				GFP_KERNEL | __GFP_NOWARN);
559 		if (!addrs)
560 			return -ENOMEM;
561 	}
562 
563 do_pass:
564 	new_insn = first_insn;
565 	fp = prog;
566 
567 	/* Classic BPF related prologue emission. */
568 	if (new_prog) {
569 		/* Classic BPF expects A and X to be reset first. These need
570 		 * to be guaranteed to be the first two instructions.
571 		 */
572 		*new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
573 		*new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
574 
575 		/* All programs must keep CTX in callee saved BPF_REG_CTX.
576 		 * In eBPF case it's done by the compiler, here we need to
577 		 * do this ourself. Initial CTX is present in BPF_REG_ARG1.
578 		 */
579 		*new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
580 		if (*seen_ld_abs) {
581 			/* For packet access in classic BPF, cache skb->data
582 			 * in callee-saved BPF R8 and skb->len - skb->data_len
583 			 * (headlen) in BPF R9. Since classic BPF is read-only
584 			 * on CTX, we only need to cache it once.
585 			 */
586 			*new_insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
587 						  BPF_REG_D, BPF_REG_CTX,
588 						  offsetof(struct sk_buff, data));
589 			*new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_H, BPF_REG_CTX,
590 						  offsetof(struct sk_buff, len));
591 			*new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_TMP, BPF_REG_CTX,
592 						  offsetof(struct sk_buff, data_len));
593 			*new_insn++ = BPF_ALU32_REG(BPF_SUB, BPF_REG_H, BPF_REG_TMP);
594 		}
595 	} else {
596 		new_insn += 3;
597 	}
598 
599 	for (i = 0; i < len; fp++, i++) {
600 		struct bpf_insn tmp_insns[32] = { };
601 		struct bpf_insn *insn = tmp_insns;
602 
603 		if (addrs)
604 			addrs[i] = new_insn - first_insn;
605 
606 		switch (fp->code) {
607 		/* All arithmetic insns and skb loads map as-is. */
608 		case BPF_ALU | BPF_ADD | BPF_X:
609 		case BPF_ALU | BPF_ADD | BPF_K:
610 		case BPF_ALU | BPF_SUB | BPF_X:
611 		case BPF_ALU | BPF_SUB | BPF_K:
612 		case BPF_ALU | BPF_AND | BPF_X:
613 		case BPF_ALU | BPF_AND | BPF_K:
614 		case BPF_ALU | BPF_OR | BPF_X:
615 		case BPF_ALU | BPF_OR | BPF_K:
616 		case BPF_ALU | BPF_LSH | BPF_X:
617 		case BPF_ALU | BPF_LSH | BPF_K:
618 		case BPF_ALU | BPF_RSH | BPF_X:
619 		case BPF_ALU | BPF_RSH | BPF_K:
620 		case BPF_ALU | BPF_XOR | BPF_X:
621 		case BPF_ALU | BPF_XOR | BPF_K:
622 		case BPF_ALU | BPF_MUL | BPF_X:
623 		case BPF_ALU | BPF_MUL | BPF_K:
624 		case BPF_ALU | BPF_DIV | BPF_X:
625 		case BPF_ALU | BPF_DIV | BPF_K:
626 		case BPF_ALU | BPF_MOD | BPF_X:
627 		case BPF_ALU | BPF_MOD | BPF_K:
628 		case BPF_ALU | BPF_NEG:
629 		case BPF_LD | BPF_ABS | BPF_W:
630 		case BPF_LD | BPF_ABS | BPF_H:
631 		case BPF_LD | BPF_ABS | BPF_B:
632 		case BPF_LD | BPF_IND | BPF_W:
633 		case BPF_LD | BPF_IND | BPF_H:
634 		case BPF_LD | BPF_IND | BPF_B:
635 			/* Check for overloaded BPF extension and
636 			 * directly convert it if found, otherwise
637 			 * just move on with mapping.
638 			 */
639 			if (BPF_CLASS(fp->code) == BPF_LD &&
640 			    BPF_MODE(fp->code) == BPF_ABS &&
641 			    convert_bpf_extensions(fp, &insn))
642 				break;
643 			if (BPF_CLASS(fp->code) == BPF_LD &&
644 			    convert_bpf_ld_abs(fp, &insn)) {
645 				*seen_ld_abs = true;
646 				break;
647 			}
648 
649 			if (fp->code == (BPF_ALU | BPF_DIV | BPF_X) ||
650 			    fp->code == (BPF_ALU | BPF_MOD | BPF_X)) {
651 				*insn++ = BPF_MOV32_REG(BPF_REG_X, BPF_REG_X);
652 				/* Error with exception code on div/mod by 0.
653 				 * For cBPF programs, this was always return 0.
654 				 */
655 				*insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_X, 0, 2);
656 				*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
657 				*insn++ = BPF_EXIT_INSN();
658 			}
659 
660 			*insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
661 			break;
662 
663 		/* Jump transformation cannot use BPF block macros
664 		 * everywhere as offset calculation and target updates
665 		 * require a bit more work than the rest, i.e. jump
666 		 * opcodes map as-is, but offsets need adjustment.
667 		 */
668 
669 #define BPF_EMIT_JMP							\
670 	do {								\
671 		const s32 off_min = S16_MIN, off_max = S16_MAX;		\
672 		s32 off;						\
673 									\
674 		if (target >= len || target < 0)			\
675 			goto err;					\
676 		off = addrs ? addrs[target] - addrs[i] - 1 : 0;		\
677 		/* Adjust pc relative offset for 2nd or 3rd insn. */	\
678 		off -= insn - tmp_insns;				\
679 		/* Reject anything not fitting into insn->off. */	\
680 		if (off < off_min || off > off_max)			\
681 			goto err;					\
682 		insn->off = off;					\
683 	} while (0)
684 
685 		case BPF_JMP | BPF_JA:
686 			target = i + fp->k + 1;
687 			insn->code = fp->code;
688 			BPF_EMIT_JMP;
689 			break;
690 
691 		case BPF_JMP | BPF_JEQ | BPF_K:
692 		case BPF_JMP | BPF_JEQ | BPF_X:
693 		case BPF_JMP | BPF_JSET | BPF_K:
694 		case BPF_JMP | BPF_JSET | BPF_X:
695 		case BPF_JMP | BPF_JGT | BPF_K:
696 		case BPF_JMP | BPF_JGT | BPF_X:
697 		case BPF_JMP | BPF_JGE | BPF_K:
698 		case BPF_JMP | BPF_JGE | BPF_X:
699 			if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
700 				/* BPF immediates are signed, zero extend
701 				 * immediate into tmp register and use it
702 				 * in compare insn.
703 				 */
704 				*insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
705 
706 				insn->dst_reg = BPF_REG_A;
707 				insn->src_reg = BPF_REG_TMP;
708 				bpf_src = BPF_X;
709 			} else {
710 				insn->dst_reg = BPF_REG_A;
711 				insn->imm = fp->k;
712 				bpf_src = BPF_SRC(fp->code);
713 				insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
714 			}
715 
716 			/* Common case where 'jump_false' is next insn. */
717 			if (fp->jf == 0) {
718 				insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
719 				target = i + fp->jt + 1;
720 				BPF_EMIT_JMP;
721 				break;
722 			}
723 
724 			/* Convert some jumps when 'jump_true' is next insn. */
725 			if (fp->jt == 0) {
726 				switch (BPF_OP(fp->code)) {
727 				case BPF_JEQ:
728 					insn->code = BPF_JMP | BPF_JNE | bpf_src;
729 					break;
730 				case BPF_JGT:
731 					insn->code = BPF_JMP | BPF_JLE | bpf_src;
732 					break;
733 				case BPF_JGE:
734 					insn->code = BPF_JMP | BPF_JLT | bpf_src;
735 					break;
736 				default:
737 					goto jmp_rest;
738 				}
739 
740 				target = i + fp->jf + 1;
741 				BPF_EMIT_JMP;
742 				break;
743 			}
744 jmp_rest:
745 			/* Other jumps are mapped into two insns: Jxx and JA. */
746 			target = i + fp->jt + 1;
747 			insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
748 			BPF_EMIT_JMP;
749 			insn++;
750 
751 			insn->code = BPF_JMP | BPF_JA;
752 			target = i + fp->jf + 1;
753 			BPF_EMIT_JMP;
754 			break;
755 
756 		/* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
757 		case BPF_LDX | BPF_MSH | BPF_B: {
758 			struct sock_filter tmp = {
759 				.code	= BPF_LD | BPF_ABS | BPF_B,
760 				.k	= fp->k,
761 			};
762 
763 			*seen_ld_abs = true;
764 
765 			/* X = A */
766 			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
767 			/* A = BPF_R0 = *(u8 *) (skb->data + K) */
768 			convert_bpf_ld_abs(&tmp, &insn);
769 			insn++;
770 			/* A &= 0xf */
771 			*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
772 			/* A <<= 2 */
773 			*insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
774 			/* tmp = X */
775 			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_X);
776 			/* X = A */
777 			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
778 			/* A = tmp */
779 			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
780 			break;
781 		}
782 		/* RET_K is remaped into 2 insns. RET_A case doesn't need an
783 		 * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
784 		 */
785 		case BPF_RET | BPF_A:
786 		case BPF_RET | BPF_K:
787 			if (BPF_RVAL(fp->code) == BPF_K)
788 				*insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
789 							0, fp->k);
790 			*insn = BPF_EXIT_INSN();
791 			break;
792 
793 		/* Store to stack. */
794 		case BPF_ST:
795 		case BPF_STX:
796 			stack_off = fp->k * 4  + 4;
797 			*insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
798 					    BPF_ST ? BPF_REG_A : BPF_REG_X,
799 					    -stack_off);
800 			/* check_load_and_stores() verifies that classic BPF can
801 			 * load from stack only after write, so tracking
802 			 * stack_depth for ST|STX insns is enough
803 			 */
804 			if (new_prog && new_prog->aux->stack_depth < stack_off)
805 				new_prog->aux->stack_depth = stack_off;
806 			break;
807 
808 		/* Load from stack. */
809 		case BPF_LD | BPF_MEM:
810 		case BPF_LDX | BPF_MEM:
811 			stack_off = fp->k * 4  + 4;
812 			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
813 					    BPF_REG_A : BPF_REG_X, BPF_REG_FP,
814 					    -stack_off);
815 			break;
816 
817 		/* A = K or X = K */
818 		case BPF_LD | BPF_IMM:
819 		case BPF_LDX | BPF_IMM:
820 			*insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
821 					      BPF_REG_A : BPF_REG_X, fp->k);
822 			break;
823 
824 		/* X = A */
825 		case BPF_MISC | BPF_TAX:
826 			*insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
827 			break;
828 
829 		/* A = X */
830 		case BPF_MISC | BPF_TXA:
831 			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
832 			break;
833 
834 		/* A = skb->len or X = skb->len */
835 		case BPF_LD | BPF_W | BPF_LEN:
836 		case BPF_LDX | BPF_W | BPF_LEN:
837 			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
838 					    BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
839 					    offsetof(struct sk_buff, len));
840 			break;
841 
842 		/* Access seccomp_data fields. */
843 		case BPF_LDX | BPF_ABS | BPF_W:
844 			/* A = *(u32 *) (ctx + K) */
845 			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
846 			break;
847 
848 		/* Unknown instruction. */
849 		default:
850 			goto err;
851 		}
852 
853 		insn++;
854 		if (new_prog)
855 			memcpy(new_insn, tmp_insns,
856 			       sizeof(*insn) * (insn - tmp_insns));
857 		new_insn += insn - tmp_insns;
858 	}
859 
860 	if (!new_prog) {
861 		/* Only calculating new length. */
862 		*new_len = new_insn - first_insn;
863 		if (*seen_ld_abs)
864 			*new_len += 4; /* Prologue bits. */
865 		return 0;
866 	}
867 
868 	pass++;
869 	if (new_flen != new_insn - first_insn) {
870 		new_flen = new_insn - first_insn;
871 		if (pass > 2)
872 			goto err;
873 		goto do_pass;
874 	}
875 
876 	kfree(addrs);
877 	BUG_ON(*new_len != new_flen);
878 	return 0;
879 err:
880 	kfree(addrs);
881 	return -EINVAL;
882 }
883 
884 /* Security:
885  *
886  * As we dont want to clear mem[] array for each packet going through
887  * __bpf_prog_run(), we check that filter loaded by user never try to read
888  * a cell if not previously written, and we check all branches to be sure
889  * a malicious user doesn't try to abuse us.
890  */
891 static int check_load_and_stores(const struct sock_filter *filter, int flen)
892 {
893 	u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
894 	int pc, ret = 0;
895 
896 	BUILD_BUG_ON(BPF_MEMWORDS > 16);
897 
898 	masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
899 	if (!masks)
900 		return -ENOMEM;
901 
902 	memset(masks, 0xff, flen * sizeof(*masks));
903 
904 	for (pc = 0; pc < flen; pc++) {
905 		memvalid &= masks[pc];
906 
907 		switch (filter[pc].code) {
908 		case BPF_ST:
909 		case BPF_STX:
910 			memvalid |= (1 << filter[pc].k);
911 			break;
912 		case BPF_LD | BPF_MEM:
913 		case BPF_LDX | BPF_MEM:
914 			if (!(memvalid & (1 << filter[pc].k))) {
915 				ret = -EINVAL;
916 				goto error;
917 			}
918 			break;
919 		case BPF_JMP | BPF_JA:
920 			/* A jump must set masks on target */
921 			masks[pc + 1 + filter[pc].k] &= memvalid;
922 			memvalid = ~0;
923 			break;
924 		case BPF_JMP | BPF_JEQ | BPF_K:
925 		case BPF_JMP | BPF_JEQ | BPF_X:
926 		case BPF_JMP | BPF_JGE | BPF_K:
927 		case BPF_JMP | BPF_JGE | BPF_X:
928 		case BPF_JMP | BPF_JGT | BPF_K:
929 		case BPF_JMP | BPF_JGT | BPF_X:
930 		case BPF_JMP | BPF_JSET | BPF_K:
931 		case BPF_JMP | BPF_JSET | BPF_X:
932 			/* A jump must set masks on targets */
933 			masks[pc + 1 + filter[pc].jt] &= memvalid;
934 			masks[pc + 1 + filter[pc].jf] &= memvalid;
935 			memvalid = ~0;
936 			break;
937 		}
938 	}
939 error:
940 	kfree(masks);
941 	return ret;
942 }
943 
944 static bool chk_code_allowed(u16 code_to_probe)
945 {
946 	static const bool codes[] = {
947 		/* 32 bit ALU operations */
948 		[BPF_ALU | BPF_ADD | BPF_K] = true,
949 		[BPF_ALU | BPF_ADD | BPF_X] = true,
950 		[BPF_ALU | BPF_SUB | BPF_K] = true,
951 		[BPF_ALU | BPF_SUB | BPF_X] = true,
952 		[BPF_ALU | BPF_MUL | BPF_K] = true,
953 		[BPF_ALU | BPF_MUL | BPF_X] = true,
954 		[BPF_ALU | BPF_DIV | BPF_K] = true,
955 		[BPF_ALU | BPF_DIV | BPF_X] = true,
956 		[BPF_ALU | BPF_MOD | BPF_K] = true,
957 		[BPF_ALU | BPF_MOD | BPF_X] = true,
958 		[BPF_ALU | BPF_AND | BPF_K] = true,
959 		[BPF_ALU | BPF_AND | BPF_X] = true,
960 		[BPF_ALU | BPF_OR | BPF_K] = true,
961 		[BPF_ALU | BPF_OR | BPF_X] = true,
962 		[BPF_ALU | BPF_XOR | BPF_K] = true,
963 		[BPF_ALU | BPF_XOR | BPF_X] = true,
964 		[BPF_ALU | BPF_LSH | BPF_K] = true,
965 		[BPF_ALU | BPF_LSH | BPF_X] = true,
966 		[BPF_ALU | BPF_RSH | BPF_K] = true,
967 		[BPF_ALU | BPF_RSH | BPF_X] = true,
968 		[BPF_ALU | BPF_NEG] = true,
969 		/* Load instructions */
970 		[BPF_LD | BPF_W | BPF_ABS] = true,
971 		[BPF_LD | BPF_H | BPF_ABS] = true,
972 		[BPF_LD | BPF_B | BPF_ABS] = true,
973 		[BPF_LD | BPF_W | BPF_LEN] = true,
974 		[BPF_LD | BPF_W | BPF_IND] = true,
975 		[BPF_LD | BPF_H | BPF_IND] = true,
976 		[BPF_LD | BPF_B | BPF_IND] = true,
977 		[BPF_LD | BPF_IMM] = true,
978 		[BPF_LD | BPF_MEM] = true,
979 		[BPF_LDX | BPF_W | BPF_LEN] = true,
980 		[BPF_LDX | BPF_B | BPF_MSH] = true,
981 		[BPF_LDX | BPF_IMM] = true,
982 		[BPF_LDX | BPF_MEM] = true,
983 		/* Store instructions */
984 		[BPF_ST] = true,
985 		[BPF_STX] = true,
986 		/* Misc instructions */
987 		[BPF_MISC | BPF_TAX] = true,
988 		[BPF_MISC | BPF_TXA] = true,
989 		/* Return instructions */
990 		[BPF_RET | BPF_K] = true,
991 		[BPF_RET | BPF_A] = true,
992 		/* Jump instructions */
993 		[BPF_JMP | BPF_JA] = true,
994 		[BPF_JMP | BPF_JEQ | BPF_K] = true,
995 		[BPF_JMP | BPF_JEQ | BPF_X] = true,
996 		[BPF_JMP | BPF_JGE | BPF_K] = true,
997 		[BPF_JMP | BPF_JGE | BPF_X] = true,
998 		[BPF_JMP | BPF_JGT | BPF_K] = true,
999 		[BPF_JMP | BPF_JGT | BPF_X] = true,
1000 		[BPF_JMP | BPF_JSET | BPF_K] = true,
1001 		[BPF_JMP | BPF_JSET | BPF_X] = true,
1002 	};
1003 
1004 	if (code_to_probe >= ARRAY_SIZE(codes))
1005 		return false;
1006 
1007 	return codes[code_to_probe];
1008 }
1009 
1010 static bool bpf_check_basics_ok(const struct sock_filter *filter,
1011 				unsigned int flen)
1012 {
1013 	if (filter == NULL)
1014 		return false;
1015 	if (flen == 0 || flen > BPF_MAXINSNS)
1016 		return false;
1017 
1018 	return true;
1019 }
1020 
1021 /**
1022  *	bpf_check_classic - verify socket filter code
1023  *	@filter: filter to verify
1024  *	@flen: length of filter
1025  *
1026  * Check the user's filter code. If we let some ugly
1027  * filter code slip through kaboom! The filter must contain
1028  * no references or jumps that are out of range, no illegal
1029  * instructions, and must end with a RET instruction.
1030  *
1031  * All jumps are forward as they are not signed.
1032  *
1033  * Returns 0 if the rule set is legal or -EINVAL if not.
1034  */
1035 static int bpf_check_classic(const struct sock_filter *filter,
1036 			     unsigned int flen)
1037 {
1038 	bool anc_found;
1039 	int pc;
1040 
1041 	/* Check the filter code now */
1042 	for (pc = 0; pc < flen; pc++) {
1043 		const struct sock_filter *ftest = &filter[pc];
1044 
1045 		/* May we actually operate on this code? */
1046 		if (!chk_code_allowed(ftest->code))
1047 			return -EINVAL;
1048 
1049 		/* Some instructions need special checks */
1050 		switch (ftest->code) {
1051 		case BPF_ALU | BPF_DIV | BPF_K:
1052 		case BPF_ALU | BPF_MOD | BPF_K:
1053 			/* Check for division by zero */
1054 			if (ftest->k == 0)
1055 				return -EINVAL;
1056 			break;
1057 		case BPF_ALU | BPF_LSH | BPF_K:
1058 		case BPF_ALU | BPF_RSH | BPF_K:
1059 			if (ftest->k >= 32)
1060 				return -EINVAL;
1061 			break;
1062 		case BPF_LD | BPF_MEM:
1063 		case BPF_LDX | BPF_MEM:
1064 		case BPF_ST:
1065 		case BPF_STX:
1066 			/* Check for invalid memory addresses */
1067 			if (ftest->k >= BPF_MEMWORDS)
1068 				return -EINVAL;
1069 			break;
1070 		case BPF_JMP | BPF_JA:
1071 			/* Note, the large ftest->k might cause loops.
1072 			 * Compare this with conditional jumps below,
1073 			 * where offsets are limited. --ANK (981016)
1074 			 */
1075 			if (ftest->k >= (unsigned int)(flen - pc - 1))
1076 				return -EINVAL;
1077 			break;
1078 		case BPF_JMP | BPF_JEQ | BPF_K:
1079 		case BPF_JMP | BPF_JEQ | BPF_X:
1080 		case BPF_JMP | BPF_JGE | BPF_K:
1081 		case BPF_JMP | BPF_JGE | BPF_X:
1082 		case BPF_JMP | BPF_JGT | BPF_K:
1083 		case BPF_JMP | BPF_JGT | BPF_X:
1084 		case BPF_JMP | BPF_JSET | BPF_K:
1085 		case BPF_JMP | BPF_JSET | BPF_X:
1086 			/* Both conditionals must be safe */
1087 			if (pc + ftest->jt + 1 >= flen ||
1088 			    pc + ftest->jf + 1 >= flen)
1089 				return -EINVAL;
1090 			break;
1091 		case BPF_LD | BPF_W | BPF_ABS:
1092 		case BPF_LD | BPF_H | BPF_ABS:
1093 		case BPF_LD | BPF_B | BPF_ABS:
1094 			anc_found = false;
1095 			if (bpf_anc_helper(ftest) & BPF_ANC)
1096 				anc_found = true;
1097 			/* Ancillary operation unknown or unsupported */
1098 			if (anc_found == false && ftest->k >= SKF_AD_OFF)
1099 				return -EINVAL;
1100 		}
1101 	}
1102 
1103 	/* Last instruction must be a RET code */
1104 	switch (filter[flen - 1].code) {
1105 	case BPF_RET | BPF_K:
1106 	case BPF_RET | BPF_A:
1107 		return check_load_and_stores(filter, flen);
1108 	}
1109 
1110 	return -EINVAL;
1111 }
1112 
1113 static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
1114 				      const struct sock_fprog *fprog)
1115 {
1116 	unsigned int fsize = bpf_classic_proglen(fprog);
1117 	struct sock_fprog_kern *fkprog;
1118 
1119 	fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
1120 	if (!fp->orig_prog)
1121 		return -ENOMEM;
1122 
1123 	fkprog = fp->orig_prog;
1124 	fkprog->len = fprog->len;
1125 
1126 	fkprog->filter = kmemdup(fp->insns, fsize,
1127 				 GFP_KERNEL | __GFP_NOWARN);
1128 	if (!fkprog->filter) {
1129 		kfree(fp->orig_prog);
1130 		return -ENOMEM;
1131 	}
1132 
1133 	return 0;
1134 }
1135 
1136 static void bpf_release_orig_filter(struct bpf_prog *fp)
1137 {
1138 	struct sock_fprog_kern *fprog = fp->orig_prog;
1139 
1140 	if (fprog) {
1141 		kfree(fprog->filter);
1142 		kfree(fprog);
1143 	}
1144 }
1145 
1146 static void __bpf_prog_release(struct bpf_prog *prog)
1147 {
1148 	if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
1149 		bpf_prog_put(prog);
1150 	} else {
1151 		bpf_release_orig_filter(prog);
1152 		bpf_prog_free(prog);
1153 	}
1154 }
1155 
1156 static void __sk_filter_release(struct sk_filter *fp)
1157 {
1158 	__bpf_prog_release(fp->prog);
1159 	kfree(fp);
1160 }
1161 
1162 /**
1163  * 	sk_filter_release_rcu - Release a socket filter by rcu_head
1164  *	@rcu: rcu_head that contains the sk_filter to free
1165  */
1166 static void sk_filter_release_rcu(struct rcu_head *rcu)
1167 {
1168 	struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
1169 
1170 	__sk_filter_release(fp);
1171 }
1172 
1173 /**
1174  *	sk_filter_release - release a socket filter
1175  *	@fp: filter to remove
1176  *
1177  *	Remove a filter from a socket and release its resources.
1178  */
1179 static void sk_filter_release(struct sk_filter *fp)
1180 {
1181 	if (refcount_dec_and_test(&fp->refcnt))
1182 		call_rcu(&fp->rcu, sk_filter_release_rcu);
1183 }
1184 
1185 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
1186 {
1187 	u32 filter_size = bpf_prog_size(fp->prog->len);
1188 
1189 	atomic_sub(filter_size, &sk->sk_omem_alloc);
1190 	sk_filter_release(fp);
1191 }
1192 
1193 /* try to charge the socket memory if there is space available
1194  * return true on success
1195  */
1196 static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1197 {
1198 	u32 filter_size = bpf_prog_size(fp->prog->len);
1199 
1200 	/* same check as in sock_kmalloc() */
1201 	if (filter_size <= sysctl_optmem_max &&
1202 	    atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
1203 		atomic_add(filter_size, &sk->sk_omem_alloc);
1204 		return true;
1205 	}
1206 	return false;
1207 }
1208 
1209 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1210 {
1211 	if (!refcount_inc_not_zero(&fp->refcnt))
1212 		return false;
1213 
1214 	if (!__sk_filter_charge(sk, fp)) {
1215 		sk_filter_release(fp);
1216 		return false;
1217 	}
1218 	return true;
1219 }
1220 
1221 static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
1222 {
1223 	struct sock_filter *old_prog;
1224 	struct bpf_prog *old_fp;
1225 	int err, new_len, old_len = fp->len;
1226 	bool seen_ld_abs = false;
1227 
1228 	/* We are free to overwrite insns et al right here as it
1229 	 * won't be used at this point in time anymore internally
1230 	 * after the migration to the internal BPF instruction
1231 	 * representation.
1232 	 */
1233 	BUILD_BUG_ON(sizeof(struct sock_filter) !=
1234 		     sizeof(struct bpf_insn));
1235 
1236 	/* Conversion cannot happen on overlapping memory areas,
1237 	 * so we need to keep the user BPF around until the 2nd
1238 	 * pass. At this time, the user BPF is stored in fp->insns.
1239 	 */
1240 	old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
1241 			   GFP_KERNEL | __GFP_NOWARN);
1242 	if (!old_prog) {
1243 		err = -ENOMEM;
1244 		goto out_err;
1245 	}
1246 
1247 	/* 1st pass: calculate the new program length. */
1248 	err = bpf_convert_filter(old_prog, old_len, NULL, &new_len,
1249 				 &seen_ld_abs);
1250 	if (err)
1251 		goto out_err_free;
1252 
1253 	/* Expand fp for appending the new filter representation. */
1254 	old_fp = fp;
1255 	fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1256 	if (!fp) {
1257 		/* The old_fp is still around in case we couldn't
1258 		 * allocate new memory, so uncharge on that one.
1259 		 */
1260 		fp = old_fp;
1261 		err = -ENOMEM;
1262 		goto out_err_free;
1263 	}
1264 
1265 	fp->len = new_len;
1266 
1267 	/* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1268 	err = bpf_convert_filter(old_prog, old_len, fp, &new_len,
1269 				 &seen_ld_abs);
1270 	if (err)
1271 		/* 2nd bpf_convert_filter() can fail only if it fails
1272 		 * to allocate memory, remapping must succeed. Note,
1273 		 * that at this time old_fp has already been released
1274 		 * by krealloc().
1275 		 */
1276 		goto out_err_free;
1277 
1278 	fp = bpf_prog_select_runtime(fp, &err);
1279 	if (err)
1280 		goto out_err_free;
1281 
1282 	kfree(old_prog);
1283 	return fp;
1284 
1285 out_err_free:
1286 	kfree(old_prog);
1287 out_err:
1288 	__bpf_prog_release(fp);
1289 	return ERR_PTR(err);
1290 }
1291 
1292 static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
1293 					   bpf_aux_classic_check_t trans)
1294 {
1295 	int err;
1296 
1297 	fp->bpf_func = NULL;
1298 	fp->jited = 0;
1299 
1300 	err = bpf_check_classic(fp->insns, fp->len);
1301 	if (err) {
1302 		__bpf_prog_release(fp);
1303 		return ERR_PTR(err);
1304 	}
1305 
1306 	/* There might be additional checks and transformations
1307 	 * needed on classic filters, f.e. in case of seccomp.
1308 	 */
1309 	if (trans) {
1310 		err = trans(fp->insns, fp->len);
1311 		if (err) {
1312 			__bpf_prog_release(fp);
1313 			return ERR_PTR(err);
1314 		}
1315 	}
1316 
1317 	/* Probe if we can JIT compile the filter and if so, do
1318 	 * the compilation of the filter.
1319 	 */
1320 	bpf_jit_compile(fp);
1321 
1322 	/* JIT compiler couldn't process this filter, so do the
1323 	 * internal BPF translation for the optimized interpreter.
1324 	 */
1325 	if (!fp->jited)
1326 		fp = bpf_migrate_filter(fp);
1327 
1328 	return fp;
1329 }
1330 
1331 /**
1332  *	bpf_prog_create - create an unattached filter
1333  *	@pfp: the unattached filter that is created
1334  *	@fprog: the filter program
1335  *
1336  * Create a filter independent of any socket. We first run some
1337  * sanity checks on it to make sure it does not explode on us later.
1338  * If an error occurs or there is insufficient memory for the filter
1339  * a negative errno code is returned. On success the return is zero.
1340  */
1341 int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1342 {
1343 	unsigned int fsize = bpf_classic_proglen(fprog);
1344 	struct bpf_prog *fp;
1345 
1346 	/* Make sure new filter is there and in the right amounts. */
1347 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1348 		return -EINVAL;
1349 
1350 	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1351 	if (!fp)
1352 		return -ENOMEM;
1353 
1354 	memcpy(fp->insns, fprog->filter, fsize);
1355 
1356 	fp->len = fprog->len;
1357 	/* Since unattached filters are not copied back to user
1358 	 * space through sk_get_filter(), we do not need to hold
1359 	 * a copy here, and can spare us the work.
1360 	 */
1361 	fp->orig_prog = NULL;
1362 
1363 	/* bpf_prepare_filter() already takes care of freeing
1364 	 * memory in case something goes wrong.
1365 	 */
1366 	fp = bpf_prepare_filter(fp, NULL);
1367 	if (IS_ERR(fp))
1368 		return PTR_ERR(fp);
1369 
1370 	*pfp = fp;
1371 	return 0;
1372 }
1373 EXPORT_SYMBOL_GPL(bpf_prog_create);
1374 
1375 /**
1376  *	bpf_prog_create_from_user - create an unattached filter from user buffer
1377  *	@pfp: the unattached filter that is created
1378  *	@fprog: the filter program
1379  *	@trans: post-classic verifier transformation handler
1380  *	@save_orig: save classic BPF program
1381  *
1382  * This function effectively does the same as bpf_prog_create(), only
1383  * that it builds up its insns buffer from user space provided buffer.
1384  * It also allows for passing a bpf_aux_classic_check_t handler.
1385  */
1386 int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1387 			      bpf_aux_classic_check_t trans, bool save_orig)
1388 {
1389 	unsigned int fsize = bpf_classic_proglen(fprog);
1390 	struct bpf_prog *fp;
1391 	int err;
1392 
1393 	/* Make sure new filter is there and in the right amounts. */
1394 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1395 		return -EINVAL;
1396 
1397 	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1398 	if (!fp)
1399 		return -ENOMEM;
1400 
1401 	if (copy_from_user(fp->insns, fprog->filter, fsize)) {
1402 		__bpf_prog_free(fp);
1403 		return -EFAULT;
1404 	}
1405 
1406 	fp->len = fprog->len;
1407 	fp->orig_prog = NULL;
1408 
1409 	if (save_orig) {
1410 		err = bpf_prog_store_orig_filter(fp, fprog);
1411 		if (err) {
1412 			__bpf_prog_free(fp);
1413 			return -ENOMEM;
1414 		}
1415 	}
1416 
1417 	/* bpf_prepare_filter() already takes care of freeing
1418 	 * memory in case something goes wrong.
1419 	 */
1420 	fp = bpf_prepare_filter(fp, trans);
1421 	if (IS_ERR(fp))
1422 		return PTR_ERR(fp);
1423 
1424 	*pfp = fp;
1425 	return 0;
1426 }
1427 EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1428 
1429 void bpf_prog_destroy(struct bpf_prog *fp)
1430 {
1431 	__bpf_prog_release(fp);
1432 }
1433 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1434 
1435 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1436 {
1437 	struct sk_filter *fp, *old_fp;
1438 
1439 	fp = kmalloc(sizeof(*fp), GFP_KERNEL);
1440 	if (!fp)
1441 		return -ENOMEM;
1442 
1443 	fp->prog = prog;
1444 
1445 	if (!__sk_filter_charge(sk, fp)) {
1446 		kfree(fp);
1447 		return -ENOMEM;
1448 	}
1449 	refcount_set(&fp->refcnt, 1);
1450 
1451 	old_fp = rcu_dereference_protected(sk->sk_filter,
1452 					   lockdep_sock_is_held(sk));
1453 	rcu_assign_pointer(sk->sk_filter, fp);
1454 
1455 	if (old_fp)
1456 		sk_filter_uncharge(sk, old_fp);
1457 
1458 	return 0;
1459 }
1460 
1461 static
1462 struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
1463 {
1464 	unsigned int fsize = bpf_classic_proglen(fprog);
1465 	struct bpf_prog *prog;
1466 	int err;
1467 
1468 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1469 		return ERR_PTR(-EPERM);
1470 
1471 	/* Make sure new filter is there and in the right amounts. */
1472 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1473 		return ERR_PTR(-EINVAL);
1474 
1475 	prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1476 	if (!prog)
1477 		return ERR_PTR(-ENOMEM);
1478 
1479 	if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1480 		__bpf_prog_free(prog);
1481 		return ERR_PTR(-EFAULT);
1482 	}
1483 
1484 	prog->len = fprog->len;
1485 
1486 	err = bpf_prog_store_orig_filter(prog, fprog);
1487 	if (err) {
1488 		__bpf_prog_free(prog);
1489 		return ERR_PTR(-ENOMEM);
1490 	}
1491 
1492 	/* bpf_prepare_filter() already takes care of freeing
1493 	 * memory in case something goes wrong.
1494 	 */
1495 	return bpf_prepare_filter(prog, NULL);
1496 }
1497 
1498 /**
1499  *	sk_attach_filter - attach a socket filter
1500  *	@fprog: the filter program
1501  *	@sk: the socket to use
1502  *
1503  * Attach the user's filter code. We first run some sanity checks on
1504  * it to make sure it does not explode on us later. If an error
1505  * occurs or there is insufficient memory for the filter a negative
1506  * errno code is returned. On success the return is zero.
1507  */
1508 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1509 {
1510 	struct bpf_prog *prog = __get_filter(fprog, sk);
1511 	int err;
1512 
1513 	if (IS_ERR(prog))
1514 		return PTR_ERR(prog);
1515 
1516 	err = __sk_attach_prog(prog, sk);
1517 	if (err < 0) {
1518 		__bpf_prog_release(prog);
1519 		return err;
1520 	}
1521 
1522 	return 0;
1523 }
1524 EXPORT_SYMBOL_GPL(sk_attach_filter);
1525 
1526 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1527 {
1528 	struct bpf_prog *prog = __get_filter(fprog, sk);
1529 	int err;
1530 
1531 	if (IS_ERR(prog))
1532 		return PTR_ERR(prog);
1533 
1534 	if (bpf_prog_size(prog->len) > sysctl_optmem_max)
1535 		err = -ENOMEM;
1536 	else
1537 		err = reuseport_attach_prog(sk, prog);
1538 
1539 	if (err)
1540 		__bpf_prog_release(prog);
1541 
1542 	return err;
1543 }
1544 
1545 static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
1546 {
1547 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1548 		return ERR_PTR(-EPERM);
1549 
1550 	return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1551 }
1552 
1553 int sk_attach_bpf(u32 ufd, struct sock *sk)
1554 {
1555 	struct bpf_prog *prog = __get_bpf(ufd, sk);
1556 	int err;
1557 
1558 	if (IS_ERR(prog))
1559 		return PTR_ERR(prog);
1560 
1561 	err = __sk_attach_prog(prog, sk);
1562 	if (err < 0) {
1563 		bpf_prog_put(prog);
1564 		return err;
1565 	}
1566 
1567 	return 0;
1568 }
1569 
1570 int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
1571 {
1572 	struct bpf_prog *prog;
1573 	int err;
1574 
1575 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1576 		return -EPERM;
1577 
1578 	prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1579 	if (IS_ERR(prog) && PTR_ERR(prog) == -EINVAL)
1580 		prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SK_REUSEPORT);
1581 	if (IS_ERR(prog))
1582 		return PTR_ERR(prog);
1583 
1584 	if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) {
1585 		/* Like other non BPF_PROG_TYPE_SOCKET_FILTER
1586 		 * bpf prog (e.g. sockmap).  It depends on the
1587 		 * limitation imposed by bpf_prog_load().
1588 		 * Hence, sysctl_optmem_max is not checked.
1589 		 */
1590 		if ((sk->sk_type != SOCK_STREAM &&
1591 		     sk->sk_type != SOCK_DGRAM) ||
1592 		    (sk->sk_protocol != IPPROTO_UDP &&
1593 		     sk->sk_protocol != IPPROTO_TCP) ||
1594 		    (sk->sk_family != AF_INET &&
1595 		     sk->sk_family != AF_INET6)) {
1596 			err = -ENOTSUPP;
1597 			goto err_prog_put;
1598 		}
1599 	} else {
1600 		/* BPF_PROG_TYPE_SOCKET_FILTER */
1601 		if (bpf_prog_size(prog->len) > sysctl_optmem_max) {
1602 			err = -ENOMEM;
1603 			goto err_prog_put;
1604 		}
1605 	}
1606 
1607 	err = reuseport_attach_prog(sk, prog);
1608 err_prog_put:
1609 	if (err)
1610 		bpf_prog_put(prog);
1611 
1612 	return err;
1613 }
1614 
1615 void sk_reuseport_prog_free(struct bpf_prog *prog)
1616 {
1617 	if (!prog)
1618 		return;
1619 
1620 	if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT)
1621 		bpf_prog_put(prog);
1622 	else
1623 		bpf_prog_destroy(prog);
1624 }
1625 
1626 struct bpf_scratchpad {
1627 	union {
1628 		__be32 diff[MAX_BPF_STACK / sizeof(__be32)];
1629 		u8     buff[MAX_BPF_STACK];
1630 	};
1631 };
1632 
1633 static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp);
1634 
1635 static inline int __bpf_try_make_writable(struct sk_buff *skb,
1636 					  unsigned int write_len)
1637 {
1638 	return skb_ensure_writable(skb, write_len);
1639 }
1640 
1641 static inline int bpf_try_make_writable(struct sk_buff *skb,
1642 					unsigned int write_len)
1643 {
1644 	int err = __bpf_try_make_writable(skb, write_len);
1645 
1646 	bpf_compute_data_pointers(skb);
1647 	return err;
1648 }
1649 
1650 static int bpf_try_make_head_writable(struct sk_buff *skb)
1651 {
1652 	return bpf_try_make_writable(skb, skb_headlen(skb));
1653 }
1654 
1655 static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
1656 {
1657 	if (skb_at_tc_ingress(skb))
1658 		skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1659 }
1660 
1661 static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
1662 {
1663 	if (skb_at_tc_ingress(skb))
1664 		skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1665 }
1666 
1667 BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
1668 	   const void *, from, u32, len, u64, flags)
1669 {
1670 	void *ptr;
1671 
1672 	if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1673 		return -EINVAL;
1674 	if (unlikely(offset > 0xffff))
1675 		return -EFAULT;
1676 	if (unlikely(bpf_try_make_writable(skb, offset + len)))
1677 		return -EFAULT;
1678 
1679 	ptr = skb->data + offset;
1680 	if (flags & BPF_F_RECOMPUTE_CSUM)
1681 		__skb_postpull_rcsum(skb, ptr, len, offset);
1682 
1683 	memcpy(ptr, from, len);
1684 
1685 	if (flags & BPF_F_RECOMPUTE_CSUM)
1686 		__skb_postpush_rcsum(skb, ptr, len, offset);
1687 	if (flags & BPF_F_INVALIDATE_HASH)
1688 		skb_clear_hash(skb);
1689 
1690 	return 0;
1691 }
1692 
1693 static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1694 	.func		= bpf_skb_store_bytes,
1695 	.gpl_only	= false,
1696 	.ret_type	= RET_INTEGER,
1697 	.arg1_type	= ARG_PTR_TO_CTX,
1698 	.arg2_type	= ARG_ANYTHING,
1699 	.arg3_type	= ARG_PTR_TO_MEM,
1700 	.arg4_type	= ARG_CONST_SIZE,
1701 	.arg5_type	= ARG_ANYTHING,
1702 };
1703 
1704 BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
1705 	   void *, to, u32, len)
1706 {
1707 	void *ptr;
1708 
1709 	if (unlikely(offset > 0xffff))
1710 		goto err_clear;
1711 
1712 	ptr = skb_header_pointer(skb, offset, len, to);
1713 	if (unlikely(!ptr))
1714 		goto err_clear;
1715 	if (ptr != to)
1716 		memcpy(to, ptr, len);
1717 
1718 	return 0;
1719 err_clear:
1720 	memset(to, 0, len);
1721 	return -EFAULT;
1722 }
1723 
1724 static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1725 	.func		= bpf_skb_load_bytes,
1726 	.gpl_only	= false,
1727 	.ret_type	= RET_INTEGER,
1728 	.arg1_type	= ARG_PTR_TO_CTX,
1729 	.arg2_type	= ARG_ANYTHING,
1730 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
1731 	.arg4_type	= ARG_CONST_SIZE,
1732 };
1733 
1734 BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb,
1735 	   u32, offset, void *, to, u32, len, u32, start_header)
1736 {
1737 	u8 *end = skb_tail_pointer(skb);
1738 	u8 *net = skb_network_header(skb);
1739 	u8 *mac = skb_mac_header(skb);
1740 	u8 *ptr;
1741 
1742 	if (unlikely(offset > 0xffff || len > (end - mac)))
1743 		goto err_clear;
1744 
1745 	switch (start_header) {
1746 	case BPF_HDR_START_MAC:
1747 		ptr = mac + offset;
1748 		break;
1749 	case BPF_HDR_START_NET:
1750 		ptr = net + offset;
1751 		break;
1752 	default:
1753 		goto err_clear;
1754 	}
1755 
1756 	if (likely(ptr >= mac && ptr + len <= end)) {
1757 		memcpy(to, ptr, len);
1758 		return 0;
1759 	}
1760 
1761 err_clear:
1762 	memset(to, 0, len);
1763 	return -EFAULT;
1764 }
1765 
1766 static const struct bpf_func_proto bpf_skb_load_bytes_relative_proto = {
1767 	.func		= bpf_skb_load_bytes_relative,
1768 	.gpl_only	= false,
1769 	.ret_type	= RET_INTEGER,
1770 	.arg1_type	= ARG_PTR_TO_CTX,
1771 	.arg2_type	= ARG_ANYTHING,
1772 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
1773 	.arg4_type	= ARG_CONST_SIZE,
1774 	.arg5_type	= ARG_ANYTHING,
1775 };
1776 
1777 BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
1778 {
1779 	/* Idea is the following: should the needed direct read/write
1780 	 * test fail during runtime, we can pull in more data and redo
1781 	 * again, since implicitly, we invalidate previous checks here.
1782 	 *
1783 	 * Or, since we know how much we need to make read/writeable,
1784 	 * this can be done once at the program beginning for direct
1785 	 * access case. By this we overcome limitations of only current
1786 	 * headroom being accessible.
1787 	 */
1788 	return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
1789 }
1790 
1791 static const struct bpf_func_proto bpf_skb_pull_data_proto = {
1792 	.func		= bpf_skb_pull_data,
1793 	.gpl_only	= false,
1794 	.ret_type	= RET_INTEGER,
1795 	.arg1_type	= ARG_PTR_TO_CTX,
1796 	.arg2_type	= ARG_ANYTHING,
1797 };
1798 
1799 static inline int sk_skb_try_make_writable(struct sk_buff *skb,
1800 					   unsigned int write_len)
1801 {
1802 	int err = __bpf_try_make_writable(skb, write_len);
1803 
1804 	bpf_compute_data_end_sk_skb(skb);
1805 	return err;
1806 }
1807 
1808 BPF_CALL_2(sk_skb_pull_data, struct sk_buff *, skb, u32, len)
1809 {
1810 	/* Idea is the following: should the needed direct read/write
1811 	 * test fail during runtime, we can pull in more data and redo
1812 	 * again, since implicitly, we invalidate previous checks here.
1813 	 *
1814 	 * Or, since we know how much we need to make read/writeable,
1815 	 * this can be done once at the program beginning for direct
1816 	 * access case. By this we overcome limitations of only current
1817 	 * headroom being accessible.
1818 	 */
1819 	return sk_skb_try_make_writable(skb, len ? : skb_headlen(skb));
1820 }
1821 
1822 static const struct bpf_func_proto sk_skb_pull_data_proto = {
1823 	.func		= sk_skb_pull_data,
1824 	.gpl_only	= false,
1825 	.ret_type	= RET_INTEGER,
1826 	.arg1_type	= ARG_PTR_TO_CTX,
1827 	.arg2_type	= ARG_ANYTHING,
1828 };
1829 
1830 BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
1831 	   u64, from, u64, to, u64, flags)
1832 {
1833 	__sum16 *ptr;
1834 
1835 	if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
1836 		return -EINVAL;
1837 	if (unlikely(offset > 0xffff || offset & 1))
1838 		return -EFAULT;
1839 	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1840 		return -EFAULT;
1841 
1842 	ptr = (__sum16 *)(skb->data + offset);
1843 	switch (flags & BPF_F_HDR_FIELD_MASK) {
1844 	case 0:
1845 		if (unlikely(from != 0))
1846 			return -EINVAL;
1847 
1848 		csum_replace_by_diff(ptr, to);
1849 		break;
1850 	case 2:
1851 		csum_replace2(ptr, from, to);
1852 		break;
1853 	case 4:
1854 		csum_replace4(ptr, from, to);
1855 		break;
1856 	default:
1857 		return -EINVAL;
1858 	}
1859 
1860 	return 0;
1861 }
1862 
1863 static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1864 	.func		= bpf_l3_csum_replace,
1865 	.gpl_only	= false,
1866 	.ret_type	= RET_INTEGER,
1867 	.arg1_type	= ARG_PTR_TO_CTX,
1868 	.arg2_type	= ARG_ANYTHING,
1869 	.arg3_type	= ARG_ANYTHING,
1870 	.arg4_type	= ARG_ANYTHING,
1871 	.arg5_type	= ARG_ANYTHING,
1872 };
1873 
1874 BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
1875 	   u64, from, u64, to, u64, flags)
1876 {
1877 	bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1878 	bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1879 	bool do_mforce = flags & BPF_F_MARK_ENFORCE;
1880 	__sum16 *ptr;
1881 
1882 	if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
1883 			       BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK)))
1884 		return -EINVAL;
1885 	if (unlikely(offset > 0xffff || offset & 1))
1886 		return -EFAULT;
1887 	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1888 		return -EFAULT;
1889 
1890 	ptr = (__sum16 *)(skb->data + offset);
1891 	if (is_mmzero && !do_mforce && !*ptr)
1892 		return 0;
1893 
1894 	switch (flags & BPF_F_HDR_FIELD_MASK) {
1895 	case 0:
1896 		if (unlikely(from != 0))
1897 			return -EINVAL;
1898 
1899 		inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
1900 		break;
1901 	case 2:
1902 		inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
1903 		break;
1904 	case 4:
1905 		inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
1906 		break;
1907 	default:
1908 		return -EINVAL;
1909 	}
1910 
1911 	if (is_mmzero && !*ptr)
1912 		*ptr = CSUM_MANGLED_0;
1913 	return 0;
1914 }
1915 
1916 static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1917 	.func		= bpf_l4_csum_replace,
1918 	.gpl_only	= false,
1919 	.ret_type	= RET_INTEGER,
1920 	.arg1_type	= ARG_PTR_TO_CTX,
1921 	.arg2_type	= ARG_ANYTHING,
1922 	.arg3_type	= ARG_ANYTHING,
1923 	.arg4_type	= ARG_ANYTHING,
1924 	.arg5_type	= ARG_ANYTHING,
1925 };
1926 
1927 BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
1928 	   __be32 *, to, u32, to_size, __wsum, seed)
1929 {
1930 	struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1931 	u32 diff_size = from_size + to_size;
1932 	int i, j = 0;
1933 
1934 	/* This is quite flexible, some examples:
1935 	 *
1936 	 * from_size == 0, to_size > 0,  seed := csum --> pushing data
1937 	 * from_size > 0,  to_size == 0, seed := csum --> pulling data
1938 	 * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
1939 	 *
1940 	 * Even for diffing, from_size and to_size don't need to be equal.
1941 	 */
1942 	if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) ||
1943 		     diff_size > sizeof(sp->diff)))
1944 		return -EINVAL;
1945 
1946 	for (i = 0; i < from_size / sizeof(__be32); i++, j++)
1947 		sp->diff[j] = ~from[i];
1948 	for (i = 0; i <   to_size / sizeof(__be32); i++, j++)
1949 		sp->diff[j] = to[i];
1950 
1951 	return csum_partial(sp->diff, diff_size, seed);
1952 }
1953 
1954 static const struct bpf_func_proto bpf_csum_diff_proto = {
1955 	.func		= bpf_csum_diff,
1956 	.gpl_only	= false,
1957 	.pkt_access	= true,
1958 	.ret_type	= RET_INTEGER,
1959 	.arg1_type	= ARG_PTR_TO_MEM_OR_NULL,
1960 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1961 	.arg3_type	= ARG_PTR_TO_MEM_OR_NULL,
1962 	.arg4_type	= ARG_CONST_SIZE_OR_ZERO,
1963 	.arg5_type	= ARG_ANYTHING,
1964 };
1965 
1966 BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
1967 {
1968 	/* The interface is to be used in combination with bpf_csum_diff()
1969 	 * for direct packet writes. csum rotation for alignment as well
1970 	 * as emulating csum_sub() can be done from the eBPF program.
1971 	 */
1972 	if (skb->ip_summed == CHECKSUM_COMPLETE)
1973 		return (skb->csum = csum_add(skb->csum, csum));
1974 
1975 	return -ENOTSUPP;
1976 }
1977 
1978 static const struct bpf_func_proto bpf_csum_update_proto = {
1979 	.func		= bpf_csum_update,
1980 	.gpl_only	= false,
1981 	.ret_type	= RET_INTEGER,
1982 	.arg1_type	= ARG_PTR_TO_CTX,
1983 	.arg2_type	= ARG_ANYTHING,
1984 };
1985 
1986 static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
1987 {
1988 	return dev_forward_skb(dev, skb);
1989 }
1990 
1991 static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
1992 				      struct sk_buff *skb)
1993 {
1994 	int ret = ____dev_forward_skb(dev, skb);
1995 
1996 	if (likely(!ret)) {
1997 		skb->dev = dev;
1998 		ret = netif_rx(skb);
1999 	}
2000 
2001 	return ret;
2002 }
2003 
2004 static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
2005 {
2006 	int ret;
2007 
2008 	if (unlikely(__this_cpu_read(xmit_recursion) > XMIT_RECURSION_LIMIT)) {
2009 		net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2010 		kfree_skb(skb);
2011 		return -ENETDOWN;
2012 	}
2013 
2014 	skb->dev = dev;
2015 
2016 	__this_cpu_inc(xmit_recursion);
2017 	ret = dev_queue_xmit(skb);
2018 	__this_cpu_dec(xmit_recursion);
2019 
2020 	return ret;
2021 }
2022 
2023 static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
2024 				 u32 flags)
2025 {
2026 	/* skb->mac_len is not set on normal egress */
2027 	unsigned int mlen = skb->network_header - skb->mac_header;
2028 
2029 	__skb_pull(skb, mlen);
2030 
2031 	/* At ingress, the mac header has already been pulled once.
2032 	 * At egress, skb_pospull_rcsum has to be done in case that
2033 	 * the skb is originated from ingress (i.e. a forwarded skb)
2034 	 * to ensure that rcsum starts at net header.
2035 	 */
2036 	if (!skb_at_tc_ingress(skb))
2037 		skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
2038 	skb_pop_mac_header(skb);
2039 	skb_reset_mac_len(skb);
2040 	return flags & BPF_F_INGRESS ?
2041 	       __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
2042 }
2043 
2044 static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
2045 				 u32 flags)
2046 {
2047 	/* Verify that a link layer header is carried */
2048 	if (unlikely(skb->mac_header >= skb->network_header)) {
2049 		kfree_skb(skb);
2050 		return -ERANGE;
2051 	}
2052 
2053 	bpf_push_mac_rcsum(skb);
2054 	return flags & BPF_F_INGRESS ?
2055 	       __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
2056 }
2057 
2058 static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
2059 			  u32 flags)
2060 {
2061 	if (dev_is_mac_header_xmit(dev))
2062 		return __bpf_redirect_common(skb, dev, flags);
2063 	else
2064 		return __bpf_redirect_no_mac(skb, dev, flags);
2065 }
2066 
2067 BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
2068 {
2069 	struct net_device *dev;
2070 	struct sk_buff *clone;
2071 	int ret;
2072 
2073 	if (unlikely(flags & ~(BPF_F_INGRESS)))
2074 		return -EINVAL;
2075 
2076 	dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
2077 	if (unlikely(!dev))
2078 		return -EINVAL;
2079 
2080 	clone = skb_clone(skb, GFP_ATOMIC);
2081 	if (unlikely(!clone))
2082 		return -ENOMEM;
2083 
2084 	/* For direct write, we need to keep the invariant that the skbs
2085 	 * we're dealing with need to be uncloned. Should uncloning fail
2086 	 * here, we need to free the just generated clone to unclone once
2087 	 * again.
2088 	 */
2089 	ret = bpf_try_make_head_writable(skb);
2090 	if (unlikely(ret)) {
2091 		kfree_skb(clone);
2092 		return -ENOMEM;
2093 	}
2094 
2095 	return __bpf_redirect(clone, dev, flags);
2096 }
2097 
2098 static const struct bpf_func_proto bpf_clone_redirect_proto = {
2099 	.func           = bpf_clone_redirect,
2100 	.gpl_only       = false,
2101 	.ret_type       = RET_INTEGER,
2102 	.arg1_type      = ARG_PTR_TO_CTX,
2103 	.arg2_type      = ARG_ANYTHING,
2104 	.arg3_type      = ARG_ANYTHING,
2105 };
2106 
2107 DEFINE_PER_CPU(struct bpf_redirect_info, bpf_redirect_info);
2108 EXPORT_PER_CPU_SYMBOL_GPL(bpf_redirect_info);
2109 
2110 BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
2111 {
2112 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2113 
2114 	if (unlikely(flags & ~(BPF_F_INGRESS)))
2115 		return TC_ACT_SHOT;
2116 
2117 	ri->ifindex = ifindex;
2118 	ri->flags = flags;
2119 
2120 	return TC_ACT_REDIRECT;
2121 }
2122 
2123 int skb_do_redirect(struct sk_buff *skb)
2124 {
2125 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2126 	struct net_device *dev;
2127 
2128 	dev = dev_get_by_index_rcu(dev_net(skb->dev), ri->ifindex);
2129 	ri->ifindex = 0;
2130 	if (unlikely(!dev)) {
2131 		kfree_skb(skb);
2132 		return -EINVAL;
2133 	}
2134 
2135 	return __bpf_redirect(skb, dev, ri->flags);
2136 }
2137 
2138 static const struct bpf_func_proto bpf_redirect_proto = {
2139 	.func           = bpf_redirect,
2140 	.gpl_only       = false,
2141 	.ret_type       = RET_INTEGER,
2142 	.arg1_type      = ARG_ANYTHING,
2143 	.arg2_type      = ARG_ANYTHING,
2144 };
2145 
2146 BPF_CALL_2(bpf_msg_apply_bytes, struct sk_msg *, msg, u32, bytes)
2147 {
2148 	msg->apply_bytes = bytes;
2149 	return 0;
2150 }
2151 
2152 static const struct bpf_func_proto bpf_msg_apply_bytes_proto = {
2153 	.func           = bpf_msg_apply_bytes,
2154 	.gpl_only       = false,
2155 	.ret_type       = RET_INTEGER,
2156 	.arg1_type	= ARG_PTR_TO_CTX,
2157 	.arg2_type      = ARG_ANYTHING,
2158 };
2159 
2160 BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg *, msg, u32, bytes)
2161 {
2162 	msg->cork_bytes = bytes;
2163 	return 0;
2164 }
2165 
2166 static const struct bpf_func_proto bpf_msg_cork_bytes_proto = {
2167 	.func           = bpf_msg_cork_bytes,
2168 	.gpl_only       = false,
2169 	.ret_type       = RET_INTEGER,
2170 	.arg1_type	= ARG_PTR_TO_CTX,
2171 	.arg2_type      = ARG_ANYTHING,
2172 };
2173 
2174 BPF_CALL_4(bpf_msg_pull_data, struct sk_msg *, msg, u32, start,
2175 	   u32, end, u64, flags)
2176 {
2177 	u32 len = 0, offset = 0, copy = 0, poffset = 0, bytes = end - start;
2178 	u32 first_sge, last_sge, i, shift, bytes_sg_total;
2179 	struct scatterlist *sge;
2180 	u8 *raw, *to, *from;
2181 	struct page *page;
2182 
2183 	if (unlikely(flags || end <= start))
2184 		return -EINVAL;
2185 
2186 	/* First find the starting scatterlist element */
2187 	i = msg->sg.start;
2188 	do {
2189 		len = sk_msg_elem(msg, i)->length;
2190 		if (start < offset + len)
2191 			break;
2192 		offset += len;
2193 		sk_msg_iter_var_next(i);
2194 	} while (i != msg->sg.end);
2195 
2196 	if (unlikely(start >= offset + len))
2197 		return -EINVAL;
2198 
2199 	first_sge = i;
2200 	/* The start may point into the sg element so we need to also
2201 	 * account for the headroom.
2202 	 */
2203 	bytes_sg_total = start - offset + bytes;
2204 	if (!msg->sg.copy[i] && bytes_sg_total <= len)
2205 		goto out;
2206 
2207 	/* At this point we need to linearize multiple scatterlist
2208 	 * elements or a single shared page. Either way we need to
2209 	 * copy into a linear buffer exclusively owned by BPF. Then
2210 	 * place the buffer in the scatterlist and fixup the original
2211 	 * entries by removing the entries now in the linear buffer
2212 	 * and shifting the remaining entries. For now we do not try
2213 	 * to copy partial entries to avoid complexity of running out
2214 	 * of sg_entry slots. The downside is reading a single byte
2215 	 * will copy the entire sg entry.
2216 	 */
2217 	do {
2218 		copy += sk_msg_elem(msg, i)->length;
2219 		sk_msg_iter_var_next(i);
2220 		if (bytes_sg_total <= copy)
2221 			break;
2222 	} while (i != msg->sg.end);
2223 	last_sge = i;
2224 
2225 	if (unlikely(bytes_sg_total > copy))
2226 		return -EINVAL;
2227 
2228 	page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2229 			   get_order(copy));
2230 	if (unlikely(!page))
2231 		return -ENOMEM;
2232 
2233 	raw = page_address(page);
2234 	i = first_sge;
2235 	do {
2236 		sge = sk_msg_elem(msg, i);
2237 		from = sg_virt(sge);
2238 		len = sge->length;
2239 		to = raw + poffset;
2240 
2241 		memcpy(to, from, len);
2242 		poffset += len;
2243 		sge->length = 0;
2244 		put_page(sg_page(sge));
2245 
2246 		sk_msg_iter_var_next(i);
2247 	} while (i != last_sge);
2248 
2249 	sg_set_page(&msg->sg.data[first_sge], page, copy, 0);
2250 
2251 	/* To repair sg ring we need to shift entries. If we only
2252 	 * had a single entry though we can just replace it and
2253 	 * be done. Otherwise walk the ring and shift the entries.
2254 	 */
2255 	WARN_ON_ONCE(last_sge == first_sge);
2256 	shift = last_sge > first_sge ?
2257 		last_sge - first_sge - 1 :
2258 		MAX_SKB_FRAGS - first_sge + last_sge - 1;
2259 	if (!shift)
2260 		goto out;
2261 
2262 	i = first_sge;
2263 	sk_msg_iter_var_next(i);
2264 	do {
2265 		u32 move_from;
2266 
2267 		if (i + shift >= MAX_MSG_FRAGS)
2268 			move_from = i + shift - MAX_MSG_FRAGS;
2269 		else
2270 			move_from = i + shift;
2271 		if (move_from == msg->sg.end)
2272 			break;
2273 
2274 		msg->sg.data[i] = msg->sg.data[move_from];
2275 		msg->sg.data[move_from].length = 0;
2276 		msg->sg.data[move_from].page_link = 0;
2277 		msg->sg.data[move_from].offset = 0;
2278 		sk_msg_iter_var_next(i);
2279 	} while (1);
2280 
2281 	msg->sg.end = msg->sg.end - shift > msg->sg.end ?
2282 		      msg->sg.end - shift + MAX_MSG_FRAGS :
2283 		      msg->sg.end - shift;
2284 out:
2285 	msg->data = sg_virt(&msg->sg.data[first_sge]) + start - offset;
2286 	msg->data_end = msg->data + bytes;
2287 	return 0;
2288 }
2289 
2290 static const struct bpf_func_proto bpf_msg_pull_data_proto = {
2291 	.func		= bpf_msg_pull_data,
2292 	.gpl_only	= false,
2293 	.ret_type	= RET_INTEGER,
2294 	.arg1_type	= ARG_PTR_TO_CTX,
2295 	.arg2_type	= ARG_ANYTHING,
2296 	.arg3_type	= ARG_ANYTHING,
2297 	.arg4_type	= ARG_ANYTHING,
2298 };
2299 
2300 BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start,
2301 	   u32, len, u64, flags)
2302 {
2303 	struct scatterlist sge, nsge, nnsge, rsge = {0}, *psge;
2304 	u32 new, i = 0, l, space, copy = 0, offset = 0;
2305 	u8 *raw, *to, *from;
2306 	struct page *page;
2307 
2308 	if (unlikely(flags))
2309 		return -EINVAL;
2310 
2311 	/* First find the starting scatterlist element */
2312 	i = msg->sg.start;
2313 	do {
2314 		l = sk_msg_elem(msg, i)->length;
2315 
2316 		if (start < offset + l)
2317 			break;
2318 		offset += l;
2319 		sk_msg_iter_var_next(i);
2320 	} while (i != msg->sg.end);
2321 
2322 	if (start >= offset + l)
2323 		return -EINVAL;
2324 
2325 	space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2326 
2327 	/* If no space available will fallback to copy, we need at
2328 	 * least one scatterlist elem available to push data into
2329 	 * when start aligns to the beginning of an element or two
2330 	 * when it falls inside an element. We handle the start equals
2331 	 * offset case because its the common case for inserting a
2332 	 * header.
2333 	 */
2334 	if (!space || (space == 1 && start != offset))
2335 		copy = msg->sg.data[i].length;
2336 
2337 	page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2338 			   get_order(copy + len));
2339 	if (unlikely(!page))
2340 		return -ENOMEM;
2341 
2342 	if (copy) {
2343 		int front, back;
2344 
2345 		raw = page_address(page);
2346 
2347 		psge = sk_msg_elem(msg, i);
2348 		front = start - offset;
2349 		back = psge->length - front;
2350 		from = sg_virt(psge);
2351 
2352 		if (front)
2353 			memcpy(raw, from, front);
2354 
2355 		if (back) {
2356 			from += front;
2357 			to = raw + front + len;
2358 
2359 			memcpy(to, from, back);
2360 		}
2361 
2362 		put_page(sg_page(psge));
2363 	} else if (start - offset) {
2364 		psge = sk_msg_elem(msg, i);
2365 		rsge = sk_msg_elem_cpy(msg, i);
2366 
2367 		psge->length = start - offset;
2368 		rsge.length -= psge->length;
2369 		rsge.offset += start;
2370 
2371 		sk_msg_iter_var_next(i);
2372 		sg_unmark_end(psge);
2373 		sk_msg_iter_next(msg, end);
2374 	}
2375 
2376 	/* Slot(s) to place newly allocated data */
2377 	new = i;
2378 
2379 	/* Shift one or two slots as needed */
2380 	if (!copy) {
2381 		sge = sk_msg_elem_cpy(msg, i);
2382 
2383 		sk_msg_iter_var_next(i);
2384 		sg_unmark_end(&sge);
2385 		sk_msg_iter_next(msg, end);
2386 
2387 		nsge = sk_msg_elem_cpy(msg, i);
2388 		if (rsge.length) {
2389 			sk_msg_iter_var_next(i);
2390 			nnsge = sk_msg_elem_cpy(msg, i);
2391 		}
2392 
2393 		while (i != msg->sg.end) {
2394 			msg->sg.data[i] = sge;
2395 			sge = nsge;
2396 			sk_msg_iter_var_next(i);
2397 			if (rsge.length) {
2398 				nsge = nnsge;
2399 				nnsge = sk_msg_elem_cpy(msg, i);
2400 			} else {
2401 				nsge = sk_msg_elem_cpy(msg, i);
2402 			}
2403 		}
2404 	}
2405 
2406 	/* Place newly allocated data buffer */
2407 	sk_mem_charge(msg->sk, len);
2408 	msg->sg.size += len;
2409 	msg->sg.copy[new] = false;
2410 	sg_set_page(&msg->sg.data[new], page, len + copy, 0);
2411 	if (rsge.length) {
2412 		get_page(sg_page(&rsge));
2413 		sk_msg_iter_var_next(new);
2414 		msg->sg.data[new] = rsge;
2415 	}
2416 
2417 	sk_msg_compute_data_pointers(msg);
2418 	return 0;
2419 }
2420 
2421 static const struct bpf_func_proto bpf_msg_push_data_proto = {
2422 	.func		= bpf_msg_push_data,
2423 	.gpl_only	= false,
2424 	.ret_type	= RET_INTEGER,
2425 	.arg1_type	= ARG_PTR_TO_CTX,
2426 	.arg2_type	= ARG_ANYTHING,
2427 	.arg3_type	= ARG_ANYTHING,
2428 	.arg4_type	= ARG_ANYTHING,
2429 };
2430 
2431 BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
2432 {
2433 	return task_get_classid(skb);
2434 }
2435 
2436 static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
2437 	.func           = bpf_get_cgroup_classid,
2438 	.gpl_only       = false,
2439 	.ret_type       = RET_INTEGER,
2440 	.arg1_type      = ARG_PTR_TO_CTX,
2441 };
2442 
2443 BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
2444 {
2445 	return dst_tclassid(skb);
2446 }
2447 
2448 static const struct bpf_func_proto bpf_get_route_realm_proto = {
2449 	.func           = bpf_get_route_realm,
2450 	.gpl_only       = false,
2451 	.ret_type       = RET_INTEGER,
2452 	.arg1_type      = ARG_PTR_TO_CTX,
2453 };
2454 
2455 BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
2456 {
2457 	/* If skb_clear_hash() was called due to mangling, we can
2458 	 * trigger SW recalculation here. Later access to hash
2459 	 * can then use the inline skb->hash via context directly
2460 	 * instead of calling this helper again.
2461 	 */
2462 	return skb_get_hash(skb);
2463 }
2464 
2465 static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
2466 	.func		= bpf_get_hash_recalc,
2467 	.gpl_only	= false,
2468 	.ret_type	= RET_INTEGER,
2469 	.arg1_type	= ARG_PTR_TO_CTX,
2470 };
2471 
2472 BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
2473 {
2474 	/* After all direct packet write, this can be used once for
2475 	 * triggering a lazy recalc on next skb_get_hash() invocation.
2476 	 */
2477 	skb_clear_hash(skb);
2478 	return 0;
2479 }
2480 
2481 static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
2482 	.func		= bpf_set_hash_invalid,
2483 	.gpl_only	= false,
2484 	.ret_type	= RET_INTEGER,
2485 	.arg1_type	= ARG_PTR_TO_CTX,
2486 };
2487 
2488 BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
2489 {
2490 	/* Set user specified hash as L4(+), so that it gets returned
2491 	 * on skb_get_hash() call unless BPF prog later on triggers a
2492 	 * skb_clear_hash().
2493 	 */
2494 	__skb_set_sw_hash(skb, hash, true);
2495 	return 0;
2496 }
2497 
2498 static const struct bpf_func_proto bpf_set_hash_proto = {
2499 	.func		= bpf_set_hash,
2500 	.gpl_only	= false,
2501 	.ret_type	= RET_INTEGER,
2502 	.arg1_type	= ARG_PTR_TO_CTX,
2503 	.arg2_type	= ARG_ANYTHING,
2504 };
2505 
2506 BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
2507 	   u16, vlan_tci)
2508 {
2509 	int ret;
2510 
2511 	if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
2512 		     vlan_proto != htons(ETH_P_8021AD)))
2513 		vlan_proto = htons(ETH_P_8021Q);
2514 
2515 	bpf_push_mac_rcsum(skb);
2516 	ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
2517 	bpf_pull_mac_rcsum(skb);
2518 
2519 	bpf_compute_data_pointers(skb);
2520 	return ret;
2521 }
2522 
2523 static const struct bpf_func_proto bpf_skb_vlan_push_proto = {
2524 	.func           = bpf_skb_vlan_push,
2525 	.gpl_only       = false,
2526 	.ret_type       = RET_INTEGER,
2527 	.arg1_type      = ARG_PTR_TO_CTX,
2528 	.arg2_type      = ARG_ANYTHING,
2529 	.arg3_type      = ARG_ANYTHING,
2530 };
2531 
2532 BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
2533 {
2534 	int ret;
2535 
2536 	bpf_push_mac_rcsum(skb);
2537 	ret = skb_vlan_pop(skb);
2538 	bpf_pull_mac_rcsum(skb);
2539 
2540 	bpf_compute_data_pointers(skb);
2541 	return ret;
2542 }
2543 
2544 static const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
2545 	.func           = bpf_skb_vlan_pop,
2546 	.gpl_only       = false,
2547 	.ret_type       = RET_INTEGER,
2548 	.arg1_type      = ARG_PTR_TO_CTX,
2549 };
2550 
2551 static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
2552 {
2553 	/* Caller already did skb_cow() with len as headroom,
2554 	 * so no need to do it here.
2555 	 */
2556 	skb_push(skb, len);
2557 	memmove(skb->data, skb->data + len, off);
2558 	memset(skb->data + off, 0, len);
2559 
2560 	/* No skb_postpush_rcsum(skb, skb->data + off, len)
2561 	 * needed here as it does not change the skb->csum
2562 	 * result for checksum complete when summing over
2563 	 * zeroed blocks.
2564 	 */
2565 	return 0;
2566 }
2567 
2568 static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
2569 {
2570 	/* skb_ensure_writable() is not needed here, as we're
2571 	 * already working on an uncloned skb.
2572 	 */
2573 	if (unlikely(!pskb_may_pull(skb, off + len)))
2574 		return -ENOMEM;
2575 
2576 	skb_postpull_rcsum(skb, skb->data + off, len);
2577 	memmove(skb->data + len, skb->data, off);
2578 	__skb_pull(skb, len);
2579 
2580 	return 0;
2581 }
2582 
2583 static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
2584 {
2585 	bool trans_same = skb->transport_header == skb->network_header;
2586 	int ret;
2587 
2588 	/* There's no need for __skb_push()/__skb_pull() pair to
2589 	 * get to the start of the mac header as we're guaranteed
2590 	 * to always start from here under eBPF.
2591 	 */
2592 	ret = bpf_skb_generic_push(skb, off, len);
2593 	if (likely(!ret)) {
2594 		skb->mac_header -= len;
2595 		skb->network_header -= len;
2596 		if (trans_same)
2597 			skb->transport_header = skb->network_header;
2598 	}
2599 
2600 	return ret;
2601 }
2602 
2603 static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
2604 {
2605 	bool trans_same = skb->transport_header == skb->network_header;
2606 	int ret;
2607 
2608 	/* Same here, __skb_push()/__skb_pull() pair not needed. */
2609 	ret = bpf_skb_generic_pop(skb, off, len);
2610 	if (likely(!ret)) {
2611 		skb->mac_header += len;
2612 		skb->network_header += len;
2613 		if (trans_same)
2614 			skb->transport_header = skb->network_header;
2615 	}
2616 
2617 	return ret;
2618 }
2619 
2620 static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
2621 {
2622 	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2623 	u32 off = skb_mac_header_len(skb);
2624 	int ret;
2625 
2626 	/* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
2627 	if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
2628 		return -ENOTSUPP;
2629 
2630 	ret = skb_cow(skb, len_diff);
2631 	if (unlikely(ret < 0))
2632 		return ret;
2633 
2634 	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
2635 	if (unlikely(ret < 0))
2636 		return ret;
2637 
2638 	if (skb_is_gso(skb)) {
2639 		struct skb_shared_info *shinfo = skb_shinfo(skb);
2640 
2641 		/* SKB_GSO_TCPV4 needs to be changed into
2642 		 * SKB_GSO_TCPV6.
2643 		 */
2644 		if (shinfo->gso_type & SKB_GSO_TCPV4) {
2645 			shinfo->gso_type &= ~SKB_GSO_TCPV4;
2646 			shinfo->gso_type |=  SKB_GSO_TCPV6;
2647 		}
2648 
2649 		/* Due to IPv6 header, MSS needs to be downgraded. */
2650 		skb_decrease_gso_size(shinfo, len_diff);
2651 		/* Header must be checked, and gso_segs recomputed. */
2652 		shinfo->gso_type |= SKB_GSO_DODGY;
2653 		shinfo->gso_segs = 0;
2654 	}
2655 
2656 	skb->protocol = htons(ETH_P_IPV6);
2657 	skb_clear_hash(skb);
2658 
2659 	return 0;
2660 }
2661 
2662 static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
2663 {
2664 	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2665 	u32 off = skb_mac_header_len(skb);
2666 	int ret;
2667 
2668 	/* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
2669 	if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
2670 		return -ENOTSUPP;
2671 
2672 	ret = skb_unclone(skb, GFP_ATOMIC);
2673 	if (unlikely(ret < 0))
2674 		return ret;
2675 
2676 	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
2677 	if (unlikely(ret < 0))
2678 		return ret;
2679 
2680 	if (skb_is_gso(skb)) {
2681 		struct skb_shared_info *shinfo = skb_shinfo(skb);
2682 
2683 		/* SKB_GSO_TCPV6 needs to be changed into
2684 		 * SKB_GSO_TCPV4.
2685 		 */
2686 		if (shinfo->gso_type & SKB_GSO_TCPV6) {
2687 			shinfo->gso_type &= ~SKB_GSO_TCPV6;
2688 			shinfo->gso_type |=  SKB_GSO_TCPV4;
2689 		}
2690 
2691 		/* Due to IPv4 header, MSS can be upgraded. */
2692 		skb_increase_gso_size(shinfo, len_diff);
2693 		/* Header must be checked, and gso_segs recomputed. */
2694 		shinfo->gso_type |= SKB_GSO_DODGY;
2695 		shinfo->gso_segs = 0;
2696 	}
2697 
2698 	skb->protocol = htons(ETH_P_IP);
2699 	skb_clear_hash(skb);
2700 
2701 	return 0;
2702 }
2703 
2704 static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
2705 {
2706 	__be16 from_proto = skb->protocol;
2707 
2708 	if (from_proto == htons(ETH_P_IP) &&
2709 	      to_proto == htons(ETH_P_IPV6))
2710 		return bpf_skb_proto_4_to_6(skb);
2711 
2712 	if (from_proto == htons(ETH_P_IPV6) &&
2713 	      to_proto == htons(ETH_P_IP))
2714 		return bpf_skb_proto_6_to_4(skb);
2715 
2716 	return -ENOTSUPP;
2717 }
2718 
2719 BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
2720 	   u64, flags)
2721 {
2722 	int ret;
2723 
2724 	if (unlikely(flags))
2725 		return -EINVAL;
2726 
2727 	/* General idea is that this helper does the basic groundwork
2728 	 * needed for changing the protocol, and eBPF program fills the
2729 	 * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
2730 	 * and other helpers, rather than passing a raw buffer here.
2731 	 *
2732 	 * The rationale is to keep this minimal and without a need to
2733 	 * deal with raw packet data. F.e. even if we would pass buffers
2734 	 * here, the program still needs to call the bpf_lX_csum_replace()
2735 	 * helpers anyway. Plus, this way we keep also separation of
2736 	 * concerns, since f.e. bpf_skb_store_bytes() should only take
2737 	 * care of stores.
2738 	 *
2739 	 * Currently, additional options and extension header space are
2740 	 * not supported, but flags register is reserved so we can adapt
2741 	 * that. For offloads, we mark packet as dodgy, so that headers
2742 	 * need to be verified first.
2743 	 */
2744 	ret = bpf_skb_proto_xlat(skb, proto);
2745 	bpf_compute_data_pointers(skb);
2746 	return ret;
2747 }
2748 
2749 static const struct bpf_func_proto bpf_skb_change_proto_proto = {
2750 	.func		= bpf_skb_change_proto,
2751 	.gpl_only	= false,
2752 	.ret_type	= RET_INTEGER,
2753 	.arg1_type	= ARG_PTR_TO_CTX,
2754 	.arg2_type	= ARG_ANYTHING,
2755 	.arg3_type	= ARG_ANYTHING,
2756 };
2757 
2758 BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
2759 {
2760 	/* We only allow a restricted subset to be changed for now. */
2761 	if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
2762 		     !skb_pkt_type_ok(pkt_type)))
2763 		return -EINVAL;
2764 
2765 	skb->pkt_type = pkt_type;
2766 	return 0;
2767 }
2768 
2769 static const struct bpf_func_proto bpf_skb_change_type_proto = {
2770 	.func		= bpf_skb_change_type,
2771 	.gpl_only	= false,
2772 	.ret_type	= RET_INTEGER,
2773 	.arg1_type	= ARG_PTR_TO_CTX,
2774 	.arg2_type	= ARG_ANYTHING,
2775 };
2776 
2777 static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
2778 {
2779 	switch (skb->protocol) {
2780 	case htons(ETH_P_IP):
2781 		return sizeof(struct iphdr);
2782 	case htons(ETH_P_IPV6):
2783 		return sizeof(struct ipv6hdr);
2784 	default:
2785 		return ~0U;
2786 	}
2787 }
2788 
2789 static int bpf_skb_net_grow(struct sk_buff *skb, u32 len_diff)
2790 {
2791 	u32 off = skb_mac_header_len(skb) + bpf_skb_net_base_len(skb);
2792 	int ret;
2793 
2794 	/* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
2795 	if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
2796 		return -ENOTSUPP;
2797 
2798 	ret = skb_cow(skb, len_diff);
2799 	if (unlikely(ret < 0))
2800 		return ret;
2801 
2802 	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
2803 	if (unlikely(ret < 0))
2804 		return ret;
2805 
2806 	if (skb_is_gso(skb)) {
2807 		struct skb_shared_info *shinfo = skb_shinfo(skb);
2808 
2809 		/* Due to header grow, MSS needs to be downgraded. */
2810 		skb_decrease_gso_size(shinfo, len_diff);
2811 		/* Header must be checked, and gso_segs recomputed. */
2812 		shinfo->gso_type |= SKB_GSO_DODGY;
2813 		shinfo->gso_segs = 0;
2814 	}
2815 
2816 	return 0;
2817 }
2818 
2819 static int bpf_skb_net_shrink(struct sk_buff *skb, u32 len_diff)
2820 {
2821 	u32 off = skb_mac_header_len(skb) + bpf_skb_net_base_len(skb);
2822 	int ret;
2823 
2824 	/* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
2825 	if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
2826 		return -ENOTSUPP;
2827 
2828 	ret = skb_unclone(skb, GFP_ATOMIC);
2829 	if (unlikely(ret < 0))
2830 		return ret;
2831 
2832 	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
2833 	if (unlikely(ret < 0))
2834 		return ret;
2835 
2836 	if (skb_is_gso(skb)) {
2837 		struct skb_shared_info *shinfo = skb_shinfo(skb);
2838 
2839 		/* Due to header shrink, MSS can be upgraded. */
2840 		skb_increase_gso_size(shinfo, len_diff);
2841 		/* Header must be checked, and gso_segs recomputed. */
2842 		shinfo->gso_type |= SKB_GSO_DODGY;
2843 		shinfo->gso_segs = 0;
2844 	}
2845 
2846 	return 0;
2847 }
2848 
2849 static u32 __bpf_skb_max_len(const struct sk_buff *skb)
2850 {
2851 	return skb->dev ? skb->dev->mtu + skb->dev->hard_header_len :
2852 			  SKB_MAX_ALLOC;
2853 }
2854 
2855 static int bpf_skb_adjust_net(struct sk_buff *skb, s32 len_diff)
2856 {
2857 	bool trans_same = skb->transport_header == skb->network_header;
2858 	u32 len_cur, len_diff_abs = abs(len_diff);
2859 	u32 len_min = bpf_skb_net_base_len(skb);
2860 	u32 len_max = __bpf_skb_max_len(skb);
2861 	__be16 proto = skb->protocol;
2862 	bool shrink = len_diff < 0;
2863 	int ret;
2864 
2865 	if (unlikely(len_diff_abs > 0xfffU))
2866 		return -EFAULT;
2867 	if (unlikely(proto != htons(ETH_P_IP) &&
2868 		     proto != htons(ETH_P_IPV6)))
2869 		return -ENOTSUPP;
2870 
2871 	len_cur = skb->len - skb_network_offset(skb);
2872 	if (skb_transport_header_was_set(skb) && !trans_same)
2873 		len_cur = skb_network_header_len(skb);
2874 	if ((shrink && (len_diff_abs >= len_cur ||
2875 			len_cur - len_diff_abs < len_min)) ||
2876 	    (!shrink && (skb->len + len_diff_abs > len_max &&
2877 			 !skb_is_gso(skb))))
2878 		return -ENOTSUPP;
2879 
2880 	ret = shrink ? bpf_skb_net_shrink(skb, len_diff_abs) :
2881 		       bpf_skb_net_grow(skb, len_diff_abs);
2882 
2883 	bpf_compute_data_pointers(skb);
2884 	return ret;
2885 }
2886 
2887 BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
2888 	   u32, mode, u64, flags)
2889 {
2890 	if (unlikely(flags))
2891 		return -EINVAL;
2892 	if (likely(mode == BPF_ADJ_ROOM_NET))
2893 		return bpf_skb_adjust_net(skb, len_diff);
2894 
2895 	return -ENOTSUPP;
2896 }
2897 
2898 static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
2899 	.func		= bpf_skb_adjust_room,
2900 	.gpl_only	= false,
2901 	.ret_type	= RET_INTEGER,
2902 	.arg1_type	= ARG_PTR_TO_CTX,
2903 	.arg2_type	= ARG_ANYTHING,
2904 	.arg3_type	= ARG_ANYTHING,
2905 	.arg4_type	= ARG_ANYTHING,
2906 };
2907 
2908 static u32 __bpf_skb_min_len(const struct sk_buff *skb)
2909 {
2910 	u32 min_len = skb_network_offset(skb);
2911 
2912 	if (skb_transport_header_was_set(skb))
2913 		min_len = skb_transport_offset(skb);
2914 	if (skb->ip_summed == CHECKSUM_PARTIAL)
2915 		min_len = skb_checksum_start_offset(skb) +
2916 			  skb->csum_offset + sizeof(__sum16);
2917 	return min_len;
2918 }
2919 
2920 static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
2921 {
2922 	unsigned int old_len = skb->len;
2923 	int ret;
2924 
2925 	ret = __skb_grow_rcsum(skb, new_len);
2926 	if (!ret)
2927 		memset(skb->data + old_len, 0, new_len - old_len);
2928 	return ret;
2929 }
2930 
2931 static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
2932 {
2933 	return __skb_trim_rcsum(skb, new_len);
2934 }
2935 
2936 static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len,
2937 					u64 flags)
2938 {
2939 	u32 max_len = __bpf_skb_max_len(skb);
2940 	u32 min_len = __bpf_skb_min_len(skb);
2941 	int ret;
2942 
2943 	if (unlikely(flags || new_len > max_len || new_len < min_len))
2944 		return -EINVAL;
2945 	if (skb->encapsulation)
2946 		return -ENOTSUPP;
2947 
2948 	/* The basic idea of this helper is that it's performing the
2949 	 * needed work to either grow or trim an skb, and eBPF program
2950 	 * rewrites the rest via helpers like bpf_skb_store_bytes(),
2951 	 * bpf_lX_csum_replace() and others rather than passing a raw
2952 	 * buffer here. This one is a slow path helper and intended
2953 	 * for replies with control messages.
2954 	 *
2955 	 * Like in bpf_skb_change_proto(), we want to keep this rather
2956 	 * minimal and without protocol specifics so that we are able
2957 	 * to separate concerns as in bpf_skb_store_bytes() should only
2958 	 * be the one responsible for writing buffers.
2959 	 *
2960 	 * It's really expected to be a slow path operation here for
2961 	 * control message replies, so we're implicitly linearizing,
2962 	 * uncloning and drop offloads from the skb by this.
2963 	 */
2964 	ret = __bpf_try_make_writable(skb, skb->len);
2965 	if (!ret) {
2966 		if (new_len > skb->len)
2967 			ret = bpf_skb_grow_rcsum(skb, new_len);
2968 		else if (new_len < skb->len)
2969 			ret = bpf_skb_trim_rcsum(skb, new_len);
2970 		if (!ret && skb_is_gso(skb))
2971 			skb_gso_reset(skb);
2972 	}
2973 	return ret;
2974 }
2975 
2976 BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
2977 	   u64, flags)
2978 {
2979 	int ret = __bpf_skb_change_tail(skb, new_len, flags);
2980 
2981 	bpf_compute_data_pointers(skb);
2982 	return ret;
2983 }
2984 
2985 static const struct bpf_func_proto bpf_skb_change_tail_proto = {
2986 	.func		= bpf_skb_change_tail,
2987 	.gpl_only	= false,
2988 	.ret_type	= RET_INTEGER,
2989 	.arg1_type	= ARG_PTR_TO_CTX,
2990 	.arg2_type	= ARG_ANYTHING,
2991 	.arg3_type	= ARG_ANYTHING,
2992 };
2993 
2994 BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len,
2995 	   u64, flags)
2996 {
2997 	int ret = __bpf_skb_change_tail(skb, new_len, flags);
2998 
2999 	bpf_compute_data_end_sk_skb(skb);
3000 	return ret;
3001 }
3002 
3003 static const struct bpf_func_proto sk_skb_change_tail_proto = {
3004 	.func		= sk_skb_change_tail,
3005 	.gpl_only	= false,
3006 	.ret_type	= RET_INTEGER,
3007 	.arg1_type	= ARG_PTR_TO_CTX,
3008 	.arg2_type	= ARG_ANYTHING,
3009 	.arg3_type	= ARG_ANYTHING,
3010 };
3011 
3012 static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room,
3013 					u64 flags)
3014 {
3015 	u32 max_len = __bpf_skb_max_len(skb);
3016 	u32 new_len = skb->len + head_room;
3017 	int ret;
3018 
3019 	if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
3020 		     new_len < skb->len))
3021 		return -EINVAL;
3022 
3023 	ret = skb_cow(skb, head_room);
3024 	if (likely(!ret)) {
3025 		/* Idea for this helper is that we currently only
3026 		 * allow to expand on mac header. This means that
3027 		 * skb->protocol network header, etc, stay as is.
3028 		 * Compared to bpf_skb_change_tail(), we're more
3029 		 * flexible due to not needing to linearize or
3030 		 * reset GSO. Intention for this helper is to be
3031 		 * used by an L3 skb that needs to push mac header
3032 		 * for redirection into L2 device.
3033 		 */
3034 		__skb_push(skb, head_room);
3035 		memset(skb->data, 0, head_room);
3036 		skb_reset_mac_header(skb);
3037 	}
3038 
3039 	return ret;
3040 }
3041 
3042 BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
3043 	   u64, flags)
3044 {
3045 	int ret = __bpf_skb_change_head(skb, head_room, flags);
3046 
3047 	bpf_compute_data_pointers(skb);
3048 	return ret;
3049 }
3050 
3051 static const struct bpf_func_proto bpf_skb_change_head_proto = {
3052 	.func		= bpf_skb_change_head,
3053 	.gpl_only	= false,
3054 	.ret_type	= RET_INTEGER,
3055 	.arg1_type	= ARG_PTR_TO_CTX,
3056 	.arg2_type	= ARG_ANYTHING,
3057 	.arg3_type	= ARG_ANYTHING,
3058 };
3059 
3060 BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room,
3061 	   u64, flags)
3062 {
3063 	int ret = __bpf_skb_change_head(skb, head_room, flags);
3064 
3065 	bpf_compute_data_end_sk_skb(skb);
3066 	return ret;
3067 }
3068 
3069 static const struct bpf_func_proto sk_skb_change_head_proto = {
3070 	.func		= sk_skb_change_head,
3071 	.gpl_only	= false,
3072 	.ret_type	= RET_INTEGER,
3073 	.arg1_type	= ARG_PTR_TO_CTX,
3074 	.arg2_type	= ARG_ANYTHING,
3075 	.arg3_type	= ARG_ANYTHING,
3076 };
3077 static unsigned long xdp_get_metalen(const struct xdp_buff *xdp)
3078 {
3079 	return xdp_data_meta_unsupported(xdp) ? 0 :
3080 	       xdp->data - xdp->data_meta;
3081 }
3082 
3083 BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
3084 {
3085 	void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3086 	unsigned long metalen = xdp_get_metalen(xdp);
3087 	void *data_start = xdp_frame_end + metalen;
3088 	void *data = xdp->data + offset;
3089 
3090 	if (unlikely(data < data_start ||
3091 		     data > xdp->data_end - ETH_HLEN))
3092 		return -EINVAL;
3093 
3094 	if (metalen)
3095 		memmove(xdp->data_meta + offset,
3096 			xdp->data_meta, metalen);
3097 	xdp->data_meta += offset;
3098 	xdp->data = data;
3099 
3100 	return 0;
3101 }
3102 
3103 static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
3104 	.func		= bpf_xdp_adjust_head,
3105 	.gpl_only	= false,
3106 	.ret_type	= RET_INTEGER,
3107 	.arg1_type	= ARG_PTR_TO_CTX,
3108 	.arg2_type	= ARG_ANYTHING,
3109 };
3110 
3111 BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
3112 {
3113 	void *data_end = xdp->data_end + offset;
3114 
3115 	/* only shrinking is allowed for now. */
3116 	if (unlikely(offset >= 0))
3117 		return -EINVAL;
3118 
3119 	if (unlikely(data_end < xdp->data + ETH_HLEN))
3120 		return -EINVAL;
3121 
3122 	xdp->data_end = data_end;
3123 
3124 	return 0;
3125 }
3126 
3127 static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
3128 	.func		= bpf_xdp_adjust_tail,
3129 	.gpl_only	= false,
3130 	.ret_type	= RET_INTEGER,
3131 	.arg1_type	= ARG_PTR_TO_CTX,
3132 	.arg2_type	= ARG_ANYTHING,
3133 };
3134 
3135 BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
3136 {
3137 	void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3138 	void *meta = xdp->data_meta + offset;
3139 	unsigned long metalen = xdp->data - meta;
3140 
3141 	if (xdp_data_meta_unsupported(xdp))
3142 		return -ENOTSUPP;
3143 	if (unlikely(meta < xdp_frame_end ||
3144 		     meta > xdp->data))
3145 		return -EINVAL;
3146 	if (unlikely((metalen & (sizeof(__u32) - 1)) ||
3147 		     (metalen > 32)))
3148 		return -EACCES;
3149 
3150 	xdp->data_meta = meta;
3151 
3152 	return 0;
3153 }
3154 
3155 static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
3156 	.func		= bpf_xdp_adjust_meta,
3157 	.gpl_only	= false,
3158 	.ret_type	= RET_INTEGER,
3159 	.arg1_type	= ARG_PTR_TO_CTX,
3160 	.arg2_type	= ARG_ANYTHING,
3161 };
3162 
3163 static int __bpf_tx_xdp(struct net_device *dev,
3164 			struct bpf_map *map,
3165 			struct xdp_buff *xdp,
3166 			u32 index)
3167 {
3168 	struct xdp_frame *xdpf;
3169 	int err, sent;
3170 
3171 	if (!dev->netdev_ops->ndo_xdp_xmit) {
3172 		return -EOPNOTSUPP;
3173 	}
3174 
3175 	err = xdp_ok_fwd_dev(dev, xdp->data_end - xdp->data);
3176 	if (unlikely(err))
3177 		return err;
3178 
3179 	xdpf = convert_to_xdp_frame(xdp);
3180 	if (unlikely(!xdpf))
3181 		return -EOVERFLOW;
3182 
3183 	sent = dev->netdev_ops->ndo_xdp_xmit(dev, 1, &xdpf, XDP_XMIT_FLUSH);
3184 	if (sent <= 0)
3185 		return sent;
3186 	return 0;
3187 }
3188 
3189 static noinline int
3190 xdp_do_redirect_slow(struct net_device *dev, struct xdp_buff *xdp,
3191 		     struct bpf_prog *xdp_prog, struct bpf_redirect_info *ri)
3192 {
3193 	struct net_device *fwd;
3194 	u32 index = ri->ifindex;
3195 	int err;
3196 
3197 	fwd = dev_get_by_index_rcu(dev_net(dev), index);
3198 	ri->ifindex = 0;
3199 	if (unlikely(!fwd)) {
3200 		err = -EINVAL;
3201 		goto err;
3202 	}
3203 
3204 	err = __bpf_tx_xdp(fwd, NULL, xdp, 0);
3205 	if (unlikely(err))
3206 		goto err;
3207 
3208 	_trace_xdp_redirect(dev, xdp_prog, index);
3209 	return 0;
3210 err:
3211 	_trace_xdp_redirect_err(dev, xdp_prog, index, err);
3212 	return err;
3213 }
3214 
3215 static int __bpf_tx_xdp_map(struct net_device *dev_rx, void *fwd,
3216 			    struct bpf_map *map,
3217 			    struct xdp_buff *xdp,
3218 			    u32 index)
3219 {
3220 	int err;
3221 
3222 	switch (map->map_type) {
3223 	case BPF_MAP_TYPE_DEVMAP: {
3224 		struct bpf_dtab_netdev *dst = fwd;
3225 
3226 		err = dev_map_enqueue(dst, xdp, dev_rx);
3227 		if (unlikely(err))
3228 			return err;
3229 		__dev_map_insert_ctx(map, index);
3230 		break;
3231 	}
3232 	case BPF_MAP_TYPE_CPUMAP: {
3233 		struct bpf_cpu_map_entry *rcpu = fwd;
3234 
3235 		err = cpu_map_enqueue(rcpu, xdp, dev_rx);
3236 		if (unlikely(err))
3237 			return err;
3238 		__cpu_map_insert_ctx(map, index);
3239 		break;
3240 	}
3241 	case BPF_MAP_TYPE_XSKMAP: {
3242 		struct xdp_sock *xs = fwd;
3243 
3244 		err = __xsk_map_redirect(map, xdp, xs);
3245 		return err;
3246 	}
3247 	default:
3248 		break;
3249 	}
3250 	return 0;
3251 }
3252 
3253 void xdp_do_flush_map(void)
3254 {
3255 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3256 	struct bpf_map *map = ri->map_to_flush;
3257 
3258 	ri->map_to_flush = NULL;
3259 	if (map) {
3260 		switch (map->map_type) {
3261 		case BPF_MAP_TYPE_DEVMAP:
3262 			__dev_map_flush(map);
3263 			break;
3264 		case BPF_MAP_TYPE_CPUMAP:
3265 			__cpu_map_flush(map);
3266 			break;
3267 		case BPF_MAP_TYPE_XSKMAP:
3268 			__xsk_map_flush(map);
3269 			break;
3270 		default:
3271 			break;
3272 		}
3273 	}
3274 }
3275 EXPORT_SYMBOL_GPL(xdp_do_flush_map);
3276 
3277 static inline void *__xdp_map_lookup_elem(struct bpf_map *map, u32 index)
3278 {
3279 	switch (map->map_type) {
3280 	case BPF_MAP_TYPE_DEVMAP:
3281 		return __dev_map_lookup_elem(map, index);
3282 	case BPF_MAP_TYPE_CPUMAP:
3283 		return __cpu_map_lookup_elem(map, index);
3284 	case BPF_MAP_TYPE_XSKMAP:
3285 		return __xsk_map_lookup_elem(map, index);
3286 	default:
3287 		return NULL;
3288 	}
3289 }
3290 
3291 void bpf_clear_redirect_map(struct bpf_map *map)
3292 {
3293 	struct bpf_redirect_info *ri;
3294 	int cpu;
3295 
3296 	for_each_possible_cpu(cpu) {
3297 		ri = per_cpu_ptr(&bpf_redirect_info, cpu);
3298 		/* Avoid polluting remote cacheline due to writes if
3299 		 * not needed. Once we pass this test, we need the
3300 		 * cmpxchg() to make sure it hasn't been changed in
3301 		 * the meantime by remote CPU.
3302 		 */
3303 		if (unlikely(READ_ONCE(ri->map) == map))
3304 			cmpxchg(&ri->map, map, NULL);
3305 	}
3306 }
3307 
3308 static int xdp_do_redirect_map(struct net_device *dev, struct xdp_buff *xdp,
3309 			       struct bpf_prog *xdp_prog, struct bpf_map *map,
3310 			       struct bpf_redirect_info *ri)
3311 {
3312 	u32 index = ri->ifindex;
3313 	void *fwd = NULL;
3314 	int err;
3315 
3316 	ri->ifindex = 0;
3317 	WRITE_ONCE(ri->map, NULL);
3318 
3319 	fwd = __xdp_map_lookup_elem(map, index);
3320 	if (unlikely(!fwd)) {
3321 		err = -EINVAL;
3322 		goto err;
3323 	}
3324 	if (ri->map_to_flush && unlikely(ri->map_to_flush != map))
3325 		xdp_do_flush_map();
3326 
3327 	err = __bpf_tx_xdp_map(dev, fwd, map, xdp, index);
3328 	if (unlikely(err))
3329 		goto err;
3330 
3331 	ri->map_to_flush = map;
3332 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3333 	return 0;
3334 err:
3335 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3336 	return err;
3337 }
3338 
3339 int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
3340 		    struct bpf_prog *xdp_prog)
3341 {
3342 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3343 	struct bpf_map *map = READ_ONCE(ri->map);
3344 
3345 	if (likely(map))
3346 		return xdp_do_redirect_map(dev, xdp, xdp_prog, map, ri);
3347 
3348 	return xdp_do_redirect_slow(dev, xdp, xdp_prog, ri);
3349 }
3350 EXPORT_SYMBOL_GPL(xdp_do_redirect);
3351 
3352 static int xdp_do_generic_redirect_map(struct net_device *dev,
3353 				       struct sk_buff *skb,
3354 				       struct xdp_buff *xdp,
3355 				       struct bpf_prog *xdp_prog,
3356 				       struct bpf_map *map)
3357 {
3358 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3359 	u32 index = ri->ifindex;
3360 	void *fwd = NULL;
3361 	int err = 0;
3362 
3363 	ri->ifindex = 0;
3364 	WRITE_ONCE(ri->map, NULL);
3365 
3366 	fwd = __xdp_map_lookup_elem(map, index);
3367 	if (unlikely(!fwd)) {
3368 		err = -EINVAL;
3369 		goto err;
3370 	}
3371 
3372 	if (map->map_type == BPF_MAP_TYPE_DEVMAP) {
3373 		struct bpf_dtab_netdev *dst = fwd;
3374 
3375 		err = dev_map_generic_redirect(dst, skb, xdp_prog);
3376 		if (unlikely(err))
3377 			goto err;
3378 	} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
3379 		struct xdp_sock *xs = fwd;
3380 
3381 		err = xsk_generic_rcv(xs, xdp);
3382 		if (err)
3383 			goto err;
3384 		consume_skb(skb);
3385 	} else {
3386 		/* TODO: Handle BPF_MAP_TYPE_CPUMAP */
3387 		err = -EBADRQC;
3388 		goto err;
3389 	}
3390 
3391 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3392 	return 0;
3393 err:
3394 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3395 	return err;
3396 }
3397 
3398 int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
3399 			    struct xdp_buff *xdp, struct bpf_prog *xdp_prog)
3400 {
3401 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3402 	struct bpf_map *map = READ_ONCE(ri->map);
3403 	u32 index = ri->ifindex;
3404 	struct net_device *fwd;
3405 	int err = 0;
3406 
3407 	if (map)
3408 		return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog,
3409 						   map);
3410 	ri->ifindex = 0;
3411 	fwd = dev_get_by_index_rcu(dev_net(dev), index);
3412 	if (unlikely(!fwd)) {
3413 		err = -EINVAL;
3414 		goto err;
3415 	}
3416 
3417 	err = xdp_ok_fwd_dev(fwd, skb->len);
3418 	if (unlikely(err))
3419 		goto err;
3420 
3421 	skb->dev = fwd;
3422 	_trace_xdp_redirect(dev, xdp_prog, index);
3423 	generic_xdp_tx(skb, xdp_prog);
3424 	return 0;
3425 err:
3426 	_trace_xdp_redirect_err(dev, xdp_prog, index, err);
3427 	return err;
3428 }
3429 EXPORT_SYMBOL_GPL(xdp_do_generic_redirect);
3430 
3431 BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
3432 {
3433 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3434 
3435 	if (unlikely(flags))
3436 		return XDP_ABORTED;
3437 
3438 	ri->ifindex = ifindex;
3439 	ri->flags = flags;
3440 	WRITE_ONCE(ri->map, NULL);
3441 
3442 	return XDP_REDIRECT;
3443 }
3444 
3445 static const struct bpf_func_proto bpf_xdp_redirect_proto = {
3446 	.func           = bpf_xdp_redirect,
3447 	.gpl_only       = false,
3448 	.ret_type       = RET_INTEGER,
3449 	.arg1_type      = ARG_ANYTHING,
3450 	.arg2_type      = ARG_ANYTHING,
3451 };
3452 
3453 BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u32, ifindex,
3454 	   u64, flags)
3455 {
3456 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3457 
3458 	if (unlikely(flags))
3459 		return XDP_ABORTED;
3460 
3461 	ri->ifindex = ifindex;
3462 	ri->flags = flags;
3463 	WRITE_ONCE(ri->map, map);
3464 
3465 	return XDP_REDIRECT;
3466 }
3467 
3468 static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
3469 	.func           = bpf_xdp_redirect_map,
3470 	.gpl_only       = false,
3471 	.ret_type       = RET_INTEGER,
3472 	.arg1_type      = ARG_CONST_MAP_PTR,
3473 	.arg2_type      = ARG_ANYTHING,
3474 	.arg3_type      = ARG_ANYTHING,
3475 };
3476 
3477 static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
3478 				  unsigned long off, unsigned long len)
3479 {
3480 	void *ptr = skb_header_pointer(skb, off, len, dst_buff);
3481 
3482 	if (unlikely(!ptr))
3483 		return len;
3484 	if (ptr != dst_buff)
3485 		memcpy(dst_buff, ptr, len);
3486 
3487 	return 0;
3488 }
3489 
3490 BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
3491 	   u64, flags, void *, meta, u64, meta_size)
3492 {
3493 	u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
3494 
3495 	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
3496 		return -EINVAL;
3497 	if (unlikely(skb_size > skb->len))
3498 		return -EFAULT;
3499 
3500 	return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
3501 				bpf_skb_copy);
3502 }
3503 
3504 static const struct bpf_func_proto bpf_skb_event_output_proto = {
3505 	.func		= bpf_skb_event_output,
3506 	.gpl_only	= true,
3507 	.ret_type	= RET_INTEGER,
3508 	.arg1_type	= ARG_PTR_TO_CTX,
3509 	.arg2_type	= ARG_CONST_MAP_PTR,
3510 	.arg3_type	= ARG_ANYTHING,
3511 	.arg4_type	= ARG_PTR_TO_MEM,
3512 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
3513 };
3514 
3515 static unsigned short bpf_tunnel_key_af(u64 flags)
3516 {
3517 	return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
3518 }
3519 
3520 BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
3521 	   u32, size, u64, flags)
3522 {
3523 	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3524 	u8 compat[sizeof(struct bpf_tunnel_key)];
3525 	void *to_orig = to;
3526 	int err;
3527 
3528 	if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) {
3529 		err = -EINVAL;
3530 		goto err_clear;
3531 	}
3532 	if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
3533 		err = -EPROTO;
3534 		goto err_clear;
3535 	}
3536 	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3537 		err = -EINVAL;
3538 		switch (size) {
3539 		case offsetof(struct bpf_tunnel_key, tunnel_label):
3540 		case offsetof(struct bpf_tunnel_key, tunnel_ext):
3541 			goto set_compat;
3542 		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3543 			/* Fixup deprecated structure layouts here, so we have
3544 			 * a common path later on.
3545 			 */
3546 			if (ip_tunnel_info_af(info) != AF_INET)
3547 				goto err_clear;
3548 set_compat:
3549 			to = (struct bpf_tunnel_key *)compat;
3550 			break;
3551 		default:
3552 			goto err_clear;
3553 		}
3554 	}
3555 
3556 	to->tunnel_id = be64_to_cpu(info->key.tun_id);
3557 	to->tunnel_tos = info->key.tos;
3558 	to->tunnel_ttl = info->key.ttl;
3559 	to->tunnel_ext = 0;
3560 
3561 	if (flags & BPF_F_TUNINFO_IPV6) {
3562 		memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
3563 		       sizeof(to->remote_ipv6));
3564 		to->tunnel_label = be32_to_cpu(info->key.label);
3565 	} else {
3566 		to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
3567 		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
3568 		to->tunnel_label = 0;
3569 	}
3570 
3571 	if (unlikely(size != sizeof(struct bpf_tunnel_key)))
3572 		memcpy(to_orig, to, size);
3573 
3574 	return 0;
3575 err_clear:
3576 	memset(to_orig, 0, size);
3577 	return err;
3578 }
3579 
3580 static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
3581 	.func		= bpf_skb_get_tunnel_key,
3582 	.gpl_only	= false,
3583 	.ret_type	= RET_INTEGER,
3584 	.arg1_type	= ARG_PTR_TO_CTX,
3585 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
3586 	.arg3_type	= ARG_CONST_SIZE,
3587 	.arg4_type	= ARG_ANYTHING,
3588 };
3589 
3590 BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
3591 {
3592 	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3593 	int err;
3594 
3595 	if (unlikely(!info ||
3596 		     !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
3597 		err = -ENOENT;
3598 		goto err_clear;
3599 	}
3600 	if (unlikely(size < info->options_len)) {
3601 		err = -ENOMEM;
3602 		goto err_clear;
3603 	}
3604 
3605 	ip_tunnel_info_opts_get(to, info);
3606 	if (size > info->options_len)
3607 		memset(to + info->options_len, 0, size - info->options_len);
3608 
3609 	return info->options_len;
3610 err_clear:
3611 	memset(to, 0, size);
3612 	return err;
3613 }
3614 
3615 static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
3616 	.func		= bpf_skb_get_tunnel_opt,
3617 	.gpl_only	= false,
3618 	.ret_type	= RET_INTEGER,
3619 	.arg1_type	= ARG_PTR_TO_CTX,
3620 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
3621 	.arg3_type	= ARG_CONST_SIZE,
3622 };
3623 
3624 static struct metadata_dst __percpu *md_dst;
3625 
3626 BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
3627 	   const struct bpf_tunnel_key *, from, u32, size, u64, flags)
3628 {
3629 	struct metadata_dst *md = this_cpu_ptr(md_dst);
3630 	u8 compat[sizeof(struct bpf_tunnel_key)];
3631 	struct ip_tunnel_info *info;
3632 
3633 	if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
3634 			       BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER)))
3635 		return -EINVAL;
3636 	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3637 		switch (size) {
3638 		case offsetof(struct bpf_tunnel_key, tunnel_label):
3639 		case offsetof(struct bpf_tunnel_key, tunnel_ext):
3640 		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3641 			/* Fixup deprecated structure layouts here, so we have
3642 			 * a common path later on.
3643 			 */
3644 			memcpy(compat, from, size);
3645 			memset(compat + size, 0, sizeof(compat) - size);
3646 			from = (const struct bpf_tunnel_key *) compat;
3647 			break;
3648 		default:
3649 			return -EINVAL;
3650 		}
3651 	}
3652 	if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
3653 		     from->tunnel_ext))
3654 		return -EINVAL;
3655 
3656 	skb_dst_drop(skb);
3657 	dst_hold((struct dst_entry *) md);
3658 	skb_dst_set(skb, (struct dst_entry *) md);
3659 
3660 	info = &md->u.tun_info;
3661 	memset(info, 0, sizeof(*info));
3662 	info->mode = IP_TUNNEL_INFO_TX;
3663 
3664 	info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
3665 	if (flags & BPF_F_DONT_FRAGMENT)
3666 		info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;
3667 	if (flags & BPF_F_ZERO_CSUM_TX)
3668 		info->key.tun_flags &= ~TUNNEL_CSUM;
3669 	if (flags & BPF_F_SEQ_NUMBER)
3670 		info->key.tun_flags |= TUNNEL_SEQ;
3671 
3672 	info->key.tun_id = cpu_to_be64(from->tunnel_id);
3673 	info->key.tos = from->tunnel_tos;
3674 	info->key.ttl = from->tunnel_ttl;
3675 
3676 	if (flags & BPF_F_TUNINFO_IPV6) {
3677 		info->mode |= IP_TUNNEL_INFO_IPV6;
3678 		memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
3679 		       sizeof(from->remote_ipv6));
3680 		info->key.label = cpu_to_be32(from->tunnel_label) &
3681 				  IPV6_FLOWLABEL_MASK;
3682 	} else {
3683 		info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
3684 	}
3685 
3686 	return 0;
3687 }
3688 
3689 static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
3690 	.func		= bpf_skb_set_tunnel_key,
3691 	.gpl_only	= false,
3692 	.ret_type	= RET_INTEGER,
3693 	.arg1_type	= ARG_PTR_TO_CTX,
3694 	.arg2_type	= ARG_PTR_TO_MEM,
3695 	.arg3_type	= ARG_CONST_SIZE,
3696 	.arg4_type	= ARG_ANYTHING,
3697 };
3698 
3699 BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
3700 	   const u8 *, from, u32, size)
3701 {
3702 	struct ip_tunnel_info *info = skb_tunnel_info(skb);
3703 	const struct metadata_dst *md = this_cpu_ptr(md_dst);
3704 
3705 	if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
3706 		return -EINVAL;
3707 	if (unlikely(size > IP_TUNNEL_OPTS_MAX))
3708 		return -ENOMEM;
3709 
3710 	ip_tunnel_info_opts_set(info, from, size, TUNNEL_OPTIONS_PRESENT);
3711 
3712 	return 0;
3713 }
3714 
3715 static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
3716 	.func		= bpf_skb_set_tunnel_opt,
3717 	.gpl_only	= false,
3718 	.ret_type	= RET_INTEGER,
3719 	.arg1_type	= ARG_PTR_TO_CTX,
3720 	.arg2_type	= ARG_PTR_TO_MEM,
3721 	.arg3_type	= ARG_CONST_SIZE,
3722 };
3723 
3724 static const struct bpf_func_proto *
3725 bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
3726 {
3727 	if (!md_dst) {
3728 		struct metadata_dst __percpu *tmp;
3729 
3730 		tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
3731 						METADATA_IP_TUNNEL,
3732 						GFP_KERNEL);
3733 		if (!tmp)
3734 			return NULL;
3735 		if (cmpxchg(&md_dst, NULL, tmp))
3736 			metadata_dst_free_percpu(tmp);
3737 	}
3738 
3739 	switch (which) {
3740 	case BPF_FUNC_skb_set_tunnel_key:
3741 		return &bpf_skb_set_tunnel_key_proto;
3742 	case BPF_FUNC_skb_set_tunnel_opt:
3743 		return &bpf_skb_set_tunnel_opt_proto;
3744 	default:
3745 		return NULL;
3746 	}
3747 }
3748 
3749 BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
3750 	   u32, idx)
3751 {
3752 	struct bpf_array *array = container_of(map, struct bpf_array, map);
3753 	struct cgroup *cgrp;
3754 	struct sock *sk;
3755 
3756 	sk = skb_to_full_sk(skb);
3757 	if (!sk || !sk_fullsock(sk))
3758 		return -ENOENT;
3759 	if (unlikely(idx >= array->map.max_entries))
3760 		return -E2BIG;
3761 
3762 	cgrp = READ_ONCE(array->ptrs[idx]);
3763 	if (unlikely(!cgrp))
3764 		return -EAGAIN;
3765 
3766 	return sk_under_cgroup_hierarchy(sk, cgrp);
3767 }
3768 
3769 static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
3770 	.func		= bpf_skb_under_cgroup,
3771 	.gpl_only	= false,
3772 	.ret_type	= RET_INTEGER,
3773 	.arg1_type	= ARG_PTR_TO_CTX,
3774 	.arg2_type	= ARG_CONST_MAP_PTR,
3775 	.arg3_type	= ARG_ANYTHING,
3776 };
3777 
3778 #ifdef CONFIG_SOCK_CGROUP_DATA
3779 BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
3780 {
3781 	struct sock *sk = skb_to_full_sk(skb);
3782 	struct cgroup *cgrp;
3783 
3784 	if (!sk || !sk_fullsock(sk))
3785 		return 0;
3786 
3787 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
3788 	return cgrp->kn->id.id;
3789 }
3790 
3791 static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
3792 	.func           = bpf_skb_cgroup_id,
3793 	.gpl_only       = false,
3794 	.ret_type       = RET_INTEGER,
3795 	.arg1_type      = ARG_PTR_TO_CTX,
3796 };
3797 
3798 BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
3799 	   ancestor_level)
3800 {
3801 	struct sock *sk = skb_to_full_sk(skb);
3802 	struct cgroup *ancestor;
3803 	struct cgroup *cgrp;
3804 
3805 	if (!sk || !sk_fullsock(sk))
3806 		return 0;
3807 
3808 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
3809 	ancestor = cgroup_ancestor(cgrp, ancestor_level);
3810 	if (!ancestor)
3811 		return 0;
3812 
3813 	return ancestor->kn->id.id;
3814 }
3815 
3816 static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
3817 	.func           = bpf_skb_ancestor_cgroup_id,
3818 	.gpl_only       = false,
3819 	.ret_type       = RET_INTEGER,
3820 	.arg1_type      = ARG_PTR_TO_CTX,
3821 	.arg2_type      = ARG_ANYTHING,
3822 };
3823 #endif
3824 
3825 static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff,
3826 				  unsigned long off, unsigned long len)
3827 {
3828 	memcpy(dst_buff, src_buff + off, len);
3829 	return 0;
3830 }
3831 
3832 BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
3833 	   u64, flags, void *, meta, u64, meta_size)
3834 {
3835 	u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
3836 
3837 	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
3838 		return -EINVAL;
3839 	if (unlikely(xdp_size > (unsigned long)(xdp->data_end - xdp->data)))
3840 		return -EFAULT;
3841 
3842 	return bpf_event_output(map, flags, meta, meta_size, xdp->data,
3843 				xdp_size, bpf_xdp_copy);
3844 }
3845 
3846 static const struct bpf_func_proto bpf_xdp_event_output_proto = {
3847 	.func		= bpf_xdp_event_output,
3848 	.gpl_only	= true,
3849 	.ret_type	= RET_INTEGER,
3850 	.arg1_type	= ARG_PTR_TO_CTX,
3851 	.arg2_type	= ARG_CONST_MAP_PTR,
3852 	.arg3_type	= ARG_ANYTHING,
3853 	.arg4_type	= ARG_PTR_TO_MEM,
3854 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
3855 };
3856 
3857 BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
3858 {
3859 	return skb->sk ? sock_gen_cookie(skb->sk) : 0;
3860 }
3861 
3862 static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
3863 	.func           = bpf_get_socket_cookie,
3864 	.gpl_only       = false,
3865 	.ret_type       = RET_INTEGER,
3866 	.arg1_type      = ARG_PTR_TO_CTX,
3867 };
3868 
3869 BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
3870 {
3871 	return sock_gen_cookie(ctx->sk);
3872 }
3873 
3874 static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
3875 	.func		= bpf_get_socket_cookie_sock_addr,
3876 	.gpl_only	= false,
3877 	.ret_type	= RET_INTEGER,
3878 	.arg1_type	= ARG_PTR_TO_CTX,
3879 };
3880 
3881 BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
3882 {
3883 	return sock_gen_cookie(ctx->sk);
3884 }
3885 
3886 static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
3887 	.func		= bpf_get_socket_cookie_sock_ops,
3888 	.gpl_only	= false,
3889 	.ret_type	= RET_INTEGER,
3890 	.arg1_type	= ARG_PTR_TO_CTX,
3891 };
3892 
3893 BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
3894 {
3895 	struct sock *sk = sk_to_full_sk(skb->sk);
3896 	kuid_t kuid;
3897 
3898 	if (!sk || !sk_fullsock(sk))
3899 		return overflowuid;
3900 	kuid = sock_net_uid(sock_net(sk), sk);
3901 	return from_kuid_munged(sock_net(sk)->user_ns, kuid);
3902 }
3903 
3904 static const struct bpf_func_proto bpf_get_socket_uid_proto = {
3905 	.func           = bpf_get_socket_uid,
3906 	.gpl_only       = false,
3907 	.ret_type       = RET_INTEGER,
3908 	.arg1_type      = ARG_PTR_TO_CTX,
3909 };
3910 
3911 BPF_CALL_5(bpf_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
3912 	   int, level, int, optname, char *, optval, int, optlen)
3913 {
3914 	struct sock *sk = bpf_sock->sk;
3915 	int ret = 0;
3916 	int val;
3917 
3918 	if (!sk_fullsock(sk))
3919 		return -EINVAL;
3920 
3921 	if (level == SOL_SOCKET) {
3922 		if (optlen != sizeof(int))
3923 			return -EINVAL;
3924 		val = *((int *)optval);
3925 
3926 		/* Only some socketops are supported */
3927 		switch (optname) {
3928 		case SO_RCVBUF:
3929 			sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
3930 			sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);
3931 			break;
3932 		case SO_SNDBUF:
3933 			sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
3934 			sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
3935 			break;
3936 		case SO_MAX_PACING_RATE: /* 32bit version */
3937 			sk->sk_max_pacing_rate = (val == ~0U) ? ~0UL : val;
3938 			sk->sk_pacing_rate = min(sk->sk_pacing_rate,
3939 						 sk->sk_max_pacing_rate);
3940 			break;
3941 		case SO_PRIORITY:
3942 			sk->sk_priority = val;
3943 			break;
3944 		case SO_RCVLOWAT:
3945 			if (val < 0)
3946 				val = INT_MAX;
3947 			sk->sk_rcvlowat = val ? : 1;
3948 			break;
3949 		case SO_MARK:
3950 			sk->sk_mark = val;
3951 			break;
3952 		default:
3953 			ret = -EINVAL;
3954 		}
3955 #ifdef CONFIG_INET
3956 	} else if (level == SOL_IP) {
3957 		if (optlen != sizeof(int) || sk->sk_family != AF_INET)
3958 			return -EINVAL;
3959 
3960 		val = *((int *)optval);
3961 		/* Only some options are supported */
3962 		switch (optname) {
3963 		case IP_TOS:
3964 			if (val < -1 || val > 0xff) {
3965 				ret = -EINVAL;
3966 			} else {
3967 				struct inet_sock *inet = inet_sk(sk);
3968 
3969 				if (val == -1)
3970 					val = 0;
3971 				inet->tos = val;
3972 			}
3973 			break;
3974 		default:
3975 			ret = -EINVAL;
3976 		}
3977 #if IS_ENABLED(CONFIG_IPV6)
3978 	} else if (level == SOL_IPV6) {
3979 		if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
3980 			return -EINVAL;
3981 
3982 		val = *((int *)optval);
3983 		/* Only some options are supported */
3984 		switch (optname) {
3985 		case IPV6_TCLASS:
3986 			if (val < -1 || val > 0xff) {
3987 				ret = -EINVAL;
3988 			} else {
3989 				struct ipv6_pinfo *np = inet6_sk(sk);
3990 
3991 				if (val == -1)
3992 					val = 0;
3993 				np->tclass = val;
3994 			}
3995 			break;
3996 		default:
3997 			ret = -EINVAL;
3998 		}
3999 #endif
4000 	} else if (level == SOL_TCP &&
4001 		   sk->sk_prot->setsockopt == tcp_setsockopt) {
4002 		if (optname == TCP_CONGESTION) {
4003 			char name[TCP_CA_NAME_MAX];
4004 			bool reinit = bpf_sock->op > BPF_SOCK_OPS_NEEDS_ECN;
4005 
4006 			strncpy(name, optval, min_t(long, optlen,
4007 						    TCP_CA_NAME_MAX-1));
4008 			name[TCP_CA_NAME_MAX-1] = 0;
4009 			ret = tcp_set_congestion_control(sk, name, false,
4010 							 reinit);
4011 		} else {
4012 			struct tcp_sock *tp = tcp_sk(sk);
4013 
4014 			if (optlen != sizeof(int))
4015 				return -EINVAL;
4016 
4017 			val = *((int *)optval);
4018 			/* Only some options are supported */
4019 			switch (optname) {
4020 			case TCP_BPF_IW:
4021 				if (val <= 0 || tp->data_segs_out > 0)
4022 					ret = -EINVAL;
4023 				else
4024 					tp->snd_cwnd = val;
4025 				break;
4026 			case TCP_BPF_SNDCWND_CLAMP:
4027 				if (val <= 0) {
4028 					ret = -EINVAL;
4029 				} else {
4030 					tp->snd_cwnd_clamp = val;
4031 					tp->snd_ssthresh = val;
4032 				}
4033 				break;
4034 			case TCP_SAVE_SYN:
4035 				if (val < 0 || val > 1)
4036 					ret = -EINVAL;
4037 				else
4038 					tp->save_syn = val;
4039 				break;
4040 			default:
4041 				ret = -EINVAL;
4042 			}
4043 		}
4044 #endif
4045 	} else {
4046 		ret = -EINVAL;
4047 	}
4048 	return ret;
4049 }
4050 
4051 static const struct bpf_func_proto bpf_setsockopt_proto = {
4052 	.func		= bpf_setsockopt,
4053 	.gpl_only	= false,
4054 	.ret_type	= RET_INTEGER,
4055 	.arg1_type	= ARG_PTR_TO_CTX,
4056 	.arg2_type	= ARG_ANYTHING,
4057 	.arg3_type	= ARG_ANYTHING,
4058 	.arg4_type	= ARG_PTR_TO_MEM,
4059 	.arg5_type	= ARG_CONST_SIZE,
4060 };
4061 
4062 BPF_CALL_5(bpf_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4063 	   int, level, int, optname, char *, optval, int, optlen)
4064 {
4065 	struct sock *sk = bpf_sock->sk;
4066 
4067 	if (!sk_fullsock(sk))
4068 		goto err_clear;
4069 #ifdef CONFIG_INET
4070 	if (level == SOL_TCP && sk->sk_prot->getsockopt == tcp_getsockopt) {
4071 		struct inet_connection_sock *icsk;
4072 		struct tcp_sock *tp;
4073 
4074 		switch (optname) {
4075 		case TCP_CONGESTION:
4076 			icsk = inet_csk(sk);
4077 
4078 			if (!icsk->icsk_ca_ops || optlen <= 1)
4079 				goto err_clear;
4080 			strncpy(optval, icsk->icsk_ca_ops->name, optlen);
4081 			optval[optlen - 1] = 0;
4082 			break;
4083 		case TCP_SAVED_SYN:
4084 			tp = tcp_sk(sk);
4085 
4086 			if (optlen <= 0 || !tp->saved_syn ||
4087 			    optlen > tp->saved_syn[0])
4088 				goto err_clear;
4089 			memcpy(optval, tp->saved_syn + 1, optlen);
4090 			break;
4091 		default:
4092 			goto err_clear;
4093 		}
4094 	} else if (level == SOL_IP) {
4095 		struct inet_sock *inet = inet_sk(sk);
4096 
4097 		if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4098 			goto err_clear;
4099 
4100 		/* Only some options are supported */
4101 		switch (optname) {
4102 		case IP_TOS:
4103 			*((int *)optval) = (int)inet->tos;
4104 			break;
4105 		default:
4106 			goto err_clear;
4107 		}
4108 #if IS_ENABLED(CONFIG_IPV6)
4109 	} else if (level == SOL_IPV6) {
4110 		struct ipv6_pinfo *np = inet6_sk(sk);
4111 
4112 		if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4113 			goto err_clear;
4114 
4115 		/* Only some options are supported */
4116 		switch (optname) {
4117 		case IPV6_TCLASS:
4118 			*((int *)optval) = (int)np->tclass;
4119 			break;
4120 		default:
4121 			goto err_clear;
4122 		}
4123 #endif
4124 	} else {
4125 		goto err_clear;
4126 	}
4127 	return 0;
4128 #endif
4129 err_clear:
4130 	memset(optval, 0, optlen);
4131 	return -EINVAL;
4132 }
4133 
4134 static const struct bpf_func_proto bpf_getsockopt_proto = {
4135 	.func		= bpf_getsockopt,
4136 	.gpl_only	= false,
4137 	.ret_type	= RET_INTEGER,
4138 	.arg1_type	= ARG_PTR_TO_CTX,
4139 	.arg2_type	= ARG_ANYTHING,
4140 	.arg3_type	= ARG_ANYTHING,
4141 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
4142 	.arg5_type	= ARG_CONST_SIZE,
4143 };
4144 
4145 BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
4146 	   int, argval)
4147 {
4148 	struct sock *sk = bpf_sock->sk;
4149 	int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
4150 
4151 	if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
4152 		return -EINVAL;
4153 
4154 	if (val)
4155 		tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
4156 
4157 	return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
4158 }
4159 
4160 static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
4161 	.func		= bpf_sock_ops_cb_flags_set,
4162 	.gpl_only	= false,
4163 	.ret_type	= RET_INTEGER,
4164 	.arg1_type	= ARG_PTR_TO_CTX,
4165 	.arg2_type	= ARG_ANYTHING,
4166 };
4167 
4168 const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly;
4169 EXPORT_SYMBOL_GPL(ipv6_bpf_stub);
4170 
4171 BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
4172 	   int, addr_len)
4173 {
4174 #ifdef CONFIG_INET
4175 	struct sock *sk = ctx->sk;
4176 	int err;
4177 
4178 	/* Binding to port can be expensive so it's prohibited in the helper.
4179 	 * Only binding to IP is supported.
4180 	 */
4181 	err = -EINVAL;
4182 	if (addr->sa_family == AF_INET) {
4183 		if (addr_len < sizeof(struct sockaddr_in))
4184 			return err;
4185 		if (((struct sockaddr_in *)addr)->sin_port != htons(0))
4186 			return err;
4187 		return __inet_bind(sk, addr, addr_len, true, false);
4188 #if IS_ENABLED(CONFIG_IPV6)
4189 	} else if (addr->sa_family == AF_INET6) {
4190 		if (addr_len < SIN6_LEN_RFC2133)
4191 			return err;
4192 		if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
4193 			return err;
4194 		/* ipv6_bpf_stub cannot be NULL, since it's called from
4195 		 * bpf_cgroup_inet6_connect hook and ipv6 is already loaded
4196 		 */
4197 		return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, true, false);
4198 #endif /* CONFIG_IPV6 */
4199 	}
4200 #endif /* CONFIG_INET */
4201 
4202 	return -EAFNOSUPPORT;
4203 }
4204 
4205 static const struct bpf_func_proto bpf_bind_proto = {
4206 	.func		= bpf_bind,
4207 	.gpl_only	= false,
4208 	.ret_type	= RET_INTEGER,
4209 	.arg1_type	= ARG_PTR_TO_CTX,
4210 	.arg2_type	= ARG_PTR_TO_MEM,
4211 	.arg3_type	= ARG_CONST_SIZE,
4212 };
4213 
4214 #ifdef CONFIG_XFRM
4215 BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
4216 	   struct bpf_xfrm_state *, to, u32, size, u64, flags)
4217 {
4218 	const struct sec_path *sp = skb_sec_path(skb);
4219 	const struct xfrm_state *x;
4220 
4221 	if (!sp || unlikely(index >= sp->len || flags))
4222 		goto err_clear;
4223 
4224 	x = sp->xvec[index];
4225 
4226 	if (unlikely(size != sizeof(struct bpf_xfrm_state)))
4227 		goto err_clear;
4228 
4229 	to->reqid = x->props.reqid;
4230 	to->spi = x->id.spi;
4231 	to->family = x->props.family;
4232 	to->ext = 0;
4233 
4234 	if (to->family == AF_INET6) {
4235 		memcpy(to->remote_ipv6, x->props.saddr.a6,
4236 		       sizeof(to->remote_ipv6));
4237 	} else {
4238 		to->remote_ipv4 = x->props.saddr.a4;
4239 		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4240 	}
4241 
4242 	return 0;
4243 err_clear:
4244 	memset(to, 0, size);
4245 	return -EINVAL;
4246 }
4247 
4248 static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
4249 	.func		= bpf_skb_get_xfrm_state,
4250 	.gpl_only	= false,
4251 	.ret_type	= RET_INTEGER,
4252 	.arg1_type	= ARG_PTR_TO_CTX,
4253 	.arg2_type	= ARG_ANYTHING,
4254 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
4255 	.arg4_type	= ARG_CONST_SIZE,
4256 	.arg5_type	= ARG_ANYTHING,
4257 };
4258 #endif
4259 
4260 #if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
4261 static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params,
4262 				  const struct neighbour *neigh,
4263 				  const struct net_device *dev)
4264 {
4265 	memcpy(params->dmac, neigh->ha, ETH_ALEN);
4266 	memcpy(params->smac, dev->dev_addr, ETH_ALEN);
4267 	params->h_vlan_TCI = 0;
4268 	params->h_vlan_proto = 0;
4269 	params->ifindex = dev->ifindex;
4270 
4271 	return 0;
4272 }
4273 #endif
4274 
4275 #if IS_ENABLED(CONFIG_INET)
4276 static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4277 			       u32 flags, bool check_mtu)
4278 {
4279 	struct in_device *in_dev;
4280 	struct neighbour *neigh;
4281 	struct net_device *dev;
4282 	struct fib_result res;
4283 	struct fib_nh *nh;
4284 	struct flowi4 fl4;
4285 	int err;
4286 	u32 mtu;
4287 
4288 	dev = dev_get_by_index_rcu(net, params->ifindex);
4289 	if (unlikely(!dev))
4290 		return -ENODEV;
4291 
4292 	/* verify forwarding is enabled on this interface */
4293 	in_dev = __in_dev_get_rcu(dev);
4294 	if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
4295 		return BPF_FIB_LKUP_RET_FWD_DISABLED;
4296 
4297 	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4298 		fl4.flowi4_iif = 1;
4299 		fl4.flowi4_oif = params->ifindex;
4300 	} else {
4301 		fl4.flowi4_iif = params->ifindex;
4302 		fl4.flowi4_oif = 0;
4303 	}
4304 	fl4.flowi4_tos = params->tos & IPTOS_RT_MASK;
4305 	fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
4306 	fl4.flowi4_flags = 0;
4307 
4308 	fl4.flowi4_proto = params->l4_protocol;
4309 	fl4.daddr = params->ipv4_dst;
4310 	fl4.saddr = params->ipv4_src;
4311 	fl4.fl4_sport = params->sport;
4312 	fl4.fl4_dport = params->dport;
4313 
4314 	if (flags & BPF_FIB_LOOKUP_DIRECT) {
4315 		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4316 		struct fib_table *tb;
4317 
4318 		tb = fib_get_table(net, tbid);
4319 		if (unlikely(!tb))
4320 			return BPF_FIB_LKUP_RET_NOT_FWDED;
4321 
4322 		err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
4323 	} else {
4324 		fl4.flowi4_mark = 0;
4325 		fl4.flowi4_secid = 0;
4326 		fl4.flowi4_tun_key.tun_id = 0;
4327 		fl4.flowi4_uid = sock_net_uid(net, NULL);
4328 
4329 		err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
4330 	}
4331 
4332 	if (err) {
4333 		/* map fib lookup errors to RTN_ type */
4334 		if (err == -EINVAL)
4335 			return BPF_FIB_LKUP_RET_BLACKHOLE;
4336 		if (err == -EHOSTUNREACH)
4337 			return BPF_FIB_LKUP_RET_UNREACHABLE;
4338 		if (err == -EACCES)
4339 			return BPF_FIB_LKUP_RET_PROHIBIT;
4340 
4341 		return BPF_FIB_LKUP_RET_NOT_FWDED;
4342 	}
4343 
4344 	if (res.type != RTN_UNICAST)
4345 		return BPF_FIB_LKUP_RET_NOT_FWDED;
4346 
4347 	if (res.fi->fib_nhs > 1)
4348 		fib_select_path(net, &res, &fl4, NULL);
4349 
4350 	if (check_mtu) {
4351 		mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
4352 		if (params->tot_len > mtu)
4353 			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4354 	}
4355 
4356 	nh = &res.fi->fib_nh[res.nh_sel];
4357 
4358 	/* do not handle lwt encaps right now */
4359 	if (nh->nh_lwtstate)
4360 		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4361 
4362 	dev = nh->nh_dev;
4363 	if (nh->nh_gw)
4364 		params->ipv4_dst = nh->nh_gw;
4365 
4366 	params->rt_metric = res.fi->fib_priority;
4367 
4368 	/* xdp and cls_bpf programs are run in RCU-bh so
4369 	 * rcu_read_lock_bh is not needed here
4370 	 */
4371 	neigh = __ipv4_neigh_lookup_noref(dev, (__force u32)params->ipv4_dst);
4372 	if (!neigh)
4373 		return BPF_FIB_LKUP_RET_NO_NEIGH;
4374 
4375 	return bpf_fib_set_fwd_params(params, neigh, dev);
4376 }
4377 #endif
4378 
4379 #if IS_ENABLED(CONFIG_IPV6)
4380 static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4381 			       u32 flags, bool check_mtu)
4382 {
4383 	struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
4384 	struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
4385 	struct neighbour *neigh;
4386 	struct net_device *dev;
4387 	struct inet6_dev *idev;
4388 	struct fib6_info *f6i;
4389 	struct flowi6 fl6;
4390 	int strict = 0;
4391 	int oif;
4392 	u32 mtu;
4393 
4394 	/* link local addresses are never forwarded */
4395 	if (rt6_need_strict(dst) || rt6_need_strict(src))
4396 		return BPF_FIB_LKUP_RET_NOT_FWDED;
4397 
4398 	dev = dev_get_by_index_rcu(net, params->ifindex);
4399 	if (unlikely(!dev))
4400 		return -ENODEV;
4401 
4402 	idev = __in6_dev_get_safely(dev);
4403 	if (unlikely(!idev || !net->ipv6.devconf_all->forwarding))
4404 		return BPF_FIB_LKUP_RET_FWD_DISABLED;
4405 
4406 	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4407 		fl6.flowi6_iif = 1;
4408 		oif = fl6.flowi6_oif = params->ifindex;
4409 	} else {
4410 		oif = fl6.flowi6_iif = params->ifindex;
4411 		fl6.flowi6_oif = 0;
4412 		strict = RT6_LOOKUP_F_HAS_SADDR;
4413 	}
4414 	fl6.flowlabel = params->flowinfo;
4415 	fl6.flowi6_scope = 0;
4416 	fl6.flowi6_flags = 0;
4417 	fl6.mp_hash = 0;
4418 
4419 	fl6.flowi6_proto = params->l4_protocol;
4420 	fl6.daddr = *dst;
4421 	fl6.saddr = *src;
4422 	fl6.fl6_sport = params->sport;
4423 	fl6.fl6_dport = params->dport;
4424 
4425 	if (flags & BPF_FIB_LOOKUP_DIRECT) {
4426 		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4427 		struct fib6_table *tb;
4428 
4429 		tb = ipv6_stub->fib6_get_table(net, tbid);
4430 		if (unlikely(!tb))
4431 			return BPF_FIB_LKUP_RET_NOT_FWDED;
4432 
4433 		f6i = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, strict);
4434 	} else {
4435 		fl6.flowi6_mark = 0;
4436 		fl6.flowi6_secid = 0;
4437 		fl6.flowi6_tun_key.tun_id = 0;
4438 		fl6.flowi6_uid = sock_net_uid(net, NULL);
4439 
4440 		f6i = ipv6_stub->fib6_lookup(net, oif, &fl6, strict);
4441 	}
4442 
4443 	if (unlikely(IS_ERR_OR_NULL(f6i) || f6i == net->ipv6.fib6_null_entry))
4444 		return BPF_FIB_LKUP_RET_NOT_FWDED;
4445 
4446 	if (unlikely(f6i->fib6_flags & RTF_REJECT)) {
4447 		switch (f6i->fib6_type) {
4448 		case RTN_BLACKHOLE:
4449 			return BPF_FIB_LKUP_RET_BLACKHOLE;
4450 		case RTN_UNREACHABLE:
4451 			return BPF_FIB_LKUP_RET_UNREACHABLE;
4452 		case RTN_PROHIBIT:
4453 			return BPF_FIB_LKUP_RET_PROHIBIT;
4454 		default:
4455 			return BPF_FIB_LKUP_RET_NOT_FWDED;
4456 		}
4457 	}
4458 
4459 	if (f6i->fib6_type != RTN_UNICAST)
4460 		return BPF_FIB_LKUP_RET_NOT_FWDED;
4461 
4462 	if (f6i->fib6_nsiblings && fl6.flowi6_oif == 0)
4463 		f6i = ipv6_stub->fib6_multipath_select(net, f6i, &fl6,
4464 						       fl6.flowi6_oif, NULL,
4465 						       strict);
4466 
4467 	if (check_mtu) {
4468 		mtu = ipv6_stub->ip6_mtu_from_fib6(f6i, dst, src);
4469 		if (params->tot_len > mtu)
4470 			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4471 	}
4472 
4473 	if (f6i->fib6_nh.nh_lwtstate)
4474 		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4475 
4476 	if (f6i->fib6_flags & RTF_GATEWAY)
4477 		*dst = f6i->fib6_nh.nh_gw;
4478 
4479 	dev = f6i->fib6_nh.nh_dev;
4480 	params->rt_metric = f6i->fib6_metric;
4481 
4482 	/* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
4483 	 * not needed here. Can not use __ipv6_neigh_lookup_noref here
4484 	 * because we need to get nd_tbl via the stub
4485 	 */
4486 	neigh = ___neigh_lookup_noref(ipv6_stub->nd_tbl, neigh_key_eq128,
4487 				      ndisc_hashfn, dst, dev);
4488 	if (!neigh)
4489 		return BPF_FIB_LKUP_RET_NO_NEIGH;
4490 
4491 	return bpf_fib_set_fwd_params(params, neigh, dev);
4492 }
4493 #endif
4494 
4495 BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
4496 	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
4497 {
4498 	if (plen < sizeof(*params))
4499 		return -EINVAL;
4500 
4501 	if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4502 		return -EINVAL;
4503 
4504 	switch (params->family) {
4505 #if IS_ENABLED(CONFIG_INET)
4506 	case AF_INET:
4507 		return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
4508 					   flags, true);
4509 #endif
4510 #if IS_ENABLED(CONFIG_IPV6)
4511 	case AF_INET6:
4512 		return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
4513 					   flags, true);
4514 #endif
4515 	}
4516 	return -EAFNOSUPPORT;
4517 }
4518 
4519 static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
4520 	.func		= bpf_xdp_fib_lookup,
4521 	.gpl_only	= true,
4522 	.ret_type	= RET_INTEGER,
4523 	.arg1_type      = ARG_PTR_TO_CTX,
4524 	.arg2_type      = ARG_PTR_TO_MEM,
4525 	.arg3_type      = ARG_CONST_SIZE,
4526 	.arg4_type	= ARG_ANYTHING,
4527 };
4528 
4529 BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
4530 	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
4531 {
4532 	struct net *net = dev_net(skb->dev);
4533 	int rc = -EAFNOSUPPORT;
4534 
4535 	if (plen < sizeof(*params))
4536 		return -EINVAL;
4537 
4538 	if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4539 		return -EINVAL;
4540 
4541 	switch (params->family) {
4542 #if IS_ENABLED(CONFIG_INET)
4543 	case AF_INET:
4544 		rc = bpf_ipv4_fib_lookup(net, params, flags, false);
4545 		break;
4546 #endif
4547 #if IS_ENABLED(CONFIG_IPV6)
4548 	case AF_INET6:
4549 		rc = bpf_ipv6_fib_lookup(net, params, flags, false);
4550 		break;
4551 #endif
4552 	}
4553 
4554 	if (!rc) {
4555 		struct net_device *dev;
4556 
4557 		dev = dev_get_by_index_rcu(net, params->ifindex);
4558 		if (!is_skb_forwardable(dev, skb))
4559 			rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
4560 	}
4561 
4562 	return rc;
4563 }
4564 
4565 static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
4566 	.func		= bpf_skb_fib_lookup,
4567 	.gpl_only	= true,
4568 	.ret_type	= RET_INTEGER,
4569 	.arg1_type      = ARG_PTR_TO_CTX,
4570 	.arg2_type      = ARG_PTR_TO_MEM,
4571 	.arg3_type      = ARG_CONST_SIZE,
4572 	.arg4_type	= ARG_ANYTHING,
4573 };
4574 
4575 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4576 static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
4577 {
4578 	int err;
4579 	struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;
4580 
4581 	if (!seg6_validate_srh(srh, len))
4582 		return -EINVAL;
4583 
4584 	switch (type) {
4585 	case BPF_LWT_ENCAP_SEG6_INLINE:
4586 		if (skb->protocol != htons(ETH_P_IPV6))
4587 			return -EBADMSG;
4588 
4589 		err = seg6_do_srh_inline(skb, srh);
4590 		break;
4591 	case BPF_LWT_ENCAP_SEG6:
4592 		skb_reset_inner_headers(skb);
4593 		skb->encapsulation = 1;
4594 		err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
4595 		break;
4596 	default:
4597 		return -EINVAL;
4598 	}
4599 
4600 	bpf_compute_data_pointers(skb);
4601 	if (err)
4602 		return err;
4603 
4604 	ipv6_hdr(skb)->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
4605 	skb_set_transport_header(skb, sizeof(struct ipv6hdr));
4606 
4607 	return seg6_lookup_nexthop(skb, NULL, 0);
4608 }
4609 #endif /* CONFIG_IPV6_SEG6_BPF */
4610 
4611 BPF_CALL_4(bpf_lwt_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
4612 	   u32, len)
4613 {
4614 	switch (type) {
4615 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4616 	case BPF_LWT_ENCAP_SEG6:
4617 	case BPF_LWT_ENCAP_SEG6_INLINE:
4618 		return bpf_push_seg6_encap(skb, type, hdr, len);
4619 #endif
4620 	default:
4621 		return -EINVAL;
4622 	}
4623 }
4624 
4625 static const struct bpf_func_proto bpf_lwt_push_encap_proto = {
4626 	.func		= bpf_lwt_push_encap,
4627 	.gpl_only	= false,
4628 	.ret_type	= RET_INTEGER,
4629 	.arg1_type	= ARG_PTR_TO_CTX,
4630 	.arg2_type	= ARG_ANYTHING,
4631 	.arg3_type	= ARG_PTR_TO_MEM,
4632 	.arg4_type	= ARG_CONST_SIZE
4633 };
4634 
4635 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4636 BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
4637 	   const void *, from, u32, len)
4638 {
4639 	struct seg6_bpf_srh_state *srh_state =
4640 		this_cpu_ptr(&seg6_bpf_srh_states);
4641 	struct ipv6_sr_hdr *srh = srh_state->srh;
4642 	void *srh_tlvs, *srh_end, *ptr;
4643 	int srhoff = 0;
4644 
4645 	if (srh == NULL)
4646 		return -EINVAL;
4647 
4648 	srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
4649 	srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
4650 
4651 	ptr = skb->data + offset;
4652 	if (ptr >= srh_tlvs && ptr + len <= srh_end)
4653 		srh_state->valid = false;
4654 	else if (ptr < (void *)&srh->flags ||
4655 		 ptr + len > (void *)&srh->segments)
4656 		return -EFAULT;
4657 
4658 	if (unlikely(bpf_try_make_writable(skb, offset + len)))
4659 		return -EFAULT;
4660 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
4661 		return -EINVAL;
4662 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
4663 
4664 	memcpy(skb->data + offset, from, len);
4665 	return 0;
4666 }
4667 
4668 static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
4669 	.func		= bpf_lwt_seg6_store_bytes,
4670 	.gpl_only	= false,
4671 	.ret_type	= RET_INTEGER,
4672 	.arg1_type	= ARG_PTR_TO_CTX,
4673 	.arg2_type	= ARG_ANYTHING,
4674 	.arg3_type	= ARG_PTR_TO_MEM,
4675 	.arg4_type	= ARG_CONST_SIZE
4676 };
4677 
4678 static void bpf_update_srh_state(struct sk_buff *skb)
4679 {
4680 	struct seg6_bpf_srh_state *srh_state =
4681 		this_cpu_ptr(&seg6_bpf_srh_states);
4682 	int srhoff = 0;
4683 
4684 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) {
4685 		srh_state->srh = NULL;
4686 	} else {
4687 		srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
4688 		srh_state->hdrlen = srh_state->srh->hdrlen << 3;
4689 		srh_state->valid = true;
4690 	}
4691 }
4692 
4693 BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
4694 	   u32, action, void *, param, u32, param_len)
4695 {
4696 	struct seg6_bpf_srh_state *srh_state =
4697 		this_cpu_ptr(&seg6_bpf_srh_states);
4698 	int hdroff = 0;
4699 	int err;
4700 
4701 	switch (action) {
4702 	case SEG6_LOCAL_ACTION_END_X:
4703 		if (!seg6_bpf_has_valid_srh(skb))
4704 			return -EBADMSG;
4705 		if (param_len != sizeof(struct in6_addr))
4706 			return -EINVAL;
4707 		return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
4708 	case SEG6_LOCAL_ACTION_END_T:
4709 		if (!seg6_bpf_has_valid_srh(skb))
4710 			return -EBADMSG;
4711 		if (param_len != sizeof(int))
4712 			return -EINVAL;
4713 		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
4714 	case SEG6_LOCAL_ACTION_END_DT6:
4715 		if (!seg6_bpf_has_valid_srh(skb))
4716 			return -EBADMSG;
4717 		if (param_len != sizeof(int))
4718 			return -EINVAL;
4719 
4720 		if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
4721 			return -EBADMSG;
4722 		if (!pskb_pull(skb, hdroff))
4723 			return -EBADMSG;
4724 
4725 		skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
4726 		skb_reset_network_header(skb);
4727 		skb_reset_transport_header(skb);
4728 		skb->encapsulation = 0;
4729 
4730 		bpf_compute_data_pointers(skb);
4731 		bpf_update_srh_state(skb);
4732 		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
4733 	case SEG6_LOCAL_ACTION_END_B6:
4734 		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
4735 			return -EBADMSG;
4736 		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
4737 					  param, param_len);
4738 		if (!err)
4739 			bpf_update_srh_state(skb);
4740 
4741 		return err;
4742 	case SEG6_LOCAL_ACTION_END_B6_ENCAP:
4743 		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
4744 			return -EBADMSG;
4745 		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
4746 					  param, param_len);
4747 		if (!err)
4748 			bpf_update_srh_state(skb);
4749 
4750 		return err;
4751 	default:
4752 		return -EINVAL;
4753 	}
4754 }
4755 
4756 static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
4757 	.func		= bpf_lwt_seg6_action,
4758 	.gpl_only	= false,
4759 	.ret_type	= RET_INTEGER,
4760 	.arg1_type	= ARG_PTR_TO_CTX,
4761 	.arg2_type	= ARG_ANYTHING,
4762 	.arg3_type	= ARG_PTR_TO_MEM,
4763 	.arg4_type	= ARG_CONST_SIZE
4764 };
4765 
4766 BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
4767 	   s32, len)
4768 {
4769 	struct seg6_bpf_srh_state *srh_state =
4770 		this_cpu_ptr(&seg6_bpf_srh_states);
4771 	struct ipv6_sr_hdr *srh = srh_state->srh;
4772 	void *srh_end, *srh_tlvs, *ptr;
4773 	struct ipv6hdr *hdr;
4774 	int srhoff = 0;
4775 	int ret;
4776 
4777 	if (unlikely(srh == NULL))
4778 		return -EINVAL;
4779 
4780 	srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
4781 			((srh->first_segment + 1) << 4));
4782 	srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
4783 			srh_state->hdrlen);
4784 	ptr = skb->data + offset;
4785 
4786 	if (unlikely(ptr < srh_tlvs || ptr > srh_end))
4787 		return -EFAULT;
4788 	if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
4789 		return -EFAULT;
4790 
4791 	if (len > 0) {
4792 		ret = skb_cow_head(skb, len);
4793 		if (unlikely(ret < 0))
4794 			return ret;
4795 
4796 		ret = bpf_skb_net_hdr_push(skb, offset, len);
4797 	} else {
4798 		ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
4799 	}
4800 
4801 	bpf_compute_data_pointers(skb);
4802 	if (unlikely(ret < 0))
4803 		return ret;
4804 
4805 	hdr = (struct ipv6hdr *)skb->data;
4806 	hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
4807 
4808 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
4809 		return -EINVAL;
4810 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
4811 	srh_state->hdrlen += len;
4812 	srh_state->valid = false;
4813 	return 0;
4814 }
4815 
4816 static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
4817 	.func		= bpf_lwt_seg6_adjust_srh,
4818 	.gpl_only	= false,
4819 	.ret_type	= RET_INTEGER,
4820 	.arg1_type	= ARG_PTR_TO_CTX,
4821 	.arg2_type	= ARG_ANYTHING,
4822 	.arg3_type	= ARG_ANYTHING,
4823 };
4824 #endif /* CONFIG_IPV6_SEG6_BPF */
4825 
4826 #ifdef CONFIG_INET
4827 static struct sock *sk_lookup(struct net *net, struct bpf_sock_tuple *tuple,
4828 			      struct sk_buff *skb, u8 family, u8 proto)
4829 {
4830 	bool refcounted = false;
4831 	struct sock *sk = NULL;
4832 	int dif = 0;
4833 
4834 	if (skb->dev)
4835 		dif = skb->dev->ifindex;
4836 
4837 	if (family == AF_INET) {
4838 		__be32 src4 = tuple->ipv4.saddr;
4839 		__be32 dst4 = tuple->ipv4.daddr;
4840 		int sdif = inet_sdif(skb);
4841 
4842 		if (proto == IPPROTO_TCP)
4843 			sk = __inet_lookup(net, &tcp_hashinfo, skb, 0,
4844 					   src4, tuple->ipv4.sport,
4845 					   dst4, tuple->ipv4.dport,
4846 					   dif, sdif, &refcounted);
4847 		else
4848 			sk = __udp4_lib_lookup(net, src4, tuple->ipv4.sport,
4849 					       dst4, tuple->ipv4.dport,
4850 					       dif, sdif, &udp_table, skb);
4851 #if IS_ENABLED(CONFIG_IPV6)
4852 	} else {
4853 		struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr;
4854 		struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr;
4855 		u16 hnum = ntohs(tuple->ipv6.dport);
4856 		int sdif = inet6_sdif(skb);
4857 
4858 		if (proto == IPPROTO_TCP)
4859 			sk = __inet6_lookup(net, &tcp_hashinfo, skb, 0,
4860 					    src6, tuple->ipv6.sport,
4861 					    dst6, hnum,
4862 					    dif, sdif, &refcounted);
4863 		else if (likely(ipv6_bpf_stub))
4864 			sk = ipv6_bpf_stub->udp6_lib_lookup(net,
4865 							    src6, tuple->ipv6.sport,
4866 							    dst6, hnum,
4867 							    dif, sdif,
4868 							    &udp_table, skb);
4869 #endif
4870 	}
4871 
4872 	if (unlikely(sk && !refcounted && !sock_flag(sk, SOCK_RCU_FREE))) {
4873 		WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
4874 		sk = NULL;
4875 	}
4876 	return sk;
4877 }
4878 
4879 /* bpf_sk_lookup performs the core lookup for different types of sockets,
4880  * taking a reference on the socket if it doesn't have the flag SOCK_RCU_FREE.
4881  * Returns the socket as an 'unsigned long' to simplify the casting in the
4882  * callers to satisfy BPF_CALL declarations.
4883  */
4884 static unsigned long
4885 bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
4886 	      u8 proto, u64 netns_id, u64 flags)
4887 {
4888 	struct net *caller_net;
4889 	struct sock *sk = NULL;
4890 	u8 family = AF_UNSPEC;
4891 	struct net *net;
4892 
4893 	family = len == sizeof(tuple->ipv4) ? AF_INET : AF_INET6;
4894 	if (unlikely(family == AF_UNSPEC || netns_id > U32_MAX || flags))
4895 		goto out;
4896 
4897 	if (skb->dev)
4898 		caller_net = dev_net(skb->dev);
4899 	else
4900 		caller_net = sock_net(skb->sk);
4901 	if (netns_id) {
4902 		net = get_net_ns_by_id(caller_net, netns_id);
4903 		if (unlikely(!net))
4904 			goto out;
4905 		sk = sk_lookup(net, tuple, skb, family, proto);
4906 		put_net(net);
4907 	} else {
4908 		net = caller_net;
4909 		sk = sk_lookup(net, tuple, skb, family, proto);
4910 	}
4911 
4912 	if (sk)
4913 		sk = sk_to_full_sk(sk);
4914 out:
4915 	return (unsigned long) sk;
4916 }
4917 
4918 BPF_CALL_5(bpf_sk_lookup_tcp, struct sk_buff *, skb,
4919 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
4920 {
4921 	return bpf_sk_lookup(skb, tuple, len, IPPROTO_TCP, netns_id, flags);
4922 }
4923 
4924 static const struct bpf_func_proto bpf_sk_lookup_tcp_proto = {
4925 	.func		= bpf_sk_lookup_tcp,
4926 	.gpl_only	= false,
4927 	.pkt_access	= true,
4928 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
4929 	.arg1_type	= ARG_PTR_TO_CTX,
4930 	.arg2_type	= ARG_PTR_TO_MEM,
4931 	.arg3_type	= ARG_CONST_SIZE,
4932 	.arg4_type	= ARG_ANYTHING,
4933 	.arg5_type	= ARG_ANYTHING,
4934 };
4935 
4936 BPF_CALL_5(bpf_sk_lookup_udp, struct sk_buff *, skb,
4937 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
4938 {
4939 	return bpf_sk_lookup(skb, tuple, len, IPPROTO_UDP, netns_id, flags);
4940 }
4941 
4942 static const struct bpf_func_proto bpf_sk_lookup_udp_proto = {
4943 	.func		= bpf_sk_lookup_udp,
4944 	.gpl_only	= false,
4945 	.pkt_access	= true,
4946 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
4947 	.arg1_type	= ARG_PTR_TO_CTX,
4948 	.arg2_type	= ARG_PTR_TO_MEM,
4949 	.arg3_type	= ARG_CONST_SIZE,
4950 	.arg4_type	= ARG_ANYTHING,
4951 	.arg5_type	= ARG_ANYTHING,
4952 };
4953 
4954 BPF_CALL_1(bpf_sk_release, struct sock *, sk)
4955 {
4956 	if (!sock_flag(sk, SOCK_RCU_FREE))
4957 		sock_gen_put(sk);
4958 	return 0;
4959 }
4960 
4961 static const struct bpf_func_proto bpf_sk_release_proto = {
4962 	.func		= bpf_sk_release,
4963 	.gpl_only	= false,
4964 	.ret_type	= RET_INTEGER,
4965 	.arg1_type	= ARG_PTR_TO_SOCKET,
4966 };
4967 #endif /* CONFIG_INET */
4968 
4969 bool bpf_helper_changes_pkt_data(void *func)
4970 {
4971 	if (func == bpf_skb_vlan_push ||
4972 	    func == bpf_skb_vlan_pop ||
4973 	    func == bpf_skb_store_bytes ||
4974 	    func == bpf_skb_change_proto ||
4975 	    func == bpf_skb_change_head ||
4976 	    func == sk_skb_change_head ||
4977 	    func == bpf_skb_change_tail ||
4978 	    func == sk_skb_change_tail ||
4979 	    func == bpf_skb_adjust_room ||
4980 	    func == bpf_skb_pull_data ||
4981 	    func == sk_skb_pull_data ||
4982 	    func == bpf_clone_redirect ||
4983 	    func == bpf_l3_csum_replace ||
4984 	    func == bpf_l4_csum_replace ||
4985 	    func == bpf_xdp_adjust_head ||
4986 	    func == bpf_xdp_adjust_meta ||
4987 	    func == bpf_msg_pull_data ||
4988 	    func == bpf_msg_push_data ||
4989 	    func == bpf_xdp_adjust_tail ||
4990 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4991 	    func == bpf_lwt_seg6_store_bytes ||
4992 	    func == bpf_lwt_seg6_adjust_srh ||
4993 	    func == bpf_lwt_seg6_action ||
4994 #endif
4995 	    func == bpf_lwt_push_encap)
4996 		return true;
4997 
4998 	return false;
4999 }
5000 
5001 static const struct bpf_func_proto *
5002 bpf_base_func_proto(enum bpf_func_id func_id)
5003 {
5004 	switch (func_id) {
5005 	case BPF_FUNC_map_lookup_elem:
5006 		return &bpf_map_lookup_elem_proto;
5007 	case BPF_FUNC_map_update_elem:
5008 		return &bpf_map_update_elem_proto;
5009 	case BPF_FUNC_map_delete_elem:
5010 		return &bpf_map_delete_elem_proto;
5011 	case BPF_FUNC_map_push_elem:
5012 		return &bpf_map_push_elem_proto;
5013 	case BPF_FUNC_map_pop_elem:
5014 		return &bpf_map_pop_elem_proto;
5015 	case BPF_FUNC_map_peek_elem:
5016 		return &bpf_map_peek_elem_proto;
5017 	case BPF_FUNC_get_prandom_u32:
5018 		return &bpf_get_prandom_u32_proto;
5019 	case BPF_FUNC_get_smp_processor_id:
5020 		return &bpf_get_raw_smp_processor_id_proto;
5021 	case BPF_FUNC_get_numa_node_id:
5022 		return &bpf_get_numa_node_id_proto;
5023 	case BPF_FUNC_tail_call:
5024 		return &bpf_tail_call_proto;
5025 	case BPF_FUNC_ktime_get_ns:
5026 		return &bpf_ktime_get_ns_proto;
5027 	case BPF_FUNC_trace_printk:
5028 		if (capable(CAP_SYS_ADMIN))
5029 			return bpf_get_trace_printk_proto();
5030 		/* else: fall through */
5031 	default:
5032 		return NULL;
5033 	}
5034 }
5035 
5036 static const struct bpf_func_proto *
5037 sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5038 {
5039 	switch (func_id) {
5040 	/* inet and inet6 sockets are created in a process
5041 	 * context so there is always a valid uid/gid
5042 	 */
5043 	case BPF_FUNC_get_current_uid_gid:
5044 		return &bpf_get_current_uid_gid_proto;
5045 	case BPF_FUNC_get_local_storage:
5046 		return &bpf_get_local_storage_proto;
5047 	default:
5048 		return bpf_base_func_proto(func_id);
5049 	}
5050 }
5051 
5052 static const struct bpf_func_proto *
5053 sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5054 {
5055 	switch (func_id) {
5056 	/* inet and inet6 sockets are created in a process
5057 	 * context so there is always a valid uid/gid
5058 	 */
5059 	case BPF_FUNC_get_current_uid_gid:
5060 		return &bpf_get_current_uid_gid_proto;
5061 	case BPF_FUNC_bind:
5062 		switch (prog->expected_attach_type) {
5063 		case BPF_CGROUP_INET4_CONNECT:
5064 		case BPF_CGROUP_INET6_CONNECT:
5065 			return &bpf_bind_proto;
5066 		default:
5067 			return NULL;
5068 		}
5069 	case BPF_FUNC_get_socket_cookie:
5070 		return &bpf_get_socket_cookie_sock_addr_proto;
5071 	case BPF_FUNC_get_local_storage:
5072 		return &bpf_get_local_storage_proto;
5073 	default:
5074 		return bpf_base_func_proto(func_id);
5075 	}
5076 }
5077 
5078 static const struct bpf_func_proto *
5079 sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5080 {
5081 	switch (func_id) {
5082 	case BPF_FUNC_skb_load_bytes:
5083 		return &bpf_skb_load_bytes_proto;
5084 	case BPF_FUNC_skb_load_bytes_relative:
5085 		return &bpf_skb_load_bytes_relative_proto;
5086 	case BPF_FUNC_get_socket_cookie:
5087 		return &bpf_get_socket_cookie_proto;
5088 	case BPF_FUNC_get_socket_uid:
5089 		return &bpf_get_socket_uid_proto;
5090 	default:
5091 		return bpf_base_func_proto(func_id);
5092 	}
5093 }
5094 
5095 static const struct bpf_func_proto *
5096 cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5097 {
5098 	switch (func_id) {
5099 	case BPF_FUNC_get_local_storage:
5100 		return &bpf_get_local_storage_proto;
5101 	default:
5102 		return sk_filter_func_proto(func_id, prog);
5103 	}
5104 }
5105 
5106 static const struct bpf_func_proto *
5107 tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5108 {
5109 	switch (func_id) {
5110 	case BPF_FUNC_skb_store_bytes:
5111 		return &bpf_skb_store_bytes_proto;
5112 	case BPF_FUNC_skb_load_bytes:
5113 		return &bpf_skb_load_bytes_proto;
5114 	case BPF_FUNC_skb_load_bytes_relative:
5115 		return &bpf_skb_load_bytes_relative_proto;
5116 	case BPF_FUNC_skb_pull_data:
5117 		return &bpf_skb_pull_data_proto;
5118 	case BPF_FUNC_csum_diff:
5119 		return &bpf_csum_diff_proto;
5120 	case BPF_FUNC_csum_update:
5121 		return &bpf_csum_update_proto;
5122 	case BPF_FUNC_l3_csum_replace:
5123 		return &bpf_l3_csum_replace_proto;
5124 	case BPF_FUNC_l4_csum_replace:
5125 		return &bpf_l4_csum_replace_proto;
5126 	case BPF_FUNC_clone_redirect:
5127 		return &bpf_clone_redirect_proto;
5128 	case BPF_FUNC_get_cgroup_classid:
5129 		return &bpf_get_cgroup_classid_proto;
5130 	case BPF_FUNC_skb_vlan_push:
5131 		return &bpf_skb_vlan_push_proto;
5132 	case BPF_FUNC_skb_vlan_pop:
5133 		return &bpf_skb_vlan_pop_proto;
5134 	case BPF_FUNC_skb_change_proto:
5135 		return &bpf_skb_change_proto_proto;
5136 	case BPF_FUNC_skb_change_type:
5137 		return &bpf_skb_change_type_proto;
5138 	case BPF_FUNC_skb_adjust_room:
5139 		return &bpf_skb_adjust_room_proto;
5140 	case BPF_FUNC_skb_change_tail:
5141 		return &bpf_skb_change_tail_proto;
5142 	case BPF_FUNC_skb_get_tunnel_key:
5143 		return &bpf_skb_get_tunnel_key_proto;
5144 	case BPF_FUNC_skb_set_tunnel_key:
5145 		return bpf_get_skb_set_tunnel_proto(func_id);
5146 	case BPF_FUNC_skb_get_tunnel_opt:
5147 		return &bpf_skb_get_tunnel_opt_proto;
5148 	case BPF_FUNC_skb_set_tunnel_opt:
5149 		return bpf_get_skb_set_tunnel_proto(func_id);
5150 	case BPF_FUNC_redirect:
5151 		return &bpf_redirect_proto;
5152 	case BPF_FUNC_get_route_realm:
5153 		return &bpf_get_route_realm_proto;
5154 	case BPF_FUNC_get_hash_recalc:
5155 		return &bpf_get_hash_recalc_proto;
5156 	case BPF_FUNC_set_hash_invalid:
5157 		return &bpf_set_hash_invalid_proto;
5158 	case BPF_FUNC_set_hash:
5159 		return &bpf_set_hash_proto;
5160 	case BPF_FUNC_perf_event_output:
5161 		return &bpf_skb_event_output_proto;
5162 	case BPF_FUNC_get_smp_processor_id:
5163 		return &bpf_get_smp_processor_id_proto;
5164 	case BPF_FUNC_skb_under_cgroup:
5165 		return &bpf_skb_under_cgroup_proto;
5166 	case BPF_FUNC_get_socket_cookie:
5167 		return &bpf_get_socket_cookie_proto;
5168 	case BPF_FUNC_get_socket_uid:
5169 		return &bpf_get_socket_uid_proto;
5170 	case BPF_FUNC_fib_lookup:
5171 		return &bpf_skb_fib_lookup_proto;
5172 #ifdef CONFIG_XFRM
5173 	case BPF_FUNC_skb_get_xfrm_state:
5174 		return &bpf_skb_get_xfrm_state_proto;
5175 #endif
5176 #ifdef CONFIG_SOCK_CGROUP_DATA
5177 	case BPF_FUNC_skb_cgroup_id:
5178 		return &bpf_skb_cgroup_id_proto;
5179 	case BPF_FUNC_skb_ancestor_cgroup_id:
5180 		return &bpf_skb_ancestor_cgroup_id_proto;
5181 #endif
5182 #ifdef CONFIG_INET
5183 	case BPF_FUNC_sk_lookup_tcp:
5184 		return &bpf_sk_lookup_tcp_proto;
5185 	case BPF_FUNC_sk_lookup_udp:
5186 		return &bpf_sk_lookup_udp_proto;
5187 	case BPF_FUNC_sk_release:
5188 		return &bpf_sk_release_proto;
5189 #endif
5190 	default:
5191 		return bpf_base_func_proto(func_id);
5192 	}
5193 }
5194 
5195 static const struct bpf_func_proto *
5196 xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5197 {
5198 	switch (func_id) {
5199 	case BPF_FUNC_perf_event_output:
5200 		return &bpf_xdp_event_output_proto;
5201 	case BPF_FUNC_get_smp_processor_id:
5202 		return &bpf_get_smp_processor_id_proto;
5203 	case BPF_FUNC_csum_diff:
5204 		return &bpf_csum_diff_proto;
5205 	case BPF_FUNC_xdp_adjust_head:
5206 		return &bpf_xdp_adjust_head_proto;
5207 	case BPF_FUNC_xdp_adjust_meta:
5208 		return &bpf_xdp_adjust_meta_proto;
5209 	case BPF_FUNC_redirect:
5210 		return &bpf_xdp_redirect_proto;
5211 	case BPF_FUNC_redirect_map:
5212 		return &bpf_xdp_redirect_map_proto;
5213 	case BPF_FUNC_xdp_adjust_tail:
5214 		return &bpf_xdp_adjust_tail_proto;
5215 	case BPF_FUNC_fib_lookup:
5216 		return &bpf_xdp_fib_lookup_proto;
5217 	default:
5218 		return bpf_base_func_proto(func_id);
5219 	}
5220 }
5221 
5222 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
5223 const struct bpf_func_proto bpf_sock_hash_update_proto __weak;
5224 
5225 static const struct bpf_func_proto *
5226 sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5227 {
5228 	switch (func_id) {
5229 	case BPF_FUNC_setsockopt:
5230 		return &bpf_setsockopt_proto;
5231 	case BPF_FUNC_getsockopt:
5232 		return &bpf_getsockopt_proto;
5233 	case BPF_FUNC_sock_ops_cb_flags_set:
5234 		return &bpf_sock_ops_cb_flags_set_proto;
5235 	case BPF_FUNC_sock_map_update:
5236 		return &bpf_sock_map_update_proto;
5237 	case BPF_FUNC_sock_hash_update:
5238 		return &bpf_sock_hash_update_proto;
5239 	case BPF_FUNC_get_socket_cookie:
5240 		return &bpf_get_socket_cookie_sock_ops_proto;
5241 	case BPF_FUNC_get_local_storage:
5242 		return &bpf_get_local_storage_proto;
5243 	default:
5244 		return bpf_base_func_proto(func_id);
5245 	}
5246 }
5247 
5248 const struct bpf_func_proto bpf_msg_redirect_map_proto __weak;
5249 const struct bpf_func_proto bpf_msg_redirect_hash_proto __weak;
5250 
5251 static const struct bpf_func_proto *
5252 sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5253 {
5254 	switch (func_id) {
5255 	case BPF_FUNC_msg_redirect_map:
5256 		return &bpf_msg_redirect_map_proto;
5257 	case BPF_FUNC_msg_redirect_hash:
5258 		return &bpf_msg_redirect_hash_proto;
5259 	case BPF_FUNC_msg_apply_bytes:
5260 		return &bpf_msg_apply_bytes_proto;
5261 	case BPF_FUNC_msg_cork_bytes:
5262 		return &bpf_msg_cork_bytes_proto;
5263 	case BPF_FUNC_msg_pull_data:
5264 		return &bpf_msg_pull_data_proto;
5265 	case BPF_FUNC_msg_push_data:
5266 		return &bpf_msg_push_data_proto;
5267 	default:
5268 		return bpf_base_func_proto(func_id);
5269 	}
5270 }
5271 
5272 const struct bpf_func_proto bpf_sk_redirect_map_proto __weak;
5273 const struct bpf_func_proto bpf_sk_redirect_hash_proto __weak;
5274 
5275 static const struct bpf_func_proto *
5276 sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5277 {
5278 	switch (func_id) {
5279 	case BPF_FUNC_skb_store_bytes:
5280 		return &bpf_skb_store_bytes_proto;
5281 	case BPF_FUNC_skb_load_bytes:
5282 		return &bpf_skb_load_bytes_proto;
5283 	case BPF_FUNC_skb_pull_data:
5284 		return &sk_skb_pull_data_proto;
5285 	case BPF_FUNC_skb_change_tail:
5286 		return &sk_skb_change_tail_proto;
5287 	case BPF_FUNC_skb_change_head:
5288 		return &sk_skb_change_head_proto;
5289 	case BPF_FUNC_get_socket_cookie:
5290 		return &bpf_get_socket_cookie_proto;
5291 	case BPF_FUNC_get_socket_uid:
5292 		return &bpf_get_socket_uid_proto;
5293 	case BPF_FUNC_sk_redirect_map:
5294 		return &bpf_sk_redirect_map_proto;
5295 	case BPF_FUNC_sk_redirect_hash:
5296 		return &bpf_sk_redirect_hash_proto;
5297 #ifdef CONFIG_INET
5298 	case BPF_FUNC_sk_lookup_tcp:
5299 		return &bpf_sk_lookup_tcp_proto;
5300 	case BPF_FUNC_sk_lookup_udp:
5301 		return &bpf_sk_lookup_udp_proto;
5302 	case BPF_FUNC_sk_release:
5303 		return &bpf_sk_release_proto;
5304 #endif
5305 	default:
5306 		return bpf_base_func_proto(func_id);
5307 	}
5308 }
5309 
5310 static const struct bpf_func_proto *
5311 flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5312 {
5313 	switch (func_id) {
5314 	case BPF_FUNC_skb_load_bytes:
5315 		return &bpf_skb_load_bytes_proto;
5316 	default:
5317 		return bpf_base_func_proto(func_id);
5318 	}
5319 }
5320 
5321 static const struct bpf_func_proto *
5322 lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5323 {
5324 	switch (func_id) {
5325 	case BPF_FUNC_skb_load_bytes:
5326 		return &bpf_skb_load_bytes_proto;
5327 	case BPF_FUNC_skb_pull_data:
5328 		return &bpf_skb_pull_data_proto;
5329 	case BPF_FUNC_csum_diff:
5330 		return &bpf_csum_diff_proto;
5331 	case BPF_FUNC_get_cgroup_classid:
5332 		return &bpf_get_cgroup_classid_proto;
5333 	case BPF_FUNC_get_route_realm:
5334 		return &bpf_get_route_realm_proto;
5335 	case BPF_FUNC_get_hash_recalc:
5336 		return &bpf_get_hash_recalc_proto;
5337 	case BPF_FUNC_perf_event_output:
5338 		return &bpf_skb_event_output_proto;
5339 	case BPF_FUNC_get_smp_processor_id:
5340 		return &bpf_get_smp_processor_id_proto;
5341 	case BPF_FUNC_skb_under_cgroup:
5342 		return &bpf_skb_under_cgroup_proto;
5343 	default:
5344 		return bpf_base_func_proto(func_id);
5345 	}
5346 }
5347 
5348 static const struct bpf_func_proto *
5349 lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5350 {
5351 	switch (func_id) {
5352 	case BPF_FUNC_lwt_push_encap:
5353 		return &bpf_lwt_push_encap_proto;
5354 	default:
5355 		return lwt_out_func_proto(func_id, prog);
5356 	}
5357 }
5358 
5359 static const struct bpf_func_proto *
5360 lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5361 {
5362 	switch (func_id) {
5363 	case BPF_FUNC_skb_get_tunnel_key:
5364 		return &bpf_skb_get_tunnel_key_proto;
5365 	case BPF_FUNC_skb_set_tunnel_key:
5366 		return bpf_get_skb_set_tunnel_proto(func_id);
5367 	case BPF_FUNC_skb_get_tunnel_opt:
5368 		return &bpf_skb_get_tunnel_opt_proto;
5369 	case BPF_FUNC_skb_set_tunnel_opt:
5370 		return bpf_get_skb_set_tunnel_proto(func_id);
5371 	case BPF_FUNC_redirect:
5372 		return &bpf_redirect_proto;
5373 	case BPF_FUNC_clone_redirect:
5374 		return &bpf_clone_redirect_proto;
5375 	case BPF_FUNC_skb_change_tail:
5376 		return &bpf_skb_change_tail_proto;
5377 	case BPF_FUNC_skb_change_head:
5378 		return &bpf_skb_change_head_proto;
5379 	case BPF_FUNC_skb_store_bytes:
5380 		return &bpf_skb_store_bytes_proto;
5381 	case BPF_FUNC_csum_update:
5382 		return &bpf_csum_update_proto;
5383 	case BPF_FUNC_l3_csum_replace:
5384 		return &bpf_l3_csum_replace_proto;
5385 	case BPF_FUNC_l4_csum_replace:
5386 		return &bpf_l4_csum_replace_proto;
5387 	case BPF_FUNC_set_hash_invalid:
5388 		return &bpf_set_hash_invalid_proto;
5389 	default:
5390 		return lwt_out_func_proto(func_id, prog);
5391 	}
5392 }
5393 
5394 static const struct bpf_func_proto *
5395 lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5396 {
5397 	switch (func_id) {
5398 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
5399 	case BPF_FUNC_lwt_seg6_store_bytes:
5400 		return &bpf_lwt_seg6_store_bytes_proto;
5401 	case BPF_FUNC_lwt_seg6_action:
5402 		return &bpf_lwt_seg6_action_proto;
5403 	case BPF_FUNC_lwt_seg6_adjust_srh:
5404 		return &bpf_lwt_seg6_adjust_srh_proto;
5405 #endif
5406 	default:
5407 		return lwt_out_func_proto(func_id, prog);
5408 	}
5409 }
5410 
5411 static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
5412 				    const struct bpf_prog *prog,
5413 				    struct bpf_insn_access_aux *info)
5414 {
5415 	const int size_default = sizeof(__u32);
5416 
5417 	if (off < 0 || off >= sizeof(struct __sk_buff))
5418 		return false;
5419 
5420 	/* The verifier guarantees that size > 0. */
5421 	if (off % size != 0)
5422 		return false;
5423 
5424 	switch (off) {
5425 	case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5426 		if (off + size > offsetofend(struct __sk_buff, cb[4]))
5427 			return false;
5428 		break;
5429 	case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
5430 	case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
5431 	case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
5432 	case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
5433 	case bpf_ctx_range(struct __sk_buff, data):
5434 	case bpf_ctx_range(struct __sk_buff, data_meta):
5435 	case bpf_ctx_range(struct __sk_buff, data_end):
5436 		if (size != size_default)
5437 			return false;
5438 		break;
5439 	case bpf_ctx_range(struct __sk_buff, flow_keys):
5440 		if (size != sizeof(struct bpf_flow_keys *))
5441 			return false;
5442 		break;
5443 	default:
5444 		/* Only narrow read access allowed for now. */
5445 		if (type == BPF_WRITE) {
5446 			if (size != size_default)
5447 				return false;
5448 		} else {
5449 			bpf_ctx_record_field_size(info, size_default);
5450 			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
5451 				return false;
5452 		}
5453 	}
5454 
5455 	return true;
5456 }
5457 
5458 static bool sk_filter_is_valid_access(int off, int size,
5459 				      enum bpf_access_type type,
5460 				      const struct bpf_prog *prog,
5461 				      struct bpf_insn_access_aux *info)
5462 {
5463 	switch (off) {
5464 	case bpf_ctx_range(struct __sk_buff, tc_classid):
5465 	case bpf_ctx_range(struct __sk_buff, data):
5466 	case bpf_ctx_range(struct __sk_buff, data_meta):
5467 	case bpf_ctx_range(struct __sk_buff, data_end):
5468 	case bpf_ctx_range(struct __sk_buff, flow_keys):
5469 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
5470 		return false;
5471 	}
5472 
5473 	if (type == BPF_WRITE) {
5474 		switch (off) {
5475 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5476 			break;
5477 		default:
5478 			return false;
5479 		}
5480 	}
5481 
5482 	return bpf_skb_is_valid_access(off, size, type, prog, info);
5483 }
5484 
5485 static bool cg_skb_is_valid_access(int off, int size,
5486 				   enum bpf_access_type type,
5487 				   const struct bpf_prog *prog,
5488 				   struct bpf_insn_access_aux *info)
5489 {
5490 	switch (off) {
5491 	case bpf_ctx_range(struct __sk_buff, tc_classid):
5492 	case bpf_ctx_range(struct __sk_buff, data_meta):
5493 	case bpf_ctx_range(struct __sk_buff, flow_keys):
5494 		return false;
5495 	case bpf_ctx_range(struct __sk_buff, data):
5496 	case bpf_ctx_range(struct __sk_buff, data_end):
5497 		if (!capable(CAP_SYS_ADMIN))
5498 			return false;
5499 		break;
5500 	}
5501 
5502 	if (type == BPF_WRITE) {
5503 		switch (off) {
5504 		case bpf_ctx_range(struct __sk_buff, mark):
5505 		case bpf_ctx_range(struct __sk_buff, priority):
5506 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5507 			break;
5508 		default:
5509 			return false;
5510 		}
5511 	}
5512 
5513 	switch (off) {
5514 	case bpf_ctx_range(struct __sk_buff, data):
5515 		info->reg_type = PTR_TO_PACKET;
5516 		break;
5517 	case bpf_ctx_range(struct __sk_buff, data_end):
5518 		info->reg_type = PTR_TO_PACKET_END;
5519 		break;
5520 	}
5521 
5522 	return bpf_skb_is_valid_access(off, size, type, prog, info);
5523 }
5524 
5525 static bool lwt_is_valid_access(int off, int size,
5526 				enum bpf_access_type type,
5527 				const struct bpf_prog *prog,
5528 				struct bpf_insn_access_aux *info)
5529 {
5530 	switch (off) {
5531 	case bpf_ctx_range(struct __sk_buff, tc_classid):
5532 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
5533 	case bpf_ctx_range(struct __sk_buff, data_meta):
5534 	case bpf_ctx_range(struct __sk_buff, flow_keys):
5535 		return false;
5536 	}
5537 
5538 	if (type == BPF_WRITE) {
5539 		switch (off) {
5540 		case bpf_ctx_range(struct __sk_buff, mark):
5541 		case bpf_ctx_range(struct __sk_buff, priority):
5542 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5543 			break;
5544 		default:
5545 			return false;
5546 		}
5547 	}
5548 
5549 	switch (off) {
5550 	case bpf_ctx_range(struct __sk_buff, data):
5551 		info->reg_type = PTR_TO_PACKET;
5552 		break;
5553 	case bpf_ctx_range(struct __sk_buff, data_end):
5554 		info->reg_type = PTR_TO_PACKET_END;
5555 		break;
5556 	}
5557 
5558 	return bpf_skb_is_valid_access(off, size, type, prog, info);
5559 }
5560 
5561 /* Attach type specific accesses */
5562 static bool __sock_filter_check_attach_type(int off,
5563 					    enum bpf_access_type access_type,
5564 					    enum bpf_attach_type attach_type)
5565 {
5566 	switch (off) {
5567 	case offsetof(struct bpf_sock, bound_dev_if):
5568 	case offsetof(struct bpf_sock, mark):
5569 	case offsetof(struct bpf_sock, priority):
5570 		switch (attach_type) {
5571 		case BPF_CGROUP_INET_SOCK_CREATE:
5572 			goto full_access;
5573 		default:
5574 			return false;
5575 		}
5576 	case bpf_ctx_range(struct bpf_sock, src_ip4):
5577 		switch (attach_type) {
5578 		case BPF_CGROUP_INET4_POST_BIND:
5579 			goto read_only;
5580 		default:
5581 			return false;
5582 		}
5583 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
5584 		switch (attach_type) {
5585 		case BPF_CGROUP_INET6_POST_BIND:
5586 			goto read_only;
5587 		default:
5588 			return false;
5589 		}
5590 	case bpf_ctx_range(struct bpf_sock, src_port):
5591 		switch (attach_type) {
5592 		case BPF_CGROUP_INET4_POST_BIND:
5593 		case BPF_CGROUP_INET6_POST_BIND:
5594 			goto read_only;
5595 		default:
5596 			return false;
5597 		}
5598 	}
5599 read_only:
5600 	return access_type == BPF_READ;
5601 full_access:
5602 	return true;
5603 }
5604 
5605 static bool __sock_filter_check_size(int off, int size,
5606 				     struct bpf_insn_access_aux *info)
5607 {
5608 	const int size_default = sizeof(__u32);
5609 
5610 	switch (off) {
5611 	case bpf_ctx_range(struct bpf_sock, src_ip4):
5612 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
5613 		bpf_ctx_record_field_size(info, size_default);
5614 		return bpf_ctx_narrow_access_ok(off, size, size_default);
5615 	}
5616 
5617 	return size == size_default;
5618 }
5619 
5620 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
5621 			      struct bpf_insn_access_aux *info)
5622 {
5623 	if (off < 0 || off >= sizeof(struct bpf_sock))
5624 		return false;
5625 	if (off % size != 0)
5626 		return false;
5627 	if (!__sock_filter_check_size(off, size, info))
5628 		return false;
5629 	return true;
5630 }
5631 
5632 static bool sock_filter_is_valid_access(int off, int size,
5633 					enum bpf_access_type type,
5634 					const struct bpf_prog *prog,
5635 					struct bpf_insn_access_aux *info)
5636 {
5637 	if (!bpf_sock_is_valid_access(off, size, type, info))
5638 		return false;
5639 	return __sock_filter_check_attach_type(off, type,
5640 					       prog->expected_attach_type);
5641 }
5642 
5643 static int bpf_noop_prologue(struct bpf_insn *insn_buf, bool direct_write,
5644 			     const struct bpf_prog *prog)
5645 {
5646 	/* Neither direct read nor direct write requires any preliminary
5647 	 * action.
5648 	 */
5649 	return 0;
5650 }
5651 
5652 static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
5653 				const struct bpf_prog *prog, int drop_verdict)
5654 {
5655 	struct bpf_insn *insn = insn_buf;
5656 
5657 	if (!direct_write)
5658 		return 0;
5659 
5660 	/* if (!skb->cloned)
5661 	 *       goto start;
5662 	 *
5663 	 * (Fast-path, otherwise approximation that we might be
5664 	 *  a clone, do the rest in helper.)
5665 	 */
5666 	*insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET());
5667 	*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
5668 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
5669 
5670 	/* ret = bpf_skb_pull_data(skb, 0); */
5671 	*insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
5672 	*insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
5673 	*insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
5674 			       BPF_FUNC_skb_pull_data);
5675 	/* if (!ret)
5676 	 *      goto restore;
5677 	 * return TC_ACT_SHOT;
5678 	 */
5679 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
5680 	*insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
5681 	*insn++ = BPF_EXIT_INSN();
5682 
5683 	/* restore: */
5684 	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
5685 	/* start: */
5686 	*insn++ = prog->insnsi[0];
5687 
5688 	return insn - insn_buf;
5689 }
5690 
5691 static int bpf_gen_ld_abs(const struct bpf_insn *orig,
5692 			  struct bpf_insn *insn_buf)
5693 {
5694 	bool indirect = BPF_MODE(orig->code) == BPF_IND;
5695 	struct bpf_insn *insn = insn_buf;
5696 
5697 	/* We're guaranteed here that CTX is in R6. */
5698 	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
5699 	if (!indirect) {
5700 		*insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
5701 	} else {
5702 		*insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
5703 		if (orig->imm)
5704 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
5705 	}
5706 
5707 	switch (BPF_SIZE(orig->code)) {
5708 	case BPF_B:
5709 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
5710 		break;
5711 	case BPF_H:
5712 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
5713 		break;
5714 	case BPF_W:
5715 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
5716 		break;
5717 	}
5718 
5719 	*insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
5720 	*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
5721 	*insn++ = BPF_EXIT_INSN();
5722 
5723 	return insn - insn_buf;
5724 }
5725 
5726 static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
5727 			       const struct bpf_prog *prog)
5728 {
5729 	return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
5730 }
5731 
5732 static bool tc_cls_act_is_valid_access(int off, int size,
5733 				       enum bpf_access_type type,
5734 				       const struct bpf_prog *prog,
5735 				       struct bpf_insn_access_aux *info)
5736 {
5737 	if (type == BPF_WRITE) {
5738 		switch (off) {
5739 		case bpf_ctx_range(struct __sk_buff, mark):
5740 		case bpf_ctx_range(struct __sk_buff, tc_index):
5741 		case bpf_ctx_range(struct __sk_buff, priority):
5742 		case bpf_ctx_range(struct __sk_buff, tc_classid):
5743 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5744 			break;
5745 		default:
5746 			return false;
5747 		}
5748 	}
5749 
5750 	switch (off) {
5751 	case bpf_ctx_range(struct __sk_buff, data):
5752 		info->reg_type = PTR_TO_PACKET;
5753 		break;
5754 	case bpf_ctx_range(struct __sk_buff, data_meta):
5755 		info->reg_type = PTR_TO_PACKET_META;
5756 		break;
5757 	case bpf_ctx_range(struct __sk_buff, data_end):
5758 		info->reg_type = PTR_TO_PACKET_END;
5759 		break;
5760 	case bpf_ctx_range(struct __sk_buff, flow_keys):
5761 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
5762 		return false;
5763 	}
5764 
5765 	return bpf_skb_is_valid_access(off, size, type, prog, info);
5766 }
5767 
5768 static bool __is_valid_xdp_access(int off, int size)
5769 {
5770 	if (off < 0 || off >= sizeof(struct xdp_md))
5771 		return false;
5772 	if (off % size != 0)
5773 		return false;
5774 	if (size != sizeof(__u32))
5775 		return false;
5776 
5777 	return true;
5778 }
5779 
5780 static bool xdp_is_valid_access(int off, int size,
5781 				enum bpf_access_type type,
5782 				const struct bpf_prog *prog,
5783 				struct bpf_insn_access_aux *info)
5784 {
5785 	if (type == BPF_WRITE) {
5786 		if (bpf_prog_is_dev_bound(prog->aux)) {
5787 			switch (off) {
5788 			case offsetof(struct xdp_md, rx_queue_index):
5789 				return __is_valid_xdp_access(off, size);
5790 			}
5791 		}
5792 		return false;
5793 	}
5794 
5795 	switch (off) {
5796 	case offsetof(struct xdp_md, data):
5797 		info->reg_type = PTR_TO_PACKET;
5798 		break;
5799 	case offsetof(struct xdp_md, data_meta):
5800 		info->reg_type = PTR_TO_PACKET_META;
5801 		break;
5802 	case offsetof(struct xdp_md, data_end):
5803 		info->reg_type = PTR_TO_PACKET_END;
5804 		break;
5805 	}
5806 
5807 	return __is_valid_xdp_access(off, size);
5808 }
5809 
5810 void bpf_warn_invalid_xdp_action(u32 act)
5811 {
5812 	const u32 act_max = XDP_REDIRECT;
5813 
5814 	WARN_ONCE(1, "%s XDP return value %u, expect packet loss!\n",
5815 		  act > act_max ? "Illegal" : "Driver unsupported",
5816 		  act);
5817 }
5818 EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
5819 
5820 static bool sock_addr_is_valid_access(int off, int size,
5821 				      enum bpf_access_type type,
5822 				      const struct bpf_prog *prog,
5823 				      struct bpf_insn_access_aux *info)
5824 {
5825 	const int size_default = sizeof(__u32);
5826 
5827 	if (off < 0 || off >= sizeof(struct bpf_sock_addr))
5828 		return false;
5829 	if (off % size != 0)
5830 		return false;
5831 
5832 	/* Disallow access to IPv6 fields from IPv4 contex and vise
5833 	 * versa.
5834 	 */
5835 	switch (off) {
5836 	case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
5837 		switch (prog->expected_attach_type) {
5838 		case BPF_CGROUP_INET4_BIND:
5839 		case BPF_CGROUP_INET4_CONNECT:
5840 		case BPF_CGROUP_UDP4_SENDMSG:
5841 			break;
5842 		default:
5843 			return false;
5844 		}
5845 		break;
5846 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
5847 		switch (prog->expected_attach_type) {
5848 		case BPF_CGROUP_INET6_BIND:
5849 		case BPF_CGROUP_INET6_CONNECT:
5850 		case BPF_CGROUP_UDP6_SENDMSG:
5851 			break;
5852 		default:
5853 			return false;
5854 		}
5855 		break;
5856 	case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
5857 		switch (prog->expected_attach_type) {
5858 		case BPF_CGROUP_UDP4_SENDMSG:
5859 			break;
5860 		default:
5861 			return false;
5862 		}
5863 		break;
5864 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
5865 				msg_src_ip6[3]):
5866 		switch (prog->expected_attach_type) {
5867 		case BPF_CGROUP_UDP6_SENDMSG:
5868 			break;
5869 		default:
5870 			return false;
5871 		}
5872 		break;
5873 	}
5874 
5875 	switch (off) {
5876 	case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
5877 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
5878 	case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
5879 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
5880 				msg_src_ip6[3]):
5881 		/* Only narrow read access allowed for now. */
5882 		if (type == BPF_READ) {
5883 			bpf_ctx_record_field_size(info, size_default);
5884 			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
5885 				return false;
5886 		} else {
5887 			if (size != size_default)
5888 				return false;
5889 		}
5890 		break;
5891 	case bpf_ctx_range(struct bpf_sock_addr, user_port):
5892 		if (size != size_default)
5893 			return false;
5894 		break;
5895 	default:
5896 		if (type == BPF_READ) {
5897 			if (size != size_default)
5898 				return false;
5899 		} else {
5900 			return false;
5901 		}
5902 	}
5903 
5904 	return true;
5905 }
5906 
5907 static bool sock_ops_is_valid_access(int off, int size,
5908 				     enum bpf_access_type type,
5909 				     const struct bpf_prog *prog,
5910 				     struct bpf_insn_access_aux *info)
5911 {
5912 	const int size_default = sizeof(__u32);
5913 
5914 	if (off < 0 || off >= sizeof(struct bpf_sock_ops))
5915 		return false;
5916 
5917 	/* The verifier guarantees that size > 0. */
5918 	if (off % size != 0)
5919 		return false;
5920 
5921 	if (type == BPF_WRITE) {
5922 		switch (off) {
5923 		case offsetof(struct bpf_sock_ops, reply):
5924 		case offsetof(struct bpf_sock_ops, sk_txhash):
5925 			if (size != size_default)
5926 				return false;
5927 			break;
5928 		default:
5929 			return false;
5930 		}
5931 	} else {
5932 		switch (off) {
5933 		case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received,
5934 					bytes_acked):
5935 			if (size != sizeof(__u64))
5936 				return false;
5937 			break;
5938 		default:
5939 			if (size != size_default)
5940 				return false;
5941 			break;
5942 		}
5943 	}
5944 
5945 	return true;
5946 }
5947 
5948 static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
5949 			   const struct bpf_prog *prog)
5950 {
5951 	return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
5952 }
5953 
5954 static bool sk_skb_is_valid_access(int off, int size,
5955 				   enum bpf_access_type type,
5956 				   const struct bpf_prog *prog,
5957 				   struct bpf_insn_access_aux *info)
5958 {
5959 	switch (off) {
5960 	case bpf_ctx_range(struct __sk_buff, tc_classid):
5961 	case bpf_ctx_range(struct __sk_buff, data_meta):
5962 	case bpf_ctx_range(struct __sk_buff, flow_keys):
5963 		return false;
5964 	}
5965 
5966 	if (type == BPF_WRITE) {
5967 		switch (off) {
5968 		case bpf_ctx_range(struct __sk_buff, tc_index):
5969 		case bpf_ctx_range(struct __sk_buff, priority):
5970 			break;
5971 		default:
5972 			return false;
5973 		}
5974 	}
5975 
5976 	switch (off) {
5977 	case bpf_ctx_range(struct __sk_buff, mark):
5978 		return false;
5979 	case bpf_ctx_range(struct __sk_buff, data):
5980 		info->reg_type = PTR_TO_PACKET;
5981 		break;
5982 	case bpf_ctx_range(struct __sk_buff, data_end):
5983 		info->reg_type = PTR_TO_PACKET_END;
5984 		break;
5985 	}
5986 
5987 	return bpf_skb_is_valid_access(off, size, type, prog, info);
5988 }
5989 
5990 static bool sk_msg_is_valid_access(int off, int size,
5991 				   enum bpf_access_type type,
5992 				   const struct bpf_prog *prog,
5993 				   struct bpf_insn_access_aux *info)
5994 {
5995 	if (type == BPF_WRITE)
5996 		return false;
5997 
5998 	switch (off) {
5999 	case offsetof(struct sk_msg_md, data):
6000 		info->reg_type = PTR_TO_PACKET;
6001 		if (size != sizeof(__u64))
6002 			return false;
6003 		break;
6004 	case offsetof(struct sk_msg_md, data_end):
6005 		info->reg_type = PTR_TO_PACKET_END;
6006 		if (size != sizeof(__u64))
6007 			return false;
6008 		break;
6009 	default:
6010 		if (size != sizeof(__u32))
6011 			return false;
6012 	}
6013 
6014 	if (off < 0 || off >= sizeof(struct sk_msg_md))
6015 		return false;
6016 	if (off % size != 0)
6017 		return false;
6018 
6019 	return true;
6020 }
6021 
6022 static bool flow_dissector_is_valid_access(int off, int size,
6023 					   enum bpf_access_type type,
6024 					   const struct bpf_prog *prog,
6025 					   struct bpf_insn_access_aux *info)
6026 {
6027 	if (type == BPF_WRITE) {
6028 		switch (off) {
6029 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6030 			break;
6031 		default:
6032 			return false;
6033 		}
6034 	}
6035 
6036 	switch (off) {
6037 	case bpf_ctx_range(struct __sk_buff, data):
6038 		info->reg_type = PTR_TO_PACKET;
6039 		break;
6040 	case bpf_ctx_range(struct __sk_buff, data_end):
6041 		info->reg_type = PTR_TO_PACKET_END;
6042 		break;
6043 	case bpf_ctx_range(struct __sk_buff, flow_keys):
6044 		info->reg_type = PTR_TO_FLOW_KEYS;
6045 		break;
6046 	case bpf_ctx_range(struct __sk_buff, tc_classid):
6047 	case bpf_ctx_range(struct __sk_buff, data_meta):
6048 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6049 		return false;
6050 	}
6051 
6052 	return bpf_skb_is_valid_access(off, size, type, prog, info);
6053 }
6054 
6055 static u32 bpf_convert_ctx_access(enum bpf_access_type type,
6056 				  const struct bpf_insn *si,
6057 				  struct bpf_insn *insn_buf,
6058 				  struct bpf_prog *prog, u32 *target_size)
6059 {
6060 	struct bpf_insn *insn = insn_buf;
6061 	int off;
6062 
6063 	switch (si->off) {
6064 	case offsetof(struct __sk_buff, len):
6065 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6066 				      bpf_target_off(struct sk_buff, len, 4,
6067 						     target_size));
6068 		break;
6069 
6070 	case offsetof(struct __sk_buff, protocol):
6071 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
6072 				      bpf_target_off(struct sk_buff, protocol, 2,
6073 						     target_size));
6074 		break;
6075 
6076 	case offsetof(struct __sk_buff, vlan_proto):
6077 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
6078 				      bpf_target_off(struct sk_buff, vlan_proto, 2,
6079 						     target_size));
6080 		break;
6081 
6082 	case offsetof(struct __sk_buff, priority):
6083 		if (type == BPF_WRITE)
6084 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6085 					      bpf_target_off(struct sk_buff, priority, 4,
6086 							     target_size));
6087 		else
6088 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6089 					      bpf_target_off(struct sk_buff, priority, 4,
6090 							     target_size));
6091 		break;
6092 
6093 	case offsetof(struct __sk_buff, ingress_ifindex):
6094 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6095 				      bpf_target_off(struct sk_buff, skb_iif, 4,
6096 						     target_size));
6097 		break;
6098 
6099 	case offsetof(struct __sk_buff, ifindex):
6100 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
6101 				      si->dst_reg, si->src_reg,
6102 				      offsetof(struct sk_buff, dev));
6103 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
6104 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6105 				      bpf_target_off(struct net_device, ifindex, 4,
6106 						     target_size));
6107 		break;
6108 
6109 	case offsetof(struct __sk_buff, hash):
6110 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6111 				      bpf_target_off(struct sk_buff, hash, 4,
6112 						     target_size));
6113 		break;
6114 
6115 	case offsetof(struct __sk_buff, mark):
6116 		if (type == BPF_WRITE)
6117 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6118 					      bpf_target_off(struct sk_buff, mark, 4,
6119 							     target_size));
6120 		else
6121 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6122 					      bpf_target_off(struct sk_buff, mark, 4,
6123 							     target_size));
6124 		break;
6125 
6126 	case offsetof(struct __sk_buff, pkt_type):
6127 		*target_size = 1;
6128 		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
6129 				      PKT_TYPE_OFFSET());
6130 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
6131 #ifdef __BIG_ENDIAN_BITFIELD
6132 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
6133 #endif
6134 		break;
6135 
6136 	case offsetof(struct __sk_buff, queue_mapping):
6137 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
6138 				      bpf_target_off(struct sk_buff, queue_mapping, 2,
6139 						     target_size));
6140 		break;
6141 
6142 	case offsetof(struct __sk_buff, vlan_present):
6143 	case offsetof(struct __sk_buff, vlan_tci):
6144 		BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);
6145 
6146 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
6147 				      bpf_target_off(struct sk_buff, vlan_tci, 2,
6148 						     target_size));
6149 		if (si->off == offsetof(struct __sk_buff, vlan_tci)) {
6150 			*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg,
6151 						~VLAN_TAG_PRESENT);
6152 		} else {
6153 			*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 12);
6154 			*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1);
6155 		}
6156 		break;
6157 
6158 	case offsetof(struct __sk_buff, cb[0]) ...
6159 	     offsetofend(struct __sk_buff, cb[4]) - 1:
6160 		BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);
6161 		BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
6162 			      offsetof(struct qdisc_skb_cb, data)) %
6163 			     sizeof(__u64));
6164 
6165 		prog->cb_access = 1;
6166 		off  = si->off;
6167 		off -= offsetof(struct __sk_buff, cb[0]);
6168 		off += offsetof(struct sk_buff, cb);
6169 		off += offsetof(struct qdisc_skb_cb, data);
6170 		if (type == BPF_WRITE)
6171 			*insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
6172 					      si->src_reg, off);
6173 		else
6174 			*insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
6175 					      si->src_reg, off);
6176 		break;
6177 
6178 	case offsetof(struct __sk_buff, tc_classid):
6179 		BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, tc_classid) != 2);
6180 
6181 		off  = si->off;
6182 		off -= offsetof(struct __sk_buff, tc_classid);
6183 		off += offsetof(struct sk_buff, cb);
6184 		off += offsetof(struct qdisc_skb_cb, tc_classid);
6185 		*target_size = 2;
6186 		if (type == BPF_WRITE)
6187 			*insn++ = BPF_STX_MEM(BPF_H, si->dst_reg,
6188 					      si->src_reg, off);
6189 		else
6190 			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
6191 					      si->src_reg, off);
6192 		break;
6193 
6194 	case offsetof(struct __sk_buff, data):
6195 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
6196 				      si->dst_reg, si->src_reg,
6197 				      offsetof(struct sk_buff, data));
6198 		break;
6199 
6200 	case offsetof(struct __sk_buff, data_meta):
6201 		off  = si->off;
6202 		off -= offsetof(struct __sk_buff, data_meta);
6203 		off += offsetof(struct sk_buff, cb);
6204 		off += offsetof(struct bpf_skb_data_end, data_meta);
6205 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
6206 				      si->src_reg, off);
6207 		break;
6208 
6209 	case offsetof(struct __sk_buff, data_end):
6210 		off  = si->off;
6211 		off -= offsetof(struct __sk_buff, data_end);
6212 		off += offsetof(struct sk_buff, cb);
6213 		off += offsetof(struct bpf_skb_data_end, data_end);
6214 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
6215 				      si->src_reg, off);
6216 		break;
6217 
6218 	case offsetof(struct __sk_buff, tc_index):
6219 #ifdef CONFIG_NET_SCHED
6220 		if (type == BPF_WRITE)
6221 			*insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
6222 					      bpf_target_off(struct sk_buff, tc_index, 2,
6223 							     target_size));
6224 		else
6225 			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
6226 					      bpf_target_off(struct sk_buff, tc_index, 2,
6227 							     target_size));
6228 #else
6229 		*target_size = 2;
6230 		if (type == BPF_WRITE)
6231 			*insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
6232 		else
6233 			*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
6234 #endif
6235 		break;
6236 
6237 	case offsetof(struct __sk_buff, napi_id):
6238 #if defined(CONFIG_NET_RX_BUSY_POLL)
6239 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6240 				      bpf_target_off(struct sk_buff, napi_id, 4,
6241 						     target_size));
6242 		*insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
6243 		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
6244 #else
6245 		*target_size = 4;
6246 		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
6247 #endif
6248 		break;
6249 	case offsetof(struct __sk_buff, family):
6250 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
6251 
6252 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
6253 				      si->dst_reg, si->src_reg,
6254 				      offsetof(struct sk_buff, sk));
6255 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6256 				      bpf_target_off(struct sock_common,
6257 						     skc_family,
6258 						     2, target_size));
6259 		break;
6260 	case offsetof(struct __sk_buff, remote_ip4):
6261 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
6262 
6263 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
6264 				      si->dst_reg, si->src_reg,
6265 				      offsetof(struct sk_buff, sk));
6266 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6267 				      bpf_target_off(struct sock_common,
6268 						     skc_daddr,
6269 						     4, target_size));
6270 		break;
6271 	case offsetof(struct __sk_buff, local_ip4):
6272 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6273 					  skc_rcv_saddr) != 4);
6274 
6275 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
6276 				      si->dst_reg, si->src_reg,
6277 				      offsetof(struct sk_buff, sk));
6278 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6279 				      bpf_target_off(struct sock_common,
6280 						     skc_rcv_saddr,
6281 						     4, target_size));
6282 		break;
6283 	case offsetof(struct __sk_buff, remote_ip6[0]) ...
6284 	     offsetof(struct __sk_buff, remote_ip6[3]):
6285 #if IS_ENABLED(CONFIG_IPV6)
6286 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6287 					  skc_v6_daddr.s6_addr32[0]) != 4);
6288 
6289 		off = si->off;
6290 		off -= offsetof(struct __sk_buff, remote_ip6[0]);
6291 
6292 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
6293 				      si->dst_reg, si->src_reg,
6294 				      offsetof(struct sk_buff, sk));
6295 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6296 				      offsetof(struct sock_common,
6297 					       skc_v6_daddr.s6_addr32[0]) +
6298 				      off);
6299 #else
6300 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
6301 #endif
6302 		break;
6303 	case offsetof(struct __sk_buff, local_ip6[0]) ...
6304 	     offsetof(struct __sk_buff, local_ip6[3]):
6305 #if IS_ENABLED(CONFIG_IPV6)
6306 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6307 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
6308 
6309 		off = si->off;
6310 		off -= offsetof(struct __sk_buff, local_ip6[0]);
6311 
6312 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
6313 				      si->dst_reg, si->src_reg,
6314 				      offsetof(struct sk_buff, sk));
6315 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6316 				      offsetof(struct sock_common,
6317 					       skc_v6_rcv_saddr.s6_addr32[0]) +
6318 				      off);
6319 #else
6320 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
6321 #endif
6322 		break;
6323 
6324 	case offsetof(struct __sk_buff, remote_port):
6325 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
6326 
6327 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
6328 				      si->dst_reg, si->src_reg,
6329 				      offsetof(struct sk_buff, sk));
6330 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6331 				      bpf_target_off(struct sock_common,
6332 						     skc_dport,
6333 						     2, target_size));
6334 #ifndef __BIG_ENDIAN_BITFIELD
6335 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
6336 #endif
6337 		break;
6338 
6339 	case offsetof(struct __sk_buff, local_port):
6340 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
6341 
6342 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
6343 				      si->dst_reg, si->src_reg,
6344 				      offsetof(struct sk_buff, sk));
6345 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6346 				      bpf_target_off(struct sock_common,
6347 						     skc_num, 2, target_size));
6348 		break;
6349 
6350 	case offsetof(struct __sk_buff, flow_keys):
6351 		off  = si->off;
6352 		off -= offsetof(struct __sk_buff, flow_keys);
6353 		off += offsetof(struct sk_buff, cb);
6354 		off += offsetof(struct qdisc_skb_cb, flow_keys);
6355 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
6356 				      si->src_reg, off);
6357 		break;
6358 	}
6359 
6360 	return insn - insn_buf;
6361 }
6362 
6363 u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
6364 				const struct bpf_insn *si,
6365 				struct bpf_insn *insn_buf,
6366 				struct bpf_prog *prog, u32 *target_size)
6367 {
6368 	struct bpf_insn *insn = insn_buf;
6369 	int off;
6370 
6371 	switch (si->off) {
6372 	case offsetof(struct bpf_sock, bound_dev_if):
6373 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_bound_dev_if) != 4);
6374 
6375 		if (type == BPF_WRITE)
6376 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6377 					offsetof(struct sock, sk_bound_dev_if));
6378 		else
6379 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6380 				      offsetof(struct sock, sk_bound_dev_if));
6381 		break;
6382 
6383 	case offsetof(struct bpf_sock, mark):
6384 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_mark) != 4);
6385 
6386 		if (type == BPF_WRITE)
6387 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6388 					offsetof(struct sock, sk_mark));
6389 		else
6390 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6391 				      offsetof(struct sock, sk_mark));
6392 		break;
6393 
6394 	case offsetof(struct bpf_sock, priority):
6395 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_priority) != 4);
6396 
6397 		if (type == BPF_WRITE)
6398 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6399 					offsetof(struct sock, sk_priority));
6400 		else
6401 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6402 				      offsetof(struct sock, sk_priority));
6403 		break;
6404 
6405 	case offsetof(struct bpf_sock, family):
6406 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_family) != 2);
6407 
6408 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
6409 				      offsetof(struct sock, sk_family));
6410 		break;
6411 
6412 	case offsetof(struct bpf_sock, type):
6413 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6414 				      offsetof(struct sock, __sk_flags_offset));
6415 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
6416 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
6417 		break;
6418 
6419 	case offsetof(struct bpf_sock, protocol):
6420 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6421 				      offsetof(struct sock, __sk_flags_offset));
6422 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
6423 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT);
6424 		break;
6425 
6426 	case offsetof(struct bpf_sock, src_ip4):
6427 		*insn++ = BPF_LDX_MEM(
6428 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
6429 			bpf_target_off(struct sock_common, skc_rcv_saddr,
6430 				       FIELD_SIZEOF(struct sock_common,
6431 						    skc_rcv_saddr),
6432 				       target_size));
6433 		break;
6434 
6435 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6436 #if IS_ENABLED(CONFIG_IPV6)
6437 		off = si->off;
6438 		off -= offsetof(struct bpf_sock, src_ip6[0]);
6439 		*insn++ = BPF_LDX_MEM(
6440 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
6441 			bpf_target_off(
6442 				struct sock_common,
6443 				skc_v6_rcv_saddr.s6_addr32[0],
6444 				FIELD_SIZEOF(struct sock_common,
6445 					     skc_v6_rcv_saddr.s6_addr32[0]),
6446 				target_size) + off);
6447 #else
6448 		(void)off;
6449 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
6450 #endif
6451 		break;
6452 
6453 	case offsetof(struct bpf_sock, src_port):
6454 		*insn++ = BPF_LDX_MEM(
6455 			BPF_FIELD_SIZEOF(struct sock_common, skc_num),
6456 			si->dst_reg, si->src_reg,
6457 			bpf_target_off(struct sock_common, skc_num,
6458 				       FIELD_SIZEOF(struct sock_common,
6459 						    skc_num),
6460 				       target_size));
6461 		break;
6462 	}
6463 
6464 	return insn - insn_buf;
6465 }
6466 
6467 static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
6468 					 const struct bpf_insn *si,
6469 					 struct bpf_insn *insn_buf,
6470 					 struct bpf_prog *prog, u32 *target_size)
6471 {
6472 	struct bpf_insn *insn = insn_buf;
6473 
6474 	switch (si->off) {
6475 	case offsetof(struct __sk_buff, ifindex):
6476 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
6477 				      si->dst_reg, si->src_reg,
6478 				      offsetof(struct sk_buff, dev));
6479 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6480 				      bpf_target_off(struct net_device, ifindex, 4,
6481 						     target_size));
6482 		break;
6483 	default:
6484 		return bpf_convert_ctx_access(type, si, insn_buf, prog,
6485 					      target_size);
6486 	}
6487 
6488 	return insn - insn_buf;
6489 }
6490 
6491 static u32 xdp_convert_ctx_access(enum bpf_access_type type,
6492 				  const struct bpf_insn *si,
6493 				  struct bpf_insn *insn_buf,
6494 				  struct bpf_prog *prog, u32 *target_size)
6495 {
6496 	struct bpf_insn *insn = insn_buf;
6497 
6498 	switch (si->off) {
6499 	case offsetof(struct xdp_md, data):
6500 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
6501 				      si->dst_reg, si->src_reg,
6502 				      offsetof(struct xdp_buff, data));
6503 		break;
6504 	case offsetof(struct xdp_md, data_meta):
6505 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta),
6506 				      si->dst_reg, si->src_reg,
6507 				      offsetof(struct xdp_buff, data_meta));
6508 		break;
6509 	case offsetof(struct xdp_md, data_end):
6510 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
6511 				      si->dst_reg, si->src_reg,
6512 				      offsetof(struct xdp_buff, data_end));
6513 		break;
6514 	case offsetof(struct xdp_md, ingress_ifindex):
6515 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
6516 				      si->dst_reg, si->src_reg,
6517 				      offsetof(struct xdp_buff, rxq));
6518 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev),
6519 				      si->dst_reg, si->dst_reg,
6520 				      offsetof(struct xdp_rxq_info, dev));
6521 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6522 				      offsetof(struct net_device, ifindex));
6523 		break;
6524 	case offsetof(struct xdp_md, rx_queue_index):
6525 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
6526 				      si->dst_reg, si->src_reg,
6527 				      offsetof(struct xdp_buff, rxq));
6528 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6529 				      offsetof(struct xdp_rxq_info,
6530 					       queue_index));
6531 		break;
6532 	}
6533 
6534 	return insn - insn_buf;
6535 }
6536 
6537 /* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of
6538  * context Structure, F is Field in context structure that contains a pointer
6539  * to Nested Structure of type NS that has the field NF.
6540  *
6541  * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make
6542  * sure that SIZE is not greater than actual size of S.F.NF.
6543  *
6544  * If offset OFF is provided, the load happens from that offset relative to
6545  * offset of NF.
6546  */
6547 #define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF)	       \
6548 	do {								       \
6549 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg,     \
6550 				      si->src_reg, offsetof(S, F));	       \
6551 		*insn++ = BPF_LDX_MEM(					       \
6552 			SIZE, si->dst_reg, si->dst_reg,			       \
6553 			bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),	       \
6554 				       target_size)			       \
6555 				+ OFF);					       \
6556 	} while (0)
6557 
6558 #define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF)			       \
6559 	SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF,		       \
6560 					     BPF_FIELD_SIZEOF(NS, NF), 0)
6561 
6562 /* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to
6563  * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation.
6564  *
6565  * It doesn't support SIZE argument though since narrow stores are not
6566  * supported for now.
6567  *
6568  * In addition it uses Temporary Field TF (member of struct S) as the 3rd
6569  * "register" since two registers available in convert_ctx_access are not
6570  * enough: we can't override neither SRC, since it contains value to store, nor
6571  * DST since it contains pointer to context that may be used by later
6572  * instructions. But we need a temporary place to save pointer to nested
6573  * structure whose field we want to store to.
6574  */
6575 #define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF, TF)		       \
6576 	do {								       \
6577 		int tmp_reg = BPF_REG_9;				       \
6578 		if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)	       \
6579 			--tmp_reg;					       \
6580 		if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)	       \
6581 			--tmp_reg;					       \
6582 		*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg,	       \
6583 				      offsetof(S, TF));			       \
6584 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg,	       \
6585 				      si->dst_reg, offsetof(S, F));	       \
6586 		*insn++ = BPF_STX_MEM(					       \
6587 			BPF_FIELD_SIZEOF(NS, NF), tmp_reg, si->src_reg,	       \
6588 			bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),	       \
6589 				       target_size)			       \
6590 				+ OFF);					       \
6591 		*insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg,	       \
6592 				      offsetof(S, TF));			       \
6593 	} while (0)
6594 
6595 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \
6596 						      TF)		       \
6597 	do {								       \
6598 		if (type == BPF_WRITE) {				       \
6599 			SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF,    \
6600 							 TF);		       \
6601 		} else {						       \
6602 			SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(		       \
6603 				S, NS, F, NF, SIZE, OFF);  \
6604 		}							       \
6605 	} while (0)
6606 
6607 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(S, NS, F, NF, TF)		       \
6608 	SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(			       \
6609 		S, NS, F, NF, BPF_FIELD_SIZEOF(NS, NF), 0, TF)
6610 
6611 static u32 sock_addr_convert_ctx_access(enum bpf_access_type type,
6612 					const struct bpf_insn *si,
6613 					struct bpf_insn *insn_buf,
6614 					struct bpf_prog *prog, u32 *target_size)
6615 {
6616 	struct bpf_insn *insn = insn_buf;
6617 	int off;
6618 
6619 	switch (si->off) {
6620 	case offsetof(struct bpf_sock_addr, user_family):
6621 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
6622 					    struct sockaddr, uaddr, sa_family);
6623 		break;
6624 
6625 	case offsetof(struct bpf_sock_addr, user_ip4):
6626 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
6627 			struct bpf_sock_addr_kern, struct sockaddr_in, uaddr,
6628 			sin_addr, BPF_SIZE(si->code), 0, tmp_reg);
6629 		break;
6630 
6631 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
6632 		off = si->off;
6633 		off -= offsetof(struct bpf_sock_addr, user_ip6[0]);
6634 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
6635 			struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
6636 			sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off,
6637 			tmp_reg);
6638 		break;
6639 
6640 	case offsetof(struct bpf_sock_addr, user_port):
6641 		/* To get port we need to know sa_family first and then treat
6642 		 * sockaddr as either sockaddr_in or sockaddr_in6.
6643 		 * Though we can simplify since port field has same offset and
6644 		 * size in both structures.
6645 		 * Here we check this invariant and use just one of the
6646 		 * structures if it's true.
6647 		 */
6648 		BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) !=
6649 			     offsetof(struct sockaddr_in6, sin6_port));
6650 		BUILD_BUG_ON(FIELD_SIZEOF(struct sockaddr_in, sin_port) !=
6651 			     FIELD_SIZEOF(struct sockaddr_in6, sin6_port));
6652 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(struct bpf_sock_addr_kern,
6653 						     struct sockaddr_in6, uaddr,
6654 						     sin6_port, tmp_reg);
6655 		break;
6656 
6657 	case offsetof(struct bpf_sock_addr, family):
6658 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
6659 					    struct sock, sk, sk_family);
6660 		break;
6661 
6662 	case offsetof(struct bpf_sock_addr, type):
6663 		SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
6664 			struct bpf_sock_addr_kern, struct sock, sk,
6665 			__sk_flags_offset, BPF_W, 0);
6666 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
6667 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
6668 		break;
6669 
6670 	case offsetof(struct bpf_sock_addr, protocol):
6671 		SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
6672 			struct bpf_sock_addr_kern, struct sock, sk,
6673 			__sk_flags_offset, BPF_W, 0);
6674 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
6675 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
6676 					SK_FL_PROTO_SHIFT);
6677 		break;
6678 
6679 	case offsetof(struct bpf_sock_addr, msg_src_ip4):
6680 		/* Treat t_ctx as struct in_addr for msg_src_ip4. */
6681 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
6682 			struct bpf_sock_addr_kern, struct in_addr, t_ctx,
6683 			s_addr, BPF_SIZE(si->code), 0, tmp_reg);
6684 		break;
6685 
6686 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
6687 				msg_src_ip6[3]):
6688 		off = si->off;
6689 		off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]);
6690 		/* Treat t_ctx as struct in6_addr for msg_src_ip6. */
6691 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
6692 			struct bpf_sock_addr_kern, struct in6_addr, t_ctx,
6693 			s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg);
6694 		break;
6695 	}
6696 
6697 	return insn - insn_buf;
6698 }
6699 
6700 static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
6701 				       const struct bpf_insn *si,
6702 				       struct bpf_insn *insn_buf,
6703 				       struct bpf_prog *prog,
6704 				       u32 *target_size)
6705 {
6706 	struct bpf_insn *insn = insn_buf;
6707 	int off;
6708 
6709 	switch (si->off) {
6710 	case offsetof(struct bpf_sock_ops, op) ...
6711 	     offsetof(struct bpf_sock_ops, replylong[3]):
6712 		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, op) !=
6713 			     FIELD_SIZEOF(struct bpf_sock_ops_kern, op));
6714 		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, reply) !=
6715 			     FIELD_SIZEOF(struct bpf_sock_ops_kern, reply));
6716 		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, replylong) !=
6717 			     FIELD_SIZEOF(struct bpf_sock_ops_kern, replylong));
6718 		off = si->off;
6719 		off -= offsetof(struct bpf_sock_ops, op);
6720 		off += offsetof(struct bpf_sock_ops_kern, op);
6721 		if (type == BPF_WRITE)
6722 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6723 					      off);
6724 		else
6725 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6726 					      off);
6727 		break;
6728 
6729 	case offsetof(struct bpf_sock_ops, family):
6730 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
6731 
6732 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6733 					      struct bpf_sock_ops_kern, sk),
6734 				      si->dst_reg, si->src_reg,
6735 				      offsetof(struct bpf_sock_ops_kern, sk));
6736 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6737 				      offsetof(struct sock_common, skc_family));
6738 		break;
6739 
6740 	case offsetof(struct bpf_sock_ops, remote_ip4):
6741 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
6742 
6743 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6744 						struct bpf_sock_ops_kern, sk),
6745 				      si->dst_reg, si->src_reg,
6746 				      offsetof(struct bpf_sock_ops_kern, sk));
6747 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6748 				      offsetof(struct sock_common, skc_daddr));
6749 		break;
6750 
6751 	case offsetof(struct bpf_sock_ops, local_ip4):
6752 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6753 					  skc_rcv_saddr) != 4);
6754 
6755 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6756 					      struct bpf_sock_ops_kern, sk),
6757 				      si->dst_reg, si->src_reg,
6758 				      offsetof(struct bpf_sock_ops_kern, sk));
6759 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6760 				      offsetof(struct sock_common,
6761 					       skc_rcv_saddr));
6762 		break;
6763 
6764 	case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
6765 	     offsetof(struct bpf_sock_ops, remote_ip6[3]):
6766 #if IS_ENABLED(CONFIG_IPV6)
6767 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6768 					  skc_v6_daddr.s6_addr32[0]) != 4);
6769 
6770 		off = si->off;
6771 		off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
6772 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6773 						struct bpf_sock_ops_kern, sk),
6774 				      si->dst_reg, si->src_reg,
6775 				      offsetof(struct bpf_sock_ops_kern, sk));
6776 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6777 				      offsetof(struct sock_common,
6778 					       skc_v6_daddr.s6_addr32[0]) +
6779 				      off);
6780 #else
6781 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
6782 #endif
6783 		break;
6784 
6785 	case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
6786 	     offsetof(struct bpf_sock_ops, local_ip6[3]):
6787 #if IS_ENABLED(CONFIG_IPV6)
6788 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6789 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
6790 
6791 		off = si->off;
6792 		off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
6793 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6794 						struct bpf_sock_ops_kern, sk),
6795 				      si->dst_reg, si->src_reg,
6796 				      offsetof(struct bpf_sock_ops_kern, sk));
6797 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6798 				      offsetof(struct sock_common,
6799 					       skc_v6_rcv_saddr.s6_addr32[0]) +
6800 				      off);
6801 #else
6802 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
6803 #endif
6804 		break;
6805 
6806 	case offsetof(struct bpf_sock_ops, remote_port):
6807 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
6808 
6809 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6810 						struct bpf_sock_ops_kern, sk),
6811 				      si->dst_reg, si->src_reg,
6812 				      offsetof(struct bpf_sock_ops_kern, sk));
6813 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6814 				      offsetof(struct sock_common, skc_dport));
6815 #ifndef __BIG_ENDIAN_BITFIELD
6816 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
6817 #endif
6818 		break;
6819 
6820 	case offsetof(struct bpf_sock_ops, local_port):
6821 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
6822 
6823 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6824 						struct bpf_sock_ops_kern, sk),
6825 				      si->dst_reg, si->src_reg,
6826 				      offsetof(struct bpf_sock_ops_kern, sk));
6827 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6828 				      offsetof(struct sock_common, skc_num));
6829 		break;
6830 
6831 	case offsetof(struct bpf_sock_ops, is_fullsock):
6832 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6833 						struct bpf_sock_ops_kern,
6834 						is_fullsock),
6835 				      si->dst_reg, si->src_reg,
6836 				      offsetof(struct bpf_sock_ops_kern,
6837 					       is_fullsock));
6838 		break;
6839 
6840 	case offsetof(struct bpf_sock_ops, state):
6841 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_state) != 1);
6842 
6843 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6844 						struct bpf_sock_ops_kern, sk),
6845 				      si->dst_reg, si->src_reg,
6846 				      offsetof(struct bpf_sock_ops_kern, sk));
6847 		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg,
6848 				      offsetof(struct sock_common, skc_state));
6849 		break;
6850 
6851 	case offsetof(struct bpf_sock_ops, rtt_min):
6852 		BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) !=
6853 			     sizeof(struct minmax));
6854 		BUILD_BUG_ON(sizeof(struct minmax) <
6855 			     sizeof(struct minmax_sample));
6856 
6857 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6858 						struct bpf_sock_ops_kern, sk),
6859 				      si->dst_reg, si->src_reg,
6860 				      offsetof(struct bpf_sock_ops_kern, sk));
6861 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6862 				      offsetof(struct tcp_sock, rtt_min) +
6863 				      FIELD_SIZEOF(struct minmax_sample, t));
6864 		break;
6865 
6866 /* Helper macro for adding read access to tcp_sock or sock fields. */
6867 #define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)			      \
6868 	do {								      \
6869 		BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >		      \
6870 			     FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
6871 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
6872 						struct bpf_sock_ops_kern,     \
6873 						is_fullsock),		      \
6874 				      si->dst_reg, si->src_reg,		      \
6875 				      offsetof(struct bpf_sock_ops_kern,      \
6876 					       is_fullsock));		      \
6877 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 2);	      \
6878 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
6879 						struct bpf_sock_ops_kern, sk),\
6880 				      si->dst_reg, si->src_reg,		      \
6881 				      offsetof(struct bpf_sock_ops_kern, sk));\
6882 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ,		      \
6883 						       OBJ_FIELD),	      \
6884 				      si->dst_reg, si->dst_reg,		      \
6885 				      offsetof(OBJ, OBJ_FIELD));	      \
6886 	} while (0)
6887 
6888 /* Helper macro for adding write access to tcp_sock or sock fields.
6889  * The macro is called with two registers, dst_reg which contains a pointer
6890  * to ctx (context) and src_reg which contains the value that should be
6891  * stored. However, we need an additional register since we cannot overwrite
6892  * dst_reg because it may be used later in the program.
6893  * Instead we "borrow" one of the other register. We first save its value
6894  * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore
6895  * it at the end of the macro.
6896  */
6897 #define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)			      \
6898 	do {								      \
6899 		int reg = BPF_REG_9;					      \
6900 		BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >		      \
6901 			     FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
6902 		if (si->dst_reg == reg || si->src_reg == reg)		      \
6903 			reg--;						      \
6904 		if (si->dst_reg == reg || si->src_reg == reg)		      \
6905 			reg--;						      \
6906 		*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg,		      \
6907 				      offsetof(struct bpf_sock_ops_kern,      \
6908 					       temp));			      \
6909 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
6910 						struct bpf_sock_ops_kern,     \
6911 						is_fullsock),		      \
6912 				      reg, si->dst_reg,			      \
6913 				      offsetof(struct bpf_sock_ops_kern,      \
6914 					       is_fullsock));		      \
6915 		*insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);		      \
6916 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
6917 						struct bpf_sock_ops_kern, sk),\
6918 				      reg, si->dst_reg,			      \
6919 				      offsetof(struct bpf_sock_ops_kern, sk));\
6920 		*insn++ = BPF_STX_MEM(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD),	      \
6921 				      reg, si->src_reg,			      \
6922 				      offsetof(OBJ, OBJ_FIELD));	      \
6923 		*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg,		      \
6924 				      offsetof(struct bpf_sock_ops_kern,      \
6925 					       temp));			      \
6926 	} while (0)
6927 
6928 #define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE)	      \
6929 	do {								      \
6930 		if (TYPE == BPF_WRITE)					      \
6931 			SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);	      \
6932 		else							      \
6933 			SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);	      \
6934 	} while (0)
6935 
6936 	case offsetof(struct bpf_sock_ops, snd_cwnd):
6937 		SOCK_OPS_GET_FIELD(snd_cwnd, snd_cwnd, struct tcp_sock);
6938 		break;
6939 
6940 	case offsetof(struct bpf_sock_ops, srtt_us):
6941 		SOCK_OPS_GET_FIELD(srtt_us, srtt_us, struct tcp_sock);
6942 		break;
6943 
6944 	case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags):
6945 		SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags,
6946 				   struct tcp_sock);
6947 		break;
6948 
6949 	case offsetof(struct bpf_sock_ops, snd_ssthresh):
6950 		SOCK_OPS_GET_FIELD(snd_ssthresh, snd_ssthresh, struct tcp_sock);
6951 		break;
6952 
6953 	case offsetof(struct bpf_sock_ops, rcv_nxt):
6954 		SOCK_OPS_GET_FIELD(rcv_nxt, rcv_nxt, struct tcp_sock);
6955 		break;
6956 
6957 	case offsetof(struct bpf_sock_ops, snd_nxt):
6958 		SOCK_OPS_GET_FIELD(snd_nxt, snd_nxt, struct tcp_sock);
6959 		break;
6960 
6961 	case offsetof(struct bpf_sock_ops, snd_una):
6962 		SOCK_OPS_GET_FIELD(snd_una, snd_una, struct tcp_sock);
6963 		break;
6964 
6965 	case offsetof(struct bpf_sock_ops, mss_cache):
6966 		SOCK_OPS_GET_FIELD(mss_cache, mss_cache, struct tcp_sock);
6967 		break;
6968 
6969 	case offsetof(struct bpf_sock_ops, ecn_flags):
6970 		SOCK_OPS_GET_FIELD(ecn_flags, ecn_flags, struct tcp_sock);
6971 		break;
6972 
6973 	case offsetof(struct bpf_sock_ops, rate_delivered):
6974 		SOCK_OPS_GET_FIELD(rate_delivered, rate_delivered,
6975 				   struct tcp_sock);
6976 		break;
6977 
6978 	case offsetof(struct bpf_sock_ops, rate_interval_us):
6979 		SOCK_OPS_GET_FIELD(rate_interval_us, rate_interval_us,
6980 				   struct tcp_sock);
6981 		break;
6982 
6983 	case offsetof(struct bpf_sock_ops, packets_out):
6984 		SOCK_OPS_GET_FIELD(packets_out, packets_out, struct tcp_sock);
6985 		break;
6986 
6987 	case offsetof(struct bpf_sock_ops, retrans_out):
6988 		SOCK_OPS_GET_FIELD(retrans_out, retrans_out, struct tcp_sock);
6989 		break;
6990 
6991 	case offsetof(struct bpf_sock_ops, total_retrans):
6992 		SOCK_OPS_GET_FIELD(total_retrans, total_retrans,
6993 				   struct tcp_sock);
6994 		break;
6995 
6996 	case offsetof(struct bpf_sock_ops, segs_in):
6997 		SOCK_OPS_GET_FIELD(segs_in, segs_in, struct tcp_sock);
6998 		break;
6999 
7000 	case offsetof(struct bpf_sock_ops, data_segs_in):
7001 		SOCK_OPS_GET_FIELD(data_segs_in, data_segs_in, struct tcp_sock);
7002 		break;
7003 
7004 	case offsetof(struct bpf_sock_ops, segs_out):
7005 		SOCK_OPS_GET_FIELD(segs_out, segs_out, struct tcp_sock);
7006 		break;
7007 
7008 	case offsetof(struct bpf_sock_ops, data_segs_out):
7009 		SOCK_OPS_GET_FIELD(data_segs_out, data_segs_out,
7010 				   struct tcp_sock);
7011 		break;
7012 
7013 	case offsetof(struct bpf_sock_ops, lost_out):
7014 		SOCK_OPS_GET_FIELD(lost_out, lost_out, struct tcp_sock);
7015 		break;
7016 
7017 	case offsetof(struct bpf_sock_ops, sacked_out):
7018 		SOCK_OPS_GET_FIELD(sacked_out, sacked_out, struct tcp_sock);
7019 		break;
7020 
7021 	case offsetof(struct bpf_sock_ops, sk_txhash):
7022 		SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash,
7023 					  struct sock, type);
7024 		break;
7025 
7026 	case offsetof(struct bpf_sock_ops, bytes_received):
7027 		SOCK_OPS_GET_FIELD(bytes_received, bytes_received,
7028 				   struct tcp_sock);
7029 		break;
7030 
7031 	case offsetof(struct bpf_sock_ops, bytes_acked):
7032 		SOCK_OPS_GET_FIELD(bytes_acked, bytes_acked, struct tcp_sock);
7033 		break;
7034 
7035 	}
7036 	return insn - insn_buf;
7037 }
7038 
7039 static u32 sk_skb_convert_ctx_access(enum bpf_access_type type,
7040 				     const struct bpf_insn *si,
7041 				     struct bpf_insn *insn_buf,
7042 				     struct bpf_prog *prog, u32 *target_size)
7043 {
7044 	struct bpf_insn *insn = insn_buf;
7045 	int off;
7046 
7047 	switch (si->off) {
7048 	case offsetof(struct __sk_buff, data_end):
7049 		off  = si->off;
7050 		off -= offsetof(struct __sk_buff, data_end);
7051 		off += offsetof(struct sk_buff, cb);
7052 		off += offsetof(struct tcp_skb_cb, bpf.data_end);
7053 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7054 				      si->src_reg, off);
7055 		break;
7056 	default:
7057 		return bpf_convert_ctx_access(type, si, insn_buf, prog,
7058 					      target_size);
7059 	}
7060 
7061 	return insn - insn_buf;
7062 }
7063 
7064 static u32 sk_msg_convert_ctx_access(enum bpf_access_type type,
7065 				     const struct bpf_insn *si,
7066 				     struct bpf_insn *insn_buf,
7067 				     struct bpf_prog *prog, u32 *target_size)
7068 {
7069 	struct bpf_insn *insn = insn_buf;
7070 #if IS_ENABLED(CONFIG_IPV6)
7071 	int off;
7072 #endif
7073 
7074 	switch (si->off) {
7075 	case offsetof(struct sk_msg_md, data):
7076 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data),
7077 				      si->dst_reg, si->src_reg,
7078 				      offsetof(struct sk_msg, data));
7079 		break;
7080 	case offsetof(struct sk_msg_md, data_end):
7081 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data_end),
7082 				      si->dst_reg, si->src_reg,
7083 				      offsetof(struct sk_msg, data_end));
7084 		break;
7085 	case offsetof(struct sk_msg_md, family):
7086 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
7087 
7088 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7089 					      struct sk_msg, sk),
7090 				      si->dst_reg, si->src_reg,
7091 				      offsetof(struct sk_msg, sk));
7092 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7093 				      offsetof(struct sock_common, skc_family));
7094 		break;
7095 
7096 	case offsetof(struct sk_msg_md, remote_ip4):
7097 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
7098 
7099 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7100 						struct sk_msg, sk),
7101 				      si->dst_reg, si->src_reg,
7102 				      offsetof(struct sk_msg, sk));
7103 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7104 				      offsetof(struct sock_common, skc_daddr));
7105 		break;
7106 
7107 	case offsetof(struct sk_msg_md, local_ip4):
7108 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7109 					  skc_rcv_saddr) != 4);
7110 
7111 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7112 					      struct sk_msg, sk),
7113 				      si->dst_reg, si->src_reg,
7114 				      offsetof(struct sk_msg, sk));
7115 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7116 				      offsetof(struct sock_common,
7117 					       skc_rcv_saddr));
7118 		break;
7119 
7120 	case offsetof(struct sk_msg_md, remote_ip6[0]) ...
7121 	     offsetof(struct sk_msg_md, remote_ip6[3]):
7122 #if IS_ENABLED(CONFIG_IPV6)
7123 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7124 					  skc_v6_daddr.s6_addr32[0]) != 4);
7125 
7126 		off = si->off;
7127 		off -= offsetof(struct sk_msg_md, remote_ip6[0]);
7128 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7129 						struct sk_msg, sk),
7130 				      si->dst_reg, si->src_reg,
7131 				      offsetof(struct sk_msg, sk));
7132 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7133 				      offsetof(struct sock_common,
7134 					       skc_v6_daddr.s6_addr32[0]) +
7135 				      off);
7136 #else
7137 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7138 #endif
7139 		break;
7140 
7141 	case offsetof(struct sk_msg_md, local_ip6[0]) ...
7142 	     offsetof(struct sk_msg_md, local_ip6[3]):
7143 #if IS_ENABLED(CONFIG_IPV6)
7144 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7145 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
7146 
7147 		off = si->off;
7148 		off -= offsetof(struct sk_msg_md, local_ip6[0]);
7149 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7150 						struct sk_msg, sk),
7151 				      si->dst_reg, si->src_reg,
7152 				      offsetof(struct sk_msg, sk));
7153 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7154 				      offsetof(struct sock_common,
7155 					       skc_v6_rcv_saddr.s6_addr32[0]) +
7156 				      off);
7157 #else
7158 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7159 #endif
7160 		break;
7161 
7162 	case offsetof(struct sk_msg_md, remote_port):
7163 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
7164 
7165 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7166 						struct sk_msg, sk),
7167 				      si->dst_reg, si->src_reg,
7168 				      offsetof(struct sk_msg, sk));
7169 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7170 				      offsetof(struct sock_common, skc_dport));
7171 #ifndef __BIG_ENDIAN_BITFIELD
7172 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
7173 #endif
7174 		break;
7175 
7176 	case offsetof(struct sk_msg_md, local_port):
7177 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
7178 
7179 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7180 						struct sk_msg, sk),
7181 				      si->dst_reg, si->src_reg,
7182 				      offsetof(struct sk_msg, sk));
7183 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7184 				      offsetof(struct sock_common, skc_num));
7185 		break;
7186 	}
7187 
7188 	return insn - insn_buf;
7189 }
7190 
7191 const struct bpf_verifier_ops sk_filter_verifier_ops = {
7192 	.get_func_proto		= sk_filter_func_proto,
7193 	.is_valid_access	= sk_filter_is_valid_access,
7194 	.convert_ctx_access	= bpf_convert_ctx_access,
7195 	.gen_ld_abs		= bpf_gen_ld_abs,
7196 };
7197 
7198 const struct bpf_prog_ops sk_filter_prog_ops = {
7199 	.test_run		= bpf_prog_test_run_skb,
7200 };
7201 
7202 const struct bpf_verifier_ops tc_cls_act_verifier_ops = {
7203 	.get_func_proto		= tc_cls_act_func_proto,
7204 	.is_valid_access	= tc_cls_act_is_valid_access,
7205 	.convert_ctx_access	= tc_cls_act_convert_ctx_access,
7206 	.gen_prologue		= tc_cls_act_prologue,
7207 	.gen_ld_abs		= bpf_gen_ld_abs,
7208 };
7209 
7210 const struct bpf_prog_ops tc_cls_act_prog_ops = {
7211 	.test_run		= bpf_prog_test_run_skb,
7212 };
7213 
7214 const struct bpf_verifier_ops xdp_verifier_ops = {
7215 	.get_func_proto		= xdp_func_proto,
7216 	.is_valid_access	= xdp_is_valid_access,
7217 	.convert_ctx_access	= xdp_convert_ctx_access,
7218 	.gen_prologue		= bpf_noop_prologue,
7219 };
7220 
7221 const struct bpf_prog_ops xdp_prog_ops = {
7222 	.test_run		= bpf_prog_test_run_xdp,
7223 };
7224 
7225 const struct bpf_verifier_ops cg_skb_verifier_ops = {
7226 	.get_func_proto		= cg_skb_func_proto,
7227 	.is_valid_access	= cg_skb_is_valid_access,
7228 	.convert_ctx_access	= bpf_convert_ctx_access,
7229 };
7230 
7231 const struct bpf_prog_ops cg_skb_prog_ops = {
7232 	.test_run		= bpf_prog_test_run_skb,
7233 };
7234 
7235 const struct bpf_verifier_ops lwt_in_verifier_ops = {
7236 	.get_func_proto		= lwt_in_func_proto,
7237 	.is_valid_access	= lwt_is_valid_access,
7238 	.convert_ctx_access	= bpf_convert_ctx_access,
7239 };
7240 
7241 const struct bpf_prog_ops lwt_in_prog_ops = {
7242 	.test_run		= bpf_prog_test_run_skb,
7243 };
7244 
7245 const struct bpf_verifier_ops lwt_out_verifier_ops = {
7246 	.get_func_proto		= lwt_out_func_proto,
7247 	.is_valid_access	= lwt_is_valid_access,
7248 	.convert_ctx_access	= bpf_convert_ctx_access,
7249 };
7250 
7251 const struct bpf_prog_ops lwt_out_prog_ops = {
7252 	.test_run		= bpf_prog_test_run_skb,
7253 };
7254 
7255 const struct bpf_verifier_ops lwt_xmit_verifier_ops = {
7256 	.get_func_proto		= lwt_xmit_func_proto,
7257 	.is_valid_access	= lwt_is_valid_access,
7258 	.convert_ctx_access	= bpf_convert_ctx_access,
7259 	.gen_prologue		= tc_cls_act_prologue,
7260 };
7261 
7262 const struct bpf_prog_ops lwt_xmit_prog_ops = {
7263 	.test_run		= bpf_prog_test_run_skb,
7264 };
7265 
7266 const struct bpf_verifier_ops lwt_seg6local_verifier_ops = {
7267 	.get_func_proto		= lwt_seg6local_func_proto,
7268 	.is_valid_access	= lwt_is_valid_access,
7269 	.convert_ctx_access	= bpf_convert_ctx_access,
7270 };
7271 
7272 const struct bpf_prog_ops lwt_seg6local_prog_ops = {
7273 	.test_run		= bpf_prog_test_run_skb,
7274 };
7275 
7276 const struct bpf_verifier_ops cg_sock_verifier_ops = {
7277 	.get_func_proto		= sock_filter_func_proto,
7278 	.is_valid_access	= sock_filter_is_valid_access,
7279 	.convert_ctx_access	= bpf_sock_convert_ctx_access,
7280 };
7281 
7282 const struct bpf_prog_ops cg_sock_prog_ops = {
7283 };
7284 
7285 const struct bpf_verifier_ops cg_sock_addr_verifier_ops = {
7286 	.get_func_proto		= sock_addr_func_proto,
7287 	.is_valid_access	= sock_addr_is_valid_access,
7288 	.convert_ctx_access	= sock_addr_convert_ctx_access,
7289 };
7290 
7291 const struct bpf_prog_ops cg_sock_addr_prog_ops = {
7292 };
7293 
7294 const struct bpf_verifier_ops sock_ops_verifier_ops = {
7295 	.get_func_proto		= sock_ops_func_proto,
7296 	.is_valid_access	= sock_ops_is_valid_access,
7297 	.convert_ctx_access	= sock_ops_convert_ctx_access,
7298 };
7299 
7300 const struct bpf_prog_ops sock_ops_prog_ops = {
7301 };
7302 
7303 const struct bpf_verifier_ops sk_skb_verifier_ops = {
7304 	.get_func_proto		= sk_skb_func_proto,
7305 	.is_valid_access	= sk_skb_is_valid_access,
7306 	.convert_ctx_access	= sk_skb_convert_ctx_access,
7307 	.gen_prologue		= sk_skb_prologue,
7308 };
7309 
7310 const struct bpf_prog_ops sk_skb_prog_ops = {
7311 };
7312 
7313 const struct bpf_verifier_ops sk_msg_verifier_ops = {
7314 	.get_func_proto		= sk_msg_func_proto,
7315 	.is_valid_access	= sk_msg_is_valid_access,
7316 	.convert_ctx_access	= sk_msg_convert_ctx_access,
7317 	.gen_prologue		= bpf_noop_prologue,
7318 };
7319 
7320 const struct bpf_prog_ops sk_msg_prog_ops = {
7321 };
7322 
7323 const struct bpf_verifier_ops flow_dissector_verifier_ops = {
7324 	.get_func_proto		= flow_dissector_func_proto,
7325 	.is_valid_access	= flow_dissector_is_valid_access,
7326 	.convert_ctx_access	= bpf_convert_ctx_access,
7327 };
7328 
7329 const struct bpf_prog_ops flow_dissector_prog_ops = {
7330 };
7331 
7332 int sk_detach_filter(struct sock *sk)
7333 {
7334 	int ret = -ENOENT;
7335 	struct sk_filter *filter;
7336 
7337 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
7338 		return -EPERM;
7339 
7340 	filter = rcu_dereference_protected(sk->sk_filter,
7341 					   lockdep_sock_is_held(sk));
7342 	if (filter) {
7343 		RCU_INIT_POINTER(sk->sk_filter, NULL);
7344 		sk_filter_uncharge(sk, filter);
7345 		ret = 0;
7346 	}
7347 
7348 	return ret;
7349 }
7350 EXPORT_SYMBOL_GPL(sk_detach_filter);
7351 
7352 int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
7353 		  unsigned int len)
7354 {
7355 	struct sock_fprog_kern *fprog;
7356 	struct sk_filter *filter;
7357 	int ret = 0;
7358 
7359 	lock_sock(sk);
7360 	filter = rcu_dereference_protected(sk->sk_filter,
7361 					   lockdep_sock_is_held(sk));
7362 	if (!filter)
7363 		goto out;
7364 
7365 	/* We're copying the filter that has been originally attached,
7366 	 * so no conversion/decode needed anymore. eBPF programs that
7367 	 * have no original program cannot be dumped through this.
7368 	 */
7369 	ret = -EACCES;
7370 	fprog = filter->prog->orig_prog;
7371 	if (!fprog)
7372 		goto out;
7373 
7374 	ret = fprog->len;
7375 	if (!len)
7376 		/* User space only enquires number of filter blocks. */
7377 		goto out;
7378 
7379 	ret = -EINVAL;
7380 	if (len < fprog->len)
7381 		goto out;
7382 
7383 	ret = -EFAULT;
7384 	if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
7385 		goto out;
7386 
7387 	/* Instead of bytes, the API requests to return the number
7388 	 * of filter blocks.
7389 	 */
7390 	ret = fprog->len;
7391 out:
7392 	release_sock(sk);
7393 	return ret;
7394 }
7395 
7396 #ifdef CONFIG_INET
7397 struct sk_reuseport_kern {
7398 	struct sk_buff *skb;
7399 	struct sock *sk;
7400 	struct sock *selected_sk;
7401 	void *data_end;
7402 	u32 hash;
7403 	u32 reuseport_id;
7404 	bool bind_inany;
7405 };
7406 
7407 static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,
7408 				    struct sock_reuseport *reuse,
7409 				    struct sock *sk, struct sk_buff *skb,
7410 				    u32 hash)
7411 {
7412 	reuse_kern->skb = skb;
7413 	reuse_kern->sk = sk;
7414 	reuse_kern->selected_sk = NULL;
7415 	reuse_kern->data_end = skb->data + skb_headlen(skb);
7416 	reuse_kern->hash = hash;
7417 	reuse_kern->reuseport_id = reuse->reuseport_id;
7418 	reuse_kern->bind_inany = reuse->bind_inany;
7419 }
7420 
7421 struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,
7422 				  struct bpf_prog *prog, struct sk_buff *skb,
7423 				  u32 hash)
7424 {
7425 	struct sk_reuseport_kern reuse_kern;
7426 	enum sk_action action;
7427 
7428 	bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, hash);
7429 	action = BPF_PROG_RUN(prog, &reuse_kern);
7430 
7431 	if (action == SK_PASS)
7432 		return reuse_kern.selected_sk;
7433 	else
7434 		return ERR_PTR(-ECONNREFUSED);
7435 }
7436 
7437 BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern,
7438 	   struct bpf_map *, map, void *, key, u32, flags)
7439 {
7440 	struct sock_reuseport *reuse;
7441 	struct sock *selected_sk;
7442 
7443 	selected_sk = map->ops->map_lookup_elem(map, key);
7444 	if (!selected_sk)
7445 		return -ENOENT;
7446 
7447 	reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
7448 	if (!reuse)
7449 		/* selected_sk is unhashed (e.g. by close()) after the
7450 		 * above map_lookup_elem().  Treat selected_sk has already
7451 		 * been removed from the map.
7452 		 */
7453 		return -ENOENT;
7454 
7455 	if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
7456 		struct sock *sk;
7457 
7458 		if (unlikely(!reuse_kern->reuseport_id))
7459 			/* There is a small race between adding the
7460 			 * sk to the map and setting the
7461 			 * reuse_kern->reuseport_id.
7462 			 * Treat it as the sk has not been added to
7463 			 * the bpf map yet.
7464 			 */
7465 			return -ENOENT;
7466 
7467 		sk = reuse_kern->sk;
7468 		if (sk->sk_protocol != selected_sk->sk_protocol)
7469 			return -EPROTOTYPE;
7470 		else if (sk->sk_family != selected_sk->sk_family)
7471 			return -EAFNOSUPPORT;
7472 
7473 		/* Catch all. Likely bound to a different sockaddr. */
7474 		return -EBADFD;
7475 	}
7476 
7477 	reuse_kern->selected_sk = selected_sk;
7478 
7479 	return 0;
7480 }
7481 
7482 static const struct bpf_func_proto sk_select_reuseport_proto = {
7483 	.func           = sk_select_reuseport,
7484 	.gpl_only       = false,
7485 	.ret_type       = RET_INTEGER,
7486 	.arg1_type	= ARG_PTR_TO_CTX,
7487 	.arg2_type      = ARG_CONST_MAP_PTR,
7488 	.arg3_type      = ARG_PTR_TO_MAP_KEY,
7489 	.arg4_type	= ARG_ANYTHING,
7490 };
7491 
7492 BPF_CALL_4(sk_reuseport_load_bytes,
7493 	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
7494 	   void *, to, u32, len)
7495 {
7496 	return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
7497 }
7498 
7499 static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
7500 	.func		= sk_reuseport_load_bytes,
7501 	.gpl_only	= false,
7502 	.ret_type	= RET_INTEGER,
7503 	.arg1_type	= ARG_PTR_TO_CTX,
7504 	.arg2_type	= ARG_ANYTHING,
7505 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
7506 	.arg4_type	= ARG_CONST_SIZE,
7507 };
7508 
7509 BPF_CALL_5(sk_reuseport_load_bytes_relative,
7510 	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
7511 	   void *, to, u32, len, u32, start_header)
7512 {
7513 	return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
7514 					       len, start_header);
7515 }
7516 
7517 static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
7518 	.func		= sk_reuseport_load_bytes_relative,
7519 	.gpl_only	= false,
7520 	.ret_type	= RET_INTEGER,
7521 	.arg1_type	= ARG_PTR_TO_CTX,
7522 	.arg2_type	= ARG_ANYTHING,
7523 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
7524 	.arg4_type	= ARG_CONST_SIZE,
7525 	.arg5_type	= ARG_ANYTHING,
7526 };
7527 
7528 static const struct bpf_func_proto *
7529 sk_reuseport_func_proto(enum bpf_func_id func_id,
7530 			const struct bpf_prog *prog)
7531 {
7532 	switch (func_id) {
7533 	case BPF_FUNC_sk_select_reuseport:
7534 		return &sk_select_reuseport_proto;
7535 	case BPF_FUNC_skb_load_bytes:
7536 		return &sk_reuseport_load_bytes_proto;
7537 	case BPF_FUNC_skb_load_bytes_relative:
7538 		return &sk_reuseport_load_bytes_relative_proto;
7539 	default:
7540 		return bpf_base_func_proto(func_id);
7541 	}
7542 }
7543 
7544 static bool
7545 sk_reuseport_is_valid_access(int off, int size,
7546 			     enum bpf_access_type type,
7547 			     const struct bpf_prog *prog,
7548 			     struct bpf_insn_access_aux *info)
7549 {
7550 	const u32 size_default = sizeof(__u32);
7551 
7552 	if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
7553 	    off % size || type != BPF_READ)
7554 		return false;
7555 
7556 	switch (off) {
7557 	case offsetof(struct sk_reuseport_md, data):
7558 		info->reg_type = PTR_TO_PACKET;
7559 		return size == sizeof(__u64);
7560 
7561 	case offsetof(struct sk_reuseport_md, data_end):
7562 		info->reg_type = PTR_TO_PACKET_END;
7563 		return size == sizeof(__u64);
7564 
7565 	case offsetof(struct sk_reuseport_md, hash):
7566 		return size == size_default;
7567 
7568 	/* Fields that allow narrowing */
7569 	case offsetof(struct sk_reuseport_md, eth_protocol):
7570 		if (size < FIELD_SIZEOF(struct sk_buff, protocol))
7571 			return false;
7572 		/* fall through */
7573 	case offsetof(struct sk_reuseport_md, ip_protocol):
7574 	case offsetof(struct sk_reuseport_md, bind_inany):
7575 	case offsetof(struct sk_reuseport_md, len):
7576 		bpf_ctx_record_field_size(info, size_default);
7577 		return bpf_ctx_narrow_access_ok(off, size, size_default);
7578 
7579 	default:
7580 		return false;
7581 	}
7582 }
7583 
7584 #define SK_REUSEPORT_LOAD_FIELD(F) ({					\
7585 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
7586 			      si->dst_reg, si->src_reg,			\
7587 			      bpf_target_off(struct sk_reuseport_kern, F, \
7588 					     FIELD_SIZEOF(struct sk_reuseport_kern, F), \
7589 					     target_size));		\
7590 	})
7591 
7592 #define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)				\
7593 	SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,		\
7594 				    struct sk_buff,			\
7595 				    skb,				\
7596 				    SKB_FIELD)
7597 
7598 #define SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(SK_FIELD, BPF_SIZE, EXTRA_OFF) \
7599 	SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(struct sk_reuseport_kern,	\
7600 					     struct sock,		\
7601 					     sk,			\
7602 					     SK_FIELD, BPF_SIZE, EXTRA_OFF)
7603 
7604 static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
7605 					   const struct bpf_insn *si,
7606 					   struct bpf_insn *insn_buf,
7607 					   struct bpf_prog *prog,
7608 					   u32 *target_size)
7609 {
7610 	struct bpf_insn *insn = insn_buf;
7611 
7612 	switch (si->off) {
7613 	case offsetof(struct sk_reuseport_md, data):
7614 		SK_REUSEPORT_LOAD_SKB_FIELD(data);
7615 		break;
7616 
7617 	case offsetof(struct sk_reuseport_md, len):
7618 		SK_REUSEPORT_LOAD_SKB_FIELD(len);
7619 		break;
7620 
7621 	case offsetof(struct sk_reuseport_md, eth_protocol):
7622 		SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
7623 		break;
7624 
7625 	case offsetof(struct sk_reuseport_md, ip_protocol):
7626 		BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE);
7627 		SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(__sk_flags_offset,
7628 						    BPF_W, 0);
7629 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
7630 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
7631 					SK_FL_PROTO_SHIFT);
7632 		/* SK_FL_PROTO_MASK and SK_FL_PROTO_SHIFT are endian
7633 		 * aware.  No further narrowing or masking is needed.
7634 		 */
7635 		*target_size = 1;
7636 		break;
7637 
7638 	case offsetof(struct sk_reuseport_md, data_end):
7639 		SK_REUSEPORT_LOAD_FIELD(data_end);
7640 		break;
7641 
7642 	case offsetof(struct sk_reuseport_md, hash):
7643 		SK_REUSEPORT_LOAD_FIELD(hash);
7644 		break;
7645 
7646 	case offsetof(struct sk_reuseport_md, bind_inany):
7647 		SK_REUSEPORT_LOAD_FIELD(bind_inany);
7648 		break;
7649 	}
7650 
7651 	return insn - insn_buf;
7652 }
7653 
7654 const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
7655 	.get_func_proto		= sk_reuseport_func_proto,
7656 	.is_valid_access	= sk_reuseport_is_valid_access,
7657 	.convert_ctx_access	= sk_reuseport_convert_ctx_access,
7658 };
7659 
7660 const struct bpf_prog_ops sk_reuseport_prog_ops = {
7661 };
7662 #endif /* CONFIG_INET */
7663