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