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