Merge tag 'smp-core-2024-03-10' of git://git.kernel.org/pub/scm/linux/kernel/git...
[linux-block.git] / net / core / filter.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Linux Socket Filter - Kernel level socket filtering
4  *
5  * Based on the design of the Berkeley Packet Filter. The new
6  * internal format has been designed by PLUMgrid:
7  *
8  *      Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
9  *
10  * Authors:
11  *
12  *      Jay Schulist <jschlst@samba.org>
13  *      Alexei Starovoitov <ast@plumgrid.com>
14  *      Daniel Borkmann <dborkman@redhat.com>
15  *
16  * Andi Kleen - Fix a few bad bugs and races.
17  * Kris Katterjohn - Added many additional checks in bpf_check_classic()
18  */
19
20 #include <linux/atomic.h>
21 #include <linux/bpf_verifier.h>
22 #include <linux/module.h>
23 #include <linux/types.h>
24 #include <linux/mm.h>
25 #include <linux/fcntl.h>
26 #include <linux/socket.h>
27 #include <linux/sock_diag.h>
28 #include <linux/in.h>
29 #include <linux/inet.h>
30 #include <linux/netdevice.h>
31 #include <linux/if_packet.h>
32 #include <linux/if_arp.h>
33 #include <linux/gfp.h>
34 #include <net/inet_common.h>
35 #include <net/ip.h>
36 #include <net/protocol.h>
37 #include <net/netlink.h>
38 #include <linux/skbuff.h>
39 #include <linux/skmsg.h>
40 #include <net/sock.h>
41 #include <net/flow_dissector.h>
42 #include <linux/errno.h>
43 #include <linux/timer.h>
44 #include <linux/uaccess.h>
45 #include <asm/unaligned.h>
46 #include <linux/filter.h>
47 #include <linux/ratelimit.h>
48 #include <linux/seccomp.h>
49 #include <linux/if_vlan.h>
50 #include <linux/bpf.h>
51 #include <linux/btf.h>
52 #include <net/sch_generic.h>
53 #include <net/cls_cgroup.h>
54 #include <net/dst_metadata.h>
55 #include <net/dst.h>
56 #include <net/sock_reuseport.h>
57 #include <net/busy_poll.h>
58 #include <net/tcp.h>
59 #include <net/xfrm.h>
60 #include <net/udp.h>
61 #include <linux/bpf_trace.h>
62 #include <net/xdp_sock.h>
63 #include <linux/inetdevice.h>
64 #include <net/inet_hashtables.h>
65 #include <net/inet6_hashtables.h>
66 #include <net/ip_fib.h>
67 #include <net/nexthop.h>
68 #include <net/flow.h>
69 #include <net/arp.h>
70 #include <net/ipv6.h>
71 #include <net/net_namespace.h>
72 #include <linux/seg6_local.h>
73 #include <net/seg6.h>
74 #include <net/seg6_local.h>
75 #include <net/lwtunnel.h>
76 #include <net/ipv6_stubs.h>
77 #include <net/bpf_sk_storage.h>
78 #include <net/transp_v6.h>
79 #include <linux/btf_ids.h>
80 #include <net/tls.h>
81 #include <net/xdp.h>
82 #include <net/mptcp.h>
83 #include <net/netfilter/nf_conntrack_bpf.h>
84 #include <net/netkit.h>
85 #include <linux/un.h>
86 #include <net/xdp_sock_drv.h>
87
88 #include "dev.h"
89
90 static const struct bpf_func_proto *
91 bpf_sk_base_func_proto(enum bpf_func_id func_id);
92
93 int copy_bpf_fprog_from_user(struct sock_fprog *dst, sockptr_t src, int len)
94 {
95         if (in_compat_syscall()) {
96                 struct compat_sock_fprog f32;
97
98                 if (len != sizeof(f32))
99                         return -EINVAL;
100                 if (copy_from_sockptr(&f32, src, sizeof(f32)))
101                         return -EFAULT;
102                 memset(dst, 0, sizeof(*dst));
103                 dst->len = f32.len;
104                 dst->filter = compat_ptr(f32.filter);
105         } else {
106                 if (len != sizeof(*dst))
107                         return -EINVAL;
108                 if (copy_from_sockptr(dst, src, sizeof(*dst)))
109                         return -EFAULT;
110         }
111
112         return 0;
113 }
114 EXPORT_SYMBOL_GPL(copy_bpf_fprog_from_user);
115
116 /**
117  *      sk_filter_trim_cap - run a packet through a socket filter
118  *      @sk: sock associated with &sk_buff
119  *      @skb: buffer to filter
120  *      @cap: limit on how short the eBPF program may trim the packet
121  *
122  * Run the eBPF program and then cut skb->data to correct size returned by
123  * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
124  * than pkt_len we keep whole skb->data. This is the socket level
125  * wrapper to bpf_prog_run. It returns 0 if the packet should
126  * be accepted or -EPERM if the packet should be tossed.
127  *
128  */
129 int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
130 {
131         int err;
132         struct sk_filter *filter;
133
134         /*
135          * If the skb was allocated from pfmemalloc reserves, only
136          * allow SOCK_MEMALLOC sockets to use it as this socket is
137          * helping free memory
138          */
139         if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
140                 NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
141                 return -ENOMEM;
142         }
143         err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
144         if (err)
145                 return err;
146
147         err = security_sock_rcv_skb(sk, skb);
148         if (err)
149                 return err;
150
151         rcu_read_lock();
152         filter = rcu_dereference(sk->sk_filter);
153         if (filter) {
154                 struct sock *save_sk = skb->sk;
155                 unsigned int pkt_len;
156
157                 skb->sk = sk;
158                 pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
159                 skb->sk = save_sk;
160                 err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
161         }
162         rcu_read_unlock();
163
164         return err;
165 }
166 EXPORT_SYMBOL(sk_filter_trim_cap);
167
168 BPF_CALL_1(bpf_skb_get_pay_offset, struct sk_buff *, skb)
169 {
170         return skb_get_poff(skb);
171 }
172
173 BPF_CALL_3(bpf_skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
174 {
175         struct nlattr *nla;
176
177         if (skb_is_nonlinear(skb))
178                 return 0;
179
180         if (skb->len < sizeof(struct nlattr))
181                 return 0;
182
183         if (a > skb->len - sizeof(struct nlattr))
184                 return 0;
185
186         nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
187         if (nla)
188                 return (void *) nla - (void *) skb->data;
189
190         return 0;
191 }
192
193 BPF_CALL_3(bpf_skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
194 {
195         struct nlattr *nla;
196
197         if (skb_is_nonlinear(skb))
198                 return 0;
199
200         if (skb->len < sizeof(struct nlattr))
201                 return 0;
202
203         if (a > skb->len - sizeof(struct nlattr))
204                 return 0;
205
206         nla = (struct nlattr *) &skb->data[a];
207         if (!nla_ok(nla, skb->len - a))
208                 return 0;
209
210         nla = nla_find_nested(nla, x);
211         if (nla)
212                 return (void *) nla - (void *) skb->data;
213
214         return 0;
215 }
216
217 BPF_CALL_4(bpf_skb_load_helper_8, const struct sk_buff *, skb, const void *,
218            data, int, headlen, int, offset)
219 {
220         u8 tmp, *ptr;
221         const int len = sizeof(tmp);
222
223         if (offset >= 0) {
224                 if (headlen - offset >= len)
225                         return *(u8 *)(data + offset);
226                 if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
227                         return tmp;
228         } else {
229                 ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
230                 if (likely(ptr))
231                         return *(u8 *)ptr;
232         }
233
234         return -EFAULT;
235 }
236
237 BPF_CALL_2(bpf_skb_load_helper_8_no_cache, const struct sk_buff *, skb,
238            int, offset)
239 {
240         return ____bpf_skb_load_helper_8(skb, skb->data, skb->len - skb->data_len,
241                                          offset);
242 }
243
244 BPF_CALL_4(bpf_skb_load_helper_16, const struct sk_buff *, skb, const void *,
245            data, int, headlen, int, offset)
246 {
247         __be16 tmp, *ptr;
248         const int len = sizeof(tmp);
249
250         if (offset >= 0) {
251                 if (headlen - offset >= len)
252                         return get_unaligned_be16(data + offset);
253                 if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
254                         return be16_to_cpu(tmp);
255         } else {
256                 ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
257                 if (likely(ptr))
258                         return get_unaligned_be16(ptr);
259         }
260
261         return -EFAULT;
262 }
263
264 BPF_CALL_2(bpf_skb_load_helper_16_no_cache, const struct sk_buff *, skb,
265            int, offset)
266 {
267         return ____bpf_skb_load_helper_16(skb, skb->data, skb->len - skb->data_len,
268                                           offset);
269 }
270
271 BPF_CALL_4(bpf_skb_load_helper_32, const struct sk_buff *, skb, const void *,
272            data, int, headlen, int, offset)
273 {
274         __be32 tmp, *ptr;
275         const int len = sizeof(tmp);
276
277         if (likely(offset >= 0)) {
278                 if (headlen - offset >= len)
279                         return get_unaligned_be32(data + offset);
280                 if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
281                         return be32_to_cpu(tmp);
282         } else {
283                 ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
284                 if (likely(ptr))
285                         return get_unaligned_be32(ptr);
286         }
287
288         return -EFAULT;
289 }
290
291 BPF_CALL_2(bpf_skb_load_helper_32_no_cache, const struct sk_buff *, skb,
292            int, offset)
293 {
294         return ____bpf_skb_load_helper_32(skb, skb->data, skb->len - skb->data_len,
295                                           offset);
296 }
297
298 static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
299                               struct bpf_insn *insn_buf)
300 {
301         struct bpf_insn *insn = insn_buf;
302
303         switch (skb_field) {
304         case SKF_AD_MARK:
305                 BUILD_BUG_ON(sizeof_field(struct sk_buff, mark) != 4);
306
307                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
308                                       offsetof(struct sk_buff, mark));
309                 break;
310
311         case SKF_AD_PKTTYPE:
312                 *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET);
313                 *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
314 #ifdef __BIG_ENDIAN_BITFIELD
315                 *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
316 #endif
317                 break;
318
319         case SKF_AD_QUEUE:
320                 BUILD_BUG_ON(sizeof_field(struct sk_buff, queue_mapping) != 2);
321
322                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
323                                       offsetof(struct sk_buff, queue_mapping));
324                 break;
325
326         case SKF_AD_VLAN_TAG:
327                 BUILD_BUG_ON(sizeof_field(struct sk_buff, vlan_tci) != 2);
328
329                 /* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
330                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
331                                       offsetof(struct sk_buff, vlan_tci));
332                 break;
333         case SKF_AD_VLAN_TAG_PRESENT:
334                 BUILD_BUG_ON(sizeof_field(struct sk_buff, vlan_all) != 4);
335                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
336                                       offsetof(struct sk_buff, vlan_all));
337                 *insn++ = BPF_JMP_IMM(BPF_JEQ, dst_reg, 0, 1);
338                 *insn++ = BPF_ALU32_IMM(BPF_MOV, dst_reg, 1);
339                 break;
340         }
341
342         return insn - insn_buf;
343 }
344
345 static bool convert_bpf_extensions(struct sock_filter *fp,
346                                    struct bpf_insn **insnp)
347 {
348         struct bpf_insn *insn = *insnp;
349         u32 cnt;
350
351         switch (fp->k) {
352         case SKF_AD_OFF + SKF_AD_PROTOCOL:
353                 BUILD_BUG_ON(sizeof_field(struct sk_buff, protocol) != 2);
354
355                 /* A = *(u16 *) (CTX + offsetof(protocol)) */
356                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
357                                       offsetof(struct sk_buff, protocol));
358                 /* A = ntohs(A) [emitting a nop or swap16] */
359                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
360                 break;
361
362         case SKF_AD_OFF + SKF_AD_PKTTYPE:
363                 cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
364                 insn += cnt - 1;
365                 break;
366
367         case SKF_AD_OFF + SKF_AD_IFINDEX:
368         case SKF_AD_OFF + SKF_AD_HATYPE:
369                 BUILD_BUG_ON(sizeof_field(struct net_device, ifindex) != 4);
370                 BUILD_BUG_ON(sizeof_field(struct net_device, type) != 2);
371
372                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
373                                       BPF_REG_TMP, BPF_REG_CTX,
374                                       offsetof(struct sk_buff, dev));
375                 /* if (tmp != 0) goto pc + 1 */
376                 *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
377                 *insn++ = BPF_EXIT_INSN();
378                 if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
379                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
380                                             offsetof(struct net_device, ifindex));
381                 else
382                         *insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
383                                             offsetof(struct net_device, type));
384                 break;
385
386         case SKF_AD_OFF + SKF_AD_MARK:
387                 cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
388                 insn += cnt - 1;
389                 break;
390
391         case SKF_AD_OFF + SKF_AD_RXHASH:
392                 BUILD_BUG_ON(sizeof_field(struct sk_buff, hash) != 4);
393
394                 *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
395                                     offsetof(struct sk_buff, hash));
396                 break;
397
398         case SKF_AD_OFF + SKF_AD_QUEUE:
399                 cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
400                 insn += cnt - 1;
401                 break;
402
403         case SKF_AD_OFF + SKF_AD_VLAN_TAG:
404                 cnt = convert_skb_access(SKF_AD_VLAN_TAG,
405                                          BPF_REG_A, BPF_REG_CTX, insn);
406                 insn += cnt - 1;
407                 break;
408
409         case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
410                 cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
411                                          BPF_REG_A, BPF_REG_CTX, insn);
412                 insn += cnt - 1;
413                 break;
414
415         case SKF_AD_OFF + SKF_AD_VLAN_TPID:
416                 BUILD_BUG_ON(sizeof_field(struct sk_buff, vlan_proto) != 2);
417
418                 /* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
419                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
420                                       offsetof(struct sk_buff, vlan_proto));
421                 /* A = ntohs(A) [emitting a nop or swap16] */
422                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
423                 break;
424
425         case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
426         case SKF_AD_OFF + SKF_AD_NLATTR:
427         case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
428         case SKF_AD_OFF + SKF_AD_CPU:
429         case SKF_AD_OFF + SKF_AD_RANDOM:
430                 /* arg1 = CTX */
431                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
432                 /* arg2 = A */
433                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
434                 /* arg3 = X */
435                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
436                 /* Emit call(arg1=CTX, arg2=A, arg3=X) */
437                 switch (fp->k) {
438                 case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
439                         *insn = BPF_EMIT_CALL(bpf_skb_get_pay_offset);
440                         break;
441                 case SKF_AD_OFF + SKF_AD_NLATTR:
442                         *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr);
443                         break;
444                 case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
445                         *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr_nest);
446                         break;
447                 case SKF_AD_OFF + SKF_AD_CPU:
448                         *insn = BPF_EMIT_CALL(bpf_get_raw_cpu_id);
449                         break;
450                 case SKF_AD_OFF + SKF_AD_RANDOM:
451                         *insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
452                         bpf_user_rnd_init_once();
453                         break;
454                 }
455                 break;
456
457         case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
458                 /* A ^= X */
459                 *insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
460                 break;
461
462         default:
463                 /* This is just a dummy call to avoid letting the compiler
464                  * evict __bpf_call_base() as an optimization. Placed here
465                  * where no-one bothers.
466                  */
467                 BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
468                 return false;
469         }
470
471         *insnp = insn;
472         return true;
473 }
474
475 static bool convert_bpf_ld_abs(struct sock_filter *fp, struct bpf_insn **insnp)
476 {
477         const bool unaligned_ok = IS_BUILTIN(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS);
478         int size = bpf_size_to_bytes(BPF_SIZE(fp->code));
479         bool endian = BPF_SIZE(fp->code) == BPF_H ||
480                       BPF_SIZE(fp->code) == BPF_W;
481         bool indirect = BPF_MODE(fp->code) == BPF_IND;
482         const int ip_align = NET_IP_ALIGN;
483         struct bpf_insn *insn = *insnp;
484         int offset = fp->k;
485
486         if (!indirect &&
487             ((unaligned_ok && offset >= 0) ||
488              (!unaligned_ok && offset >= 0 &&
489               offset + ip_align >= 0 &&
490               offset + ip_align % size == 0))) {
491                 bool ldx_off_ok = offset <= S16_MAX;
492
493                 *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_H);
494                 if (offset)
495                         *insn++ = BPF_ALU64_IMM(BPF_SUB, BPF_REG_TMP, offset);
496                 *insn++ = BPF_JMP_IMM(BPF_JSLT, BPF_REG_TMP,
497                                       size, 2 + endian + (!ldx_off_ok * 2));
498                 if (ldx_off_ok) {
499                         *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
500                                               BPF_REG_D, offset);
501                 } else {
502                         *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_D);
503                         *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_TMP, offset);
504                         *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
505                                               BPF_REG_TMP, 0);
506                 }
507                 if (endian)
508                         *insn++ = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, size * 8);
509                 *insn++ = BPF_JMP_A(8);
510         }
511
512         *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
513         *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_D);
514         *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_H);
515         if (!indirect) {
516                 *insn++ = BPF_MOV64_IMM(BPF_REG_ARG4, offset);
517         } else {
518                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG4, BPF_REG_X);
519                 if (fp->k)
520                         *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_ARG4, offset);
521         }
522
523         switch (BPF_SIZE(fp->code)) {
524         case BPF_B:
525                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8);
526                 break;
527         case BPF_H:
528                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16);
529                 break;
530         case BPF_W:
531                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32);
532                 break;
533         default:
534                 return false;
535         }
536
537         *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_A, 0, 2);
538         *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
539         *insn   = BPF_EXIT_INSN();
540
541         *insnp = insn;
542         return true;
543 }
544
545 /**
546  *      bpf_convert_filter - convert filter program
547  *      @prog: the user passed filter program
548  *      @len: the length of the user passed filter program
549  *      @new_prog: allocated 'struct bpf_prog' or NULL
550  *      @new_len: pointer to store length of converted program
551  *      @seen_ld_abs: bool whether we've seen ld_abs/ind
552  *
553  * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
554  * style extended BPF (eBPF).
555  * Conversion workflow:
556  *
557  * 1) First pass for calculating the new program length:
558  *   bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs)
559  *
560  * 2) 2nd pass to remap in two passes: 1st pass finds new
561  *    jump offsets, 2nd pass remapping:
562  *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len, &seen_ld_abs)
563  */
564 static int bpf_convert_filter(struct sock_filter *prog, int len,
565                               struct bpf_prog *new_prog, int *new_len,
566                               bool *seen_ld_abs)
567 {
568         int new_flen = 0, pass = 0, target, i, stack_off;
569         struct bpf_insn *new_insn, *first_insn = NULL;
570         struct sock_filter *fp;
571         int *addrs = NULL;
572         u8 bpf_src;
573
574         BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
575         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
576
577         if (len <= 0 || len > BPF_MAXINSNS)
578                 return -EINVAL;
579
580         if (new_prog) {
581                 first_insn = new_prog->insnsi;
582                 addrs = kcalloc(len, sizeof(*addrs),
583                                 GFP_KERNEL | __GFP_NOWARN);
584                 if (!addrs)
585                         return -ENOMEM;
586         }
587
588 do_pass:
589         new_insn = first_insn;
590         fp = prog;
591
592         /* Classic BPF related prologue emission. */
593         if (new_prog) {
594                 /* Classic BPF expects A and X to be reset first. These need
595                  * to be guaranteed to be the first two instructions.
596                  */
597                 *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
598                 *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
599
600                 /* All programs must keep CTX in callee saved BPF_REG_CTX.
601                  * In eBPF case it's done by the compiler, here we need to
602                  * do this ourself. Initial CTX is present in BPF_REG_ARG1.
603                  */
604                 *new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
605                 if (*seen_ld_abs) {
606                         /* For packet access in classic BPF, cache skb->data
607                          * in callee-saved BPF R8 and skb->len - skb->data_len
608                          * (headlen) in BPF R9. Since classic BPF is read-only
609                          * on CTX, we only need to cache it once.
610                          */
611                         *new_insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
612                                                   BPF_REG_D, BPF_REG_CTX,
613                                                   offsetof(struct sk_buff, data));
614                         *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_H, BPF_REG_CTX,
615                                                   offsetof(struct sk_buff, len));
616                         *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_TMP, BPF_REG_CTX,
617                                                   offsetof(struct sk_buff, data_len));
618                         *new_insn++ = BPF_ALU32_REG(BPF_SUB, BPF_REG_H, BPF_REG_TMP);
619                 }
620         } else {
621                 new_insn += 3;
622         }
623
624         for (i = 0; i < len; fp++, i++) {
625                 struct bpf_insn tmp_insns[32] = { };
626                 struct bpf_insn *insn = tmp_insns;
627
628                 if (addrs)
629                         addrs[i] = new_insn - first_insn;
630
631                 switch (fp->code) {
632                 /* All arithmetic insns and skb loads map as-is. */
633                 case BPF_ALU | BPF_ADD | BPF_X:
634                 case BPF_ALU | BPF_ADD | BPF_K:
635                 case BPF_ALU | BPF_SUB | BPF_X:
636                 case BPF_ALU | BPF_SUB | BPF_K:
637                 case BPF_ALU | BPF_AND | BPF_X:
638                 case BPF_ALU | BPF_AND | BPF_K:
639                 case BPF_ALU | BPF_OR | BPF_X:
640                 case BPF_ALU | BPF_OR | BPF_K:
641                 case BPF_ALU | BPF_LSH | BPF_X:
642                 case BPF_ALU | BPF_LSH | BPF_K:
643                 case BPF_ALU | BPF_RSH | BPF_X:
644                 case BPF_ALU | BPF_RSH | BPF_K:
645                 case BPF_ALU | BPF_XOR | BPF_X:
646                 case BPF_ALU | BPF_XOR | BPF_K:
647                 case BPF_ALU | BPF_MUL | BPF_X:
648                 case BPF_ALU | BPF_MUL | BPF_K:
649                 case BPF_ALU | BPF_DIV | BPF_X:
650                 case BPF_ALU | BPF_DIV | BPF_K:
651                 case BPF_ALU | BPF_MOD | BPF_X:
652                 case BPF_ALU | BPF_MOD | BPF_K:
653                 case BPF_ALU | BPF_NEG:
654                 case BPF_LD | BPF_ABS | BPF_W:
655                 case BPF_LD | BPF_ABS | BPF_H:
656                 case BPF_LD | BPF_ABS | BPF_B:
657                 case BPF_LD | BPF_IND | BPF_W:
658                 case BPF_LD | BPF_IND | BPF_H:
659                 case BPF_LD | BPF_IND | BPF_B:
660                         /* Check for overloaded BPF extension and
661                          * directly convert it if found, otherwise
662                          * just move on with mapping.
663                          */
664                         if (BPF_CLASS(fp->code) == BPF_LD &&
665                             BPF_MODE(fp->code) == BPF_ABS &&
666                             convert_bpf_extensions(fp, &insn))
667                                 break;
668                         if (BPF_CLASS(fp->code) == BPF_LD &&
669                             convert_bpf_ld_abs(fp, &insn)) {
670                                 *seen_ld_abs = true;
671                                 break;
672                         }
673
674                         if (fp->code == (BPF_ALU | BPF_DIV | BPF_X) ||
675                             fp->code == (BPF_ALU | BPF_MOD | BPF_X)) {
676                                 *insn++ = BPF_MOV32_REG(BPF_REG_X, BPF_REG_X);
677                                 /* Error with exception code on div/mod by 0.
678                                  * For cBPF programs, this was always return 0.
679                                  */
680                                 *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_X, 0, 2);
681                                 *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
682                                 *insn++ = BPF_EXIT_INSN();
683                         }
684
685                         *insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
686                         break;
687
688                 /* Jump transformation cannot use BPF block macros
689                  * everywhere as offset calculation and target updates
690                  * require a bit more work than the rest, i.e. jump
691                  * opcodes map as-is, but offsets need adjustment.
692                  */
693
694 #define BPF_EMIT_JMP                                                    \
695         do {                                                            \
696                 const s32 off_min = S16_MIN, off_max = S16_MAX;         \
697                 s32 off;                                                \
698                                                                         \
699                 if (target >= len || target < 0)                        \
700                         goto err;                                       \
701                 off = addrs ? addrs[target] - addrs[i] - 1 : 0;         \
702                 /* Adjust pc relative offset for 2nd or 3rd insn. */    \
703                 off -= insn - tmp_insns;                                \
704                 /* Reject anything not fitting into insn->off. */       \
705                 if (off < off_min || off > off_max)                     \
706                         goto err;                                       \
707                 insn->off = off;                                        \
708         } while (0)
709
710                 case BPF_JMP | BPF_JA:
711                         target = i + fp->k + 1;
712                         insn->code = fp->code;
713                         BPF_EMIT_JMP;
714                         break;
715
716                 case BPF_JMP | BPF_JEQ | BPF_K:
717                 case BPF_JMP | BPF_JEQ | BPF_X:
718                 case BPF_JMP | BPF_JSET | BPF_K:
719                 case BPF_JMP | BPF_JSET | BPF_X:
720                 case BPF_JMP | BPF_JGT | BPF_K:
721                 case BPF_JMP | BPF_JGT | BPF_X:
722                 case BPF_JMP | BPF_JGE | BPF_K:
723                 case BPF_JMP | BPF_JGE | BPF_X:
724                         if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
725                                 /* BPF immediates are signed, zero extend
726                                  * immediate into tmp register and use it
727                                  * in compare insn.
728                                  */
729                                 *insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
730
731                                 insn->dst_reg = BPF_REG_A;
732                                 insn->src_reg = BPF_REG_TMP;
733                                 bpf_src = BPF_X;
734                         } else {
735                                 insn->dst_reg = BPF_REG_A;
736                                 insn->imm = fp->k;
737                                 bpf_src = BPF_SRC(fp->code);
738                                 insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
739                         }
740
741                         /* Common case where 'jump_false' is next insn. */
742                         if (fp->jf == 0) {
743                                 insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
744                                 target = i + fp->jt + 1;
745                                 BPF_EMIT_JMP;
746                                 break;
747                         }
748
749                         /* Convert some jumps when 'jump_true' is next insn. */
750                         if (fp->jt == 0) {
751                                 switch (BPF_OP(fp->code)) {
752                                 case BPF_JEQ:
753                                         insn->code = BPF_JMP | BPF_JNE | bpf_src;
754                                         break;
755                                 case BPF_JGT:
756                                         insn->code = BPF_JMP | BPF_JLE | bpf_src;
757                                         break;
758                                 case BPF_JGE:
759                                         insn->code = BPF_JMP | BPF_JLT | bpf_src;
760                                         break;
761                                 default:
762                                         goto jmp_rest;
763                                 }
764
765                                 target = i + fp->jf + 1;
766                                 BPF_EMIT_JMP;
767                                 break;
768                         }
769 jmp_rest:
770                         /* Other jumps are mapped into two insns: Jxx and JA. */
771                         target = i + fp->jt + 1;
772                         insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
773                         BPF_EMIT_JMP;
774                         insn++;
775
776                         insn->code = BPF_JMP | BPF_JA;
777                         target = i + fp->jf + 1;
778                         BPF_EMIT_JMP;
779                         break;
780
781                 /* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
782                 case BPF_LDX | BPF_MSH | BPF_B: {
783                         struct sock_filter tmp = {
784                                 .code   = BPF_LD | BPF_ABS | BPF_B,
785                                 .k      = fp->k,
786                         };
787
788                         *seen_ld_abs = true;
789
790                         /* X = A */
791                         *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
792                         /* A = BPF_R0 = *(u8 *) (skb->data + K) */
793                         convert_bpf_ld_abs(&tmp, &insn);
794                         insn++;
795                         /* A &= 0xf */
796                         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
797                         /* A <<= 2 */
798                         *insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
799                         /* tmp = X */
800                         *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_X);
801                         /* X = A */
802                         *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
803                         /* A = tmp */
804                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
805                         break;
806                 }
807                 /* RET_K is remaped into 2 insns. RET_A case doesn't need an
808                  * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
809                  */
810                 case BPF_RET | BPF_A:
811                 case BPF_RET | BPF_K:
812                         if (BPF_RVAL(fp->code) == BPF_K)
813                                 *insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
814                                                         0, fp->k);
815                         *insn = BPF_EXIT_INSN();
816                         break;
817
818                 /* Store to stack. */
819                 case BPF_ST:
820                 case BPF_STX:
821                         stack_off = fp->k * 4  + 4;
822                         *insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
823                                             BPF_ST ? BPF_REG_A : BPF_REG_X,
824                                             -stack_off);
825                         /* check_load_and_stores() verifies that classic BPF can
826                          * load from stack only after write, so tracking
827                          * stack_depth for ST|STX insns is enough
828                          */
829                         if (new_prog && new_prog->aux->stack_depth < stack_off)
830                                 new_prog->aux->stack_depth = stack_off;
831                         break;
832
833                 /* Load from stack. */
834                 case BPF_LD | BPF_MEM:
835                 case BPF_LDX | BPF_MEM:
836                         stack_off = fp->k * 4  + 4;
837                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
838                                             BPF_REG_A : BPF_REG_X, BPF_REG_FP,
839                                             -stack_off);
840                         break;
841
842                 /* A = K or X = K */
843                 case BPF_LD | BPF_IMM:
844                 case BPF_LDX | BPF_IMM:
845                         *insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
846                                               BPF_REG_A : BPF_REG_X, fp->k);
847                         break;
848
849                 /* X = A */
850                 case BPF_MISC | BPF_TAX:
851                         *insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
852                         break;
853
854                 /* A = X */
855                 case BPF_MISC | BPF_TXA:
856                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
857                         break;
858
859                 /* A = skb->len or X = skb->len */
860                 case BPF_LD | BPF_W | BPF_LEN:
861                 case BPF_LDX | BPF_W | BPF_LEN:
862                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
863                                             BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
864                                             offsetof(struct sk_buff, len));
865                         break;
866
867                 /* Access seccomp_data fields. */
868                 case BPF_LDX | BPF_ABS | BPF_W:
869                         /* A = *(u32 *) (ctx + K) */
870                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
871                         break;
872
873                 /* Unknown instruction. */
874                 default:
875                         goto err;
876                 }
877
878                 insn++;
879                 if (new_prog)
880                         memcpy(new_insn, tmp_insns,
881                                sizeof(*insn) * (insn - tmp_insns));
882                 new_insn += insn - tmp_insns;
883         }
884
885         if (!new_prog) {
886                 /* Only calculating new length. */
887                 *new_len = new_insn - first_insn;
888                 if (*seen_ld_abs)
889                         *new_len += 4; /* Prologue bits. */
890                 return 0;
891         }
892
893         pass++;
894         if (new_flen != new_insn - first_insn) {
895                 new_flen = new_insn - first_insn;
896                 if (pass > 2)
897                         goto err;
898                 goto do_pass;
899         }
900
901         kfree(addrs);
902         BUG_ON(*new_len != new_flen);
903         return 0;
904 err:
905         kfree(addrs);
906         return -EINVAL;
907 }
908
909 /* Security:
910  *
911  * As we dont want to clear mem[] array for each packet going through
912  * __bpf_prog_run(), we check that filter loaded by user never try to read
913  * a cell if not previously written, and we check all branches to be sure
914  * a malicious user doesn't try to abuse us.
915  */
916 static int check_load_and_stores(const struct sock_filter *filter, int flen)
917 {
918         u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
919         int pc, ret = 0;
920
921         BUILD_BUG_ON(BPF_MEMWORDS > 16);
922
923         masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
924         if (!masks)
925                 return -ENOMEM;
926
927         memset(masks, 0xff, flen * sizeof(*masks));
928
929         for (pc = 0; pc < flen; pc++) {
930                 memvalid &= masks[pc];
931
932                 switch (filter[pc].code) {
933                 case BPF_ST:
934                 case BPF_STX:
935                         memvalid |= (1 << filter[pc].k);
936                         break;
937                 case BPF_LD | BPF_MEM:
938                 case BPF_LDX | BPF_MEM:
939                         if (!(memvalid & (1 << filter[pc].k))) {
940                                 ret = -EINVAL;
941                                 goto error;
942                         }
943                         break;
944                 case BPF_JMP | BPF_JA:
945                         /* A jump must set masks on target */
946                         masks[pc + 1 + filter[pc].k] &= memvalid;
947                         memvalid = ~0;
948                         break;
949                 case BPF_JMP | BPF_JEQ | BPF_K:
950                 case BPF_JMP | BPF_JEQ | BPF_X:
951                 case BPF_JMP | BPF_JGE | BPF_K:
952                 case BPF_JMP | BPF_JGE | BPF_X:
953                 case BPF_JMP | BPF_JGT | BPF_K:
954                 case BPF_JMP | BPF_JGT | BPF_X:
955                 case BPF_JMP | BPF_JSET | BPF_K:
956                 case BPF_JMP | BPF_JSET | BPF_X:
957                         /* A jump must set masks on targets */
958                         masks[pc + 1 + filter[pc].jt] &= memvalid;
959                         masks[pc + 1 + filter[pc].jf] &= memvalid;
960                         memvalid = ~0;
961                         break;
962                 }
963         }
964 error:
965         kfree(masks);
966         return ret;
967 }
968
969 static bool chk_code_allowed(u16 code_to_probe)
970 {
971         static const bool codes[] = {
972                 /* 32 bit ALU operations */
973                 [BPF_ALU | BPF_ADD | BPF_K] = true,
974                 [BPF_ALU | BPF_ADD | BPF_X] = true,
975                 [BPF_ALU | BPF_SUB | BPF_K] = true,
976                 [BPF_ALU | BPF_SUB | BPF_X] = true,
977                 [BPF_ALU | BPF_MUL | BPF_K] = true,
978                 [BPF_ALU | BPF_MUL | BPF_X] = true,
979                 [BPF_ALU | BPF_DIV | BPF_K] = true,
980                 [BPF_ALU | BPF_DIV | BPF_X] = true,
981                 [BPF_ALU | BPF_MOD | BPF_K] = true,
982                 [BPF_ALU | BPF_MOD | BPF_X] = true,
983                 [BPF_ALU | BPF_AND | BPF_K] = true,
984                 [BPF_ALU | BPF_AND | BPF_X] = true,
985                 [BPF_ALU | BPF_OR | BPF_K] = true,
986                 [BPF_ALU | BPF_OR | BPF_X] = true,
987                 [BPF_ALU | BPF_XOR | BPF_K] = true,
988                 [BPF_ALU | BPF_XOR | BPF_X] = true,
989                 [BPF_ALU | BPF_LSH | BPF_K] = true,
990                 [BPF_ALU | BPF_LSH | BPF_X] = true,
991                 [BPF_ALU | BPF_RSH | BPF_K] = true,
992                 [BPF_ALU | BPF_RSH | BPF_X] = true,
993                 [BPF_ALU | BPF_NEG] = true,
994                 /* Load instructions */
995                 [BPF_LD | BPF_W | BPF_ABS] = true,
996                 [BPF_LD | BPF_H | BPF_ABS] = true,
997                 [BPF_LD | BPF_B | BPF_ABS] = true,
998                 [BPF_LD | BPF_W | BPF_LEN] = true,
999                 [BPF_LD | BPF_W | BPF_IND] = true,
1000                 [BPF_LD | BPF_H | BPF_IND] = true,
1001                 [BPF_LD | BPF_B | BPF_IND] = true,
1002                 [BPF_LD | BPF_IMM] = true,
1003                 [BPF_LD | BPF_MEM] = true,
1004                 [BPF_LDX | BPF_W | BPF_LEN] = true,
1005                 [BPF_LDX | BPF_B | BPF_MSH] = true,
1006                 [BPF_LDX | BPF_IMM] = true,
1007                 [BPF_LDX | BPF_MEM] = true,
1008                 /* Store instructions */
1009                 [BPF_ST] = true,
1010                 [BPF_STX] = true,
1011                 /* Misc instructions */
1012                 [BPF_MISC | BPF_TAX] = true,
1013                 [BPF_MISC | BPF_TXA] = true,
1014                 /* Return instructions */
1015                 [BPF_RET | BPF_K] = true,
1016                 [BPF_RET | BPF_A] = true,
1017                 /* Jump instructions */
1018                 [BPF_JMP | BPF_JA] = true,
1019                 [BPF_JMP | BPF_JEQ | BPF_K] = true,
1020                 [BPF_JMP | BPF_JEQ | BPF_X] = true,
1021                 [BPF_JMP | BPF_JGE | BPF_K] = true,
1022                 [BPF_JMP | BPF_JGE | BPF_X] = true,
1023                 [BPF_JMP | BPF_JGT | BPF_K] = true,
1024                 [BPF_JMP | BPF_JGT | BPF_X] = true,
1025                 [BPF_JMP | BPF_JSET | BPF_K] = true,
1026                 [BPF_JMP | BPF_JSET | BPF_X] = true,
1027         };
1028
1029         if (code_to_probe >= ARRAY_SIZE(codes))
1030                 return false;
1031
1032         return codes[code_to_probe];
1033 }
1034
1035 static bool bpf_check_basics_ok(const struct sock_filter *filter,
1036                                 unsigned int flen)
1037 {
1038         if (filter == NULL)
1039                 return false;
1040         if (flen == 0 || flen > BPF_MAXINSNS)
1041                 return false;
1042
1043         return true;
1044 }
1045
1046 /**
1047  *      bpf_check_classic - verify socket filter code
1048  *      @filter: filter to verify
1049  *      @flen: length of filter
1050  *
1051  * Check the user's filter code. If we let some ugly
1052  * filter code slip through kaboom! The filter must contain
1053  * no references or jumps that are out of range, no illegal
1054  * instructions, and must end with a RET instruction.
1055  *
1056  * All jumps are forward as they are not signed.
1057  *
1058  * Returns 0 if the rule set is legal or -EINVAL if not.
1059  */
1060 static int bpf_check_classic(const struct sock_filter *filter,
1061                              unsigned int flen)
1062 {
1063         bool anc_found;
1064         int pc;
1065
1066         /* Check the filter code now */
1067         for (pc = 0; pc < flen; pc++) {
1068                 const struct sock_filter *ftest = &filter[pc];
1069
1070                 /* May we actually operate on this code? */
1071                 if (!chk_code_allowed(ftest->code))
1072                         return -EINVAL;
1073
1074                 /* Some instructions need special checks */
1075                 switch (ftest->code) {
1076                 case BPF_ALU | BPF_DIV | BPF_K:
1077                 case BPF_ALU | BPF_MOD | BPF_K:
1078                         /* Check for division by zero */
1079                         if (ftest->k == 0)
1080                                 return -EINVAL;
1081                         break;
1082                 case BPF_ALU | BPF_LSH | BPF_K:
1083                 case BPF_ALU | BPF_RSH | BPF_K:
1084                         if (ftest->k >= 32)
1085                                 return -EINVAL;
1086                         break;
1087                 case BPF_LD | BPF_MEM:
1088                 case BPF_LDX | BPF_MEM:
1089                 case BPF_ST:
1090                 case BPF_STX:
1091                         /* Check for invalid memory addresses */
1092                         if (ftest->k >= BPF_MEMWORDS)
1093                                 return -EINVAL;
1094                         break;
1095                 case BPF_JMP | BPF_JA:
1096                         /* Note, the large ftest->k might cause loops.
1097                          * Compare this with conditional jumps below,
1098                          * where offsets are limited. --ANK (981016)
1099                          */
1100                         if (ftest->k >= (unsigned int)(flen - pc - 1))
1101                                 return -EINVAL;
1102                         break;
1103                 case BPF_JMP | BPF_JEQ | BPF_K:
1104                 case BPF_JMP | BPF_JEQ | BPF_X:
1105                 case BPF_JMP | BPF_JGE | BPF_K:
1106                 case BPF_JMP | BPF_JGE | BPF_X:
1107                 case BPF_JMP | BPF_JGT | BPF_K:
1108                 case BPF_JMP | BPF_JGT | BPF_X:
1109                 case BPF_JMP | BPF_JSET | BPF_K:
1110                 case BPF_JMP | BPF_JSET | BPF_X:
1111                         /* Both conditionals must be safe */
1112                         if (pc + ftest->jt + 1 >= flen ||
1113                             pc + ftest->jf + 1 >= flen)
1114                                 return -EINVAL;
1115                         break;
1116                 case BPF_LD | BPF_W | BPF_ABS:
1117                 case BPF_LD | BPF_H | BPF_ABS:
1118                 case BPF_LD | BPF_B | BPF_ABS:
1119                         anc_found = false;
1120                         if (bpf_anc_helper(ftest) & BPF_ANC)
1121                                 anc_found = true;
1122                         /* Ancillary operation unknown or unsupported */
1123                         if (anc_found == false && ftest->k >= SKF_AD_OFF)
1124                                 return -EINVAL;
1125                 }
1126         }
1127
1128         /* Last instruction must be a RET code */
1129         switch (filter[flen - 1].code) {
1130         case BPF_RET | BPF_K:
1131         case BPF_RET | BPF_A:
1132                 return check_load_and_stores(filter, flen);
1133         }
1134
1135         return -EINVAL;
1136 }
1137
1138 static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
1139                                       const struct sock_fprog *fprog)
1140 {
1141         unsigned int fsize = bpf_classic_proglen(fprog);
1142         struct sock_fprog_kern *fkprog;
1143
1144         fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
1145         if (!fp->orig_prog)
1146                 return -ENOMEM;
1147
1148         fkprog = fp->orig_prog;
1149         fkprog->len = fprog->len;
1150
1151         fkprog->filter = kmemdup(fp->insns, fsize,
1152                                  GFP_KERNEL | __GFP_NOWARN);
1153         if (!fkprog->filter) {
1154                 kfree(fp->orig_prog);
1155                 return -ENOMEM;
1156         }
1157
1158         return 0;
1159 }
1160
1161 static void bpf_release_orig_filter(struct bpf_prog *fp)
1162 {
1163         struct sock_fprog_kern *fprog = fp->orig_prog;
1164
1165         if (fprog) {
1166                 kfree(fprog->filter);
1167                 kfree(fprog);
1168         }
1169 }
1170
1171 static void __bpf_prog_release(struct bpf_prog *prog)
1172 {
1173         if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
1174                 bpf_prog_put(prog);
1175         } else {
1176                 bpf_release_orig_filter(prog);
1177                 bpf_prog_free(prog);
1178         }
1179 }
1180
1181 static void __sk_filter_release(struct sk_filter *fp)
1182 {
1183         __bpf_prog_release(fp->prog);
1184         kfree(fp);
1185 }
1186
1187 /**
1188  *      sk_filter_release_rcu - Release a socket filter by rcu_head
1189  *      @rcu: rcu_head that contains the sk_filter to free
1190  */
1191 static void sk_filter_release_rcu(struct rcu_head *rcu)
1192 {
1193         struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
1194
1195         __sk_filter_release(fp);
1196 }
1197
1198 /**
1199  *      sk_filter_release - release a socket filter
1200  *      @fp: filter to remove
1201  *
1202  *      Remove a filter from a socket and release its resources.
1203  */
1204 static void sk_filter_release(struct sk_filter *fp)
1205 {
1206         if (refcount_dec_and_test(&fp->refcnt))
1207                 call_rcu(&fp->rcu, sk_filter_release_rcu);
1208 }
1209
1210 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
1211 {
1212         u32 filter_size = bpf_prog_size(fp->prog->len);
1213
1214         atomic_sub(filter_size, &sk->sk_omem_alloc);
1215         sk_filter_release(fp);
1216 }
1217
1218 /* try to charge the socket memory if there is space available
1219  * return true on success
1220  */
1221 static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1222 {
1223         int optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max);
1224         u32 filter_size = bpf_prog_size(fp->prog->len);
1225
1226         /* same check as in sock_kmalloc() */
1227         if (filter_size <= optmem_max &&
1228             atomic_read(&sk->sk_omem_alloc) + filter_size < optmem_max) {
1229                 atomic_add(filter_size, &sk->sk_omem_alloc);
1230                 return true;
1231         }
1232         return false;
1233 }
1234
1235 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1236 {
1237         if (!refcount_inc_not_zero(&fp->refcnt))
1238                 return false;
1239
1240         if (!__sk_filter_charge(sk, fp)) {
1241                 sk_filter_release(fp);
1242                 return false;
1243         }
1244         return true;
1245 }
1246
1247 static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
1248 {
1249         struct sock_filter *old_prog;
1250         struct bpf_prog *old_fp;
1251         int err, new_len, old_len = fp->len;
1252         bool seen_ld_abs = false;
1253
1254         /* We are free to overwrite insns et al right here as it won't be used at
1255          * this point in time anymore internally after the migration to the eBPF
1256          * instruction representation.
1257          */
1258         BUILD_BUG_ON(sizeof(struct sock_filter) !=
1259                      sizeof(struct bpf_insn));
1260
1261         /* Conversion cannot happen on overlapping memory areas,
1262          * so we need to keep the user BPF around until the 2nd
1263          * pass. At this time, the user BPF is stored in fp->insns.
1264          */
1265         old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
1266                            GFP_KERNEL | __GFP_NOWARN);
1267         if (!old_prog) {
1268                 err = -ENOMEM;
1269                 goto out_err;
1270         }
1271
1272         /* 1st pass: calculate the new program length. */
1273         err = bpf_convert_filter(old_prog, old_len, NULL, &new_len,
1274                                  &seen_ld_abs);
1275         if (err)
1276                 goto out_err_free;
1277
1278         /* Expand fp for appending the new filter representation. */
1279         old_fp = fp;
1280         fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1281         if (!fp) {
1282                 /* The old_fp is still around in case we couldn't
1283                  * allocate new memory, so uncharge on that one.
1284                  */
1285                 fp = old_fp;
1286                 err = -ENOMEM;
1287                 goto out_err_free;
1288         }
1289
1290         fp->len = new_len;
1291
1292         /* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1293         err = bpf_convert_filter(old_prog, old_len, fp, &new_len,
1294                                  &seen_ld_abs);
1295         if (err)
1296                 /* 2nd bpf_convert_filter() can fail only if it fails
1297                  * to allocate memory, remapping must succeed. Note,
1298                  * that at this time old_fp has already been released
1299                  * by krealloc().
1300                  */
1301                 goto out_err_free;
1302
1303         fp = bpf_prog_select_runtime(fp, &err);
1304         if (err)
1305                 goto out_err_free;
1306
1307         kfree(old_prog);
1308         return fp;
1309
1310 out_err_free:
1311         kfree(old_prog);
1312 out_err:
1313         __bpf_prog_release(fp);
1314         return ERR_PTR(err);
1315 }
1316
1317 static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
1318                                            bpf_aux_classic_check_t trans)
1319 {
1320         int err;
1321
1322         fp->bpf_func = NULL;
1323         fp->jited = 0;
1324
1325         err = bpf_check_classic(fp->insns, fp->len);
1326         if (err) {
1327                 __bpf_prog_release(fp);
1328                 return ERR_PTR(err);
1329         }
1330
1331         /* There might be additional checks and transformations
1332          * needed on classic filters, f.e. in case of seccomp.
1333          */
1334         if (trans) {
1335                 err = trans(fp->insns, fp->len);
1336                 if (err) {
1337                         __bpf_prog_release(fp);
1338                         return ERR_PTR(err);
1339                 }
1340         }
1341
1342         /* Probe if we can JIT compile the filter and if so, do
1343          * the compilation of the filter.
1344          */
1345         bpf_jit_compile(fp);
1346
1347         /* JIT compiler couldn't process this filter, so do the eBPF translation
1348          * for the optimized interpreter.
1349          */
1350         if (!fp->jited)
1351                 fp = bpf_migrate_filter(fp);
1352
1353         return fp;
1354 }
1355
1356 /**
1357  *      bpf_prog_create - create an unattached filter
1358  *      @pfp: the unattached filter that is created
1359  *      @fprog: the filter program
1360  *
1361  * Create a filter independent of any socket. We first run some
1362  * sanity checks on it to make sure it does not explode on us later.
1363  * If an error occurs or there is insufficient memory for the filter
1364  * a negative errno code is returned. On success the return is zero.
1365  */
1366 int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1367 {
1368         unsigned int fsize = bpf_classic_proglen(fprog);
1369         struct bpf_prog *fp;
1370
1371         /* Make sure new filter is there and in the right amounts. */
1372         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1373                 return -EINVAL;
1374
1375         fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1376         if (!fp)
1377                 return -ENOMEM;
1378
1379         memcpy(fp->insns, fprog->filter, fsize);
1380
1381         fp->len = fprog->len;
1382         /* Since unattached filters are not copied back to user
1383          * space through sk_get_filter(), we do not need to hold
1384          * a copy here, and can spare us the work.
1385          */
1386         fp->orig_prog = NULL;
1387
1388         /* bpf_prepare_filter() already takes care of freeing
1389          * memory in case something goes wrong.
1390          */
1391         fp = bpf_prepare_filter(fp, NULL);
1392         if (IS_ERR(fp))
1393                 return PTR_ERR(fp);
1394
1395         *pfp = fp;
1396         return 0;
1397 }
1398 EXPORT_SYMBOL_GPL(bpf_prog_create);
1399
1400 /**
1401  *      bpf_prog_create_from_user - create an unattached filter from user buffer
1402  *      @pfp: the unattached filter that is created
1403  *      @fprog: the filter program
1404  *      @trans: post-classic verifier transformation handler
1405  *      @save_orig: save classic BPF program
1406  *
1407  * This function effectively does the same as bpf_prog_create(), only
1408  * that it builds up its insns buffer from user space provided buffer.
1409  * It also allows for passing a bpf_aux_classic_check_t handler.
1410  */
1411 int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1412                               bpf_aux_classic_check_t trans, bool save_orig)
1413 {
1414         unsigned int fsize = bpf_classic_proglen(fprog);
1415         struct bpf_prog *fp;
1416         int err;
1417
1418         /* Make sure new filter is there and in the right amounts. */
1419         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1420                 return -EINVAL;
1421
1422         fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1423         if (!fp)
1424                 return -ENOMEM;
1425
1426         if (copy_from_user(fp->insns, fprog->filter, fsize)) {
1427                 __bpf_prog_free(fp);
1428                 return -EFAULT;
1429         }
1430
1431         fp->len = fprog->len;
1432         fp->orig_prog = NULL;
1433
1434         if (save_orig) {
1435                 err = bpf_prog_store_orig_filter(fp, fprog);
1436                 if (err) {
1437                         __bpf_prog_free(fp);
1438                         return -ENOMEM;
1439                 }
1440         }
1441
1442         /* bpf_prepare_filter() already takes care of freeing
1443          * memory in case something goes wrong.
1444          */
1445         fp = bpf_prepare_filter(fp, trans);
1446         if (IS_ERR(fp))
1447                 return PTR_ERR(fp);
1448
1449         *pfp = fp;
1450         return 0;
1451 }
1452 EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1453
1454 void bpf_prog_destroy(struct bpf_prog *fp)
1455 {
1456         __bpf_prog_release(fp);
1457 }
1458 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1459
1460 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1461 {
1462         struct sk_filter *fp, *old_fp;
1463
1464         fp = kmalloc(sizeof(*fp), GFP_KERNEL);
1465         if (!fp)
1466                 return -ENOMEM;
1467
1468         fp->prog = prog;
1469
1470         if (!__sk_filter_charge(sk, fp)) {
1471                 kfree(fp);
1472                 return -ENOMEM;
1473         }
1474         refcount_set(&fp->refcnt, 1);
1475
1476         old_fp = rcu_dereference_protected(sk->sk_filter,
1477                                            lockdep_sock_is_held(sk));
1478         rcu_assign_pointer(sk->sk_filter, fp);
1479
1480         if (old_fp)
1481                 sk_filter_uncharge(sk, old_fp);
1482
1483         return 0;
1484 }
1485
1486 static
1487 struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
1488 {
1489         unsigned int fsize = bpf_classic_proglen(fprog);
1490         struct bpf_prog *prog;
1491         int err;
1492
1493         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1494                 return ERR_PTR(-EPERM);
1495
1496         /* Make sure new filter is there and in the right amounts. */
1497         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1498                 return ERR_PTR(-EINVAL);
1499
1500         prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1501         if (!prog)
1502                 return ERR_PTR(-ENOMEM);
1503
1504         if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1505                 __bpf_prog_free(prog);
1506                 return ERR_PTR(-EFAULT);
1507         }
1508
1509         prog->len = fprog->len;
1510
1511         err = bpf_prog_store_orig_filter(prog, fprog);
1512         if (err) {
1513                 __bpf_prog_free(prog);
1514                 return ERR_PTR(-ENOMEM);
1515         }
1516
1517         /* bpf_prepare_filter() already takes care of freeing
1518          * memory in case something goes wrong.
1519          */
1520         return bpf_prepare_filter(prog, NULL);
1521 }
1522
1523 /**
1524  *      sk_attach_filter - attach a socket filter
1525  *      @fprog: the filter program
1526  *      @sk: the socket to use
1527  *
1528  * Attach the user's filter code. We first run some sanity checks on
1529  * it to make sure it does not explode on us later. If an error
1530  * occurs or there is insufficient memory for the filter a negative
1531  * errno code is returned. On success the return is zero.
1532  */
1533 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1534 {
1535         struct bpf_prog *prog = __get_filter(fprog, sk);
1536         int err;
1537
1538         if (IS_ERR(prog))
1539                 return PTR_ERR(prog);
1540
1541         err = __sk_attach_prog(prog, sk);
1542         if (err < 0) {
1543                 __bpf_prog_release(prog);
1544                 return err;
1545         }
1546
1547         return 0;
1548 }
1549 EXPORT_SYMBOL_GPL(sk_attach_filter);
1550
1551 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1552 {
1553         struct bpf_prog *prog = __get_filter(fprog, sk);
1554         int err, optmem_max;
1555
1556         if (IS_ERR(prog))
1557                 return PTR_ERR(prog);
1558
1559         optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max);
1560         if (bpf_prog_size(prog->len) > optmem_max)
1561                 err = -ENOMEM;
1562         else
1563                 err = reuseport_attach_prog(sk, prog);
1564
1565         if (err)
1566                 __bpf_prog_release(prog);
1567
1568         return err;
1569 }
1570
1571 static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
1572 {
1573         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1574                 return ERR_PTR(-EPERM);
1575
1576         return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1577 }
1578
1579 int sk_attach_bpf(u32 ufd, struct sock *sk)
1580 {
1581         struct bpf_prog *prog = __get_bpf(ufd, sk);
1582         int err;
1583
1584         if (IS_ERR(prog))
1585                 return PTR_ERR(prog);
1586
1587         err = __sk_attach_prog(prog, sk);
1588         if (err < 0) {
1589                 bpf_prog_put(prog);
1590                 return err;
1591         }
1592
1593         return 0;
1594 }
1595
1596 int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
1597 {
1598         struct bpf_prog *prog;
1599         int err, optmem_max;
1600
1601         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1602                 return -EPERM;
1603
1604         prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1605         if (PTR_ERR(prog) == -EINVAL)
1606                 prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SK_REUSEPORT);
1607         if (IS_ERR(prog))
1608                 return PTR_ERR(prog);
1609
1610         if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) {
1611                 /* Like other non BPF_PROG_TYPE_SOCKET_FILTER
1612                  * bpf prog (e.g. sockmap).  It depends on the
1613                  * limitation imposed by bpf_prog_load().
1614                  * Hence, sysctl_optmem_max is not checked.
1615                  */
1616                 if ((sk->sk_type != SOCK_STREAM &&
1617                      sk->sk_type != SOCK_DGRAM) ||
1618                     (sk->sk_protocol != IPPROTO_UDP &&
1619                      sk->sk_protocol != IPPROTO_TCP) ||
1620                     (sk->sk_family != AF_INET &&
1621                      sk->sk_family != AF_INET6)) {
1622                         err = -ENOTSUPP;
1623                         goto err_prog_put;
1624                 }
1625         } else {
1626                 /* BPF_PROG_TYPE_SOCKET_FILTER */
1627                 optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max);
1628                 if (bpf_prog_size(prog->len) > optmem_max) {
1629                         err = -ENOMEM;
1630                         goto err_prog_put;
1631                 }
1632         }
1633
1634         err = reuseport_attach_prog(sk, prog);
1635 err_prog_put:
1636         if (err)
1637                 bpf_prog_put(prog);
1638
1639         return err;
1640 }
1641
1642 void sk_reuseport_prog_free(struct bpf_prog *prog)
1643 {
1644         if (!prog)
1645                 return;
1646
1647         if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT)
1648                 bpf_prog_put(prog);
1649         else
1650                 bpf_prog_destroy(prog);
1651 }
1652
1653 struct bpf_scratchpad {
1654         union {
1655                 __be32 diff[MAX_BPF_STACK / sizeof(__be32)];
1656                 u8     buff[MAX_BPF_STACK];
1657         };
1658 };
1659
1660 static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp);
1661
1662 static inline int __bpf_try_make_writable(struct sk_buff *skb,
1663                                           unsigned int write_len)
1664 {
1665         return skb_ensure_writable(skb, write_len);
1666 }
1667
1668 static inline int bpf_try_make_writable(struct sk_buff *skb,
1669                                         unsigned int write_len)
1670 {
1671         int err = __bpf_try_make_writable(skb, write_len);
1672
1673         bpf_compute_data_pointers(skb);
1674         return err;
1675 }
1676
1677 static int bpf_try_make_head_writable(struct sk_buff *skb)
1678 {
1679         return bpf_try_make_writable(skb, skb_headlen(skb));
1680 }
1681
1682 static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
1683 {
1684         if (skb_at_tc_ingress(skb))
1685                 skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1686 }
1687
1688 static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
1689 {
1690         if (skb_at_tc_ingress(skb))
1691                 skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1692 }
1693
1694 BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
1695            const void *, from, u32, len, u64, flags)
1696 {
1697         void *ptr;
1698
1699         if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1700                 return -EINVAL;
1701         if (unlikely(offset > INT_MAX))
1702                 return -EFAULT;
1703         if (unlikely(bpf_try_make_writable(skb, offset + len)))
1704                 return -EFAULT;
1705
1706         ptr = skb->data + offset;
1707         if (flags & BPF_F_RECOMPUTE_CSUM)
1708                 __skb_postpull_rcsum(skb, ptr, len, offset);
1709
1710         memcpy(ptr, from, len);
1711
1712         if (flags & BPF_F_RECOMPUTE_CSUM)
1713                 __skb_postpush_rcsum(skb, ptr, len, offset);
1714         if (flags & BPF_F_INVALIDATE_HASH)
1715                 skb_clear_hash(skb);
1716
1717         return 0;
1718 }
1719
1720 static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1721         .func           = bpf_skb_store_bytes,
1722         .gpl_only       = false,
1723         .ret_type       = RET_INTEGER,
1724         .arg1_type      = ARG_PTR_TO_CTX,
1725         .arg2_type      = ARG_ANYTHING,
1726         .arg3_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
1727         .arg4_type      = ARG_CONST_SIZE,
1728         .arg5_type      = ARG_ANYTHING,
1729 };
1730
1731 int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from,
1732                           u32 len, u64 flags)
1733 {
1734         return ____bpf_skb_store_bytes(skb, offset, from, len, flags);
1735 }
1736
1737 BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
1738            void *, to, u32, len)
1739 {
1740         void *ptr;
1741
1742         if (unlikely(offset > INT_MAX))
1743                 goto err_clear;
1744
1745         ptr = skb_header_pointer(skb, offset, len, to);
1746         if (unlikely(!ptr))
1747                 goto err_clear;
1748         if (ptr != to)
1749                 memcpy(to, ptr, len);
1750
1751         return 0;
1752 err_clear:
1753         memset(to, 0, len);
1754         return -EFAULT;
1755 }
1756
1757 static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1758         .func           = bpf_skb_load_bytes,
1759         .gpl_only       = false,
1760         .ret_type       = RET_INTEGER,
1761         .arg1_type      = ARG_PTR_TO_CTX,
1762         .arg2_type      = ARG_ANYTHING,
1763         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1764         .arg4_type      = ARG_CONST_SIZE,
1765 };
1766
1767 int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset, void *to, u32 len)
1768 {
1769         return ____bpf_skb_load_bytes(skb, offset, to, len);
1770 }
1771
1772 BPF_CALL_4(bpf_flow_dissector_load_bytes,
1773            const struct bpf_flow_dissector *, ctx, u32, offset,
1774            void *, to, u32, len)
1775 {
1776         void *ptr;
1777
1778         if (unlikely(offset > 0xffff))
1779                 goto err_clear;
1780
1781         if (unlikely(!ctx->skb))
1782                 goto err_clear;
1783
1784         ptr = skb_header_pointer(ctx->skb, offset, len, to);
1785         if (unlikely(!ptr))
1786                 goto err_clear;
1787         if (ptr != to)
1788                 memcpy(to, ptr, len);
1789
1790         return 0;
1791 err_clear:
1792         memset(to, 0, len);
1793         return -EFAULT;
1794 }
1795
1796 static const struct bpf_func_proto bpf_flow_dissector_load_bytes_proto = {
1797         .func           = bpf_flow_dissector_load_bytes,
1798         .gpl_only       = false,
1799         .ret_type       = RET_INTEGER,
1800         .arg1_type      = ARG_PTR_TO_CTX,
1801         .arg2_type      = ARG_ANYTHING,
1802         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1803         .arg4_type      = ARG_CONST_SIZE,
1804 };
1805
1806 BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb,
1807            u32, offset, void *, to, u32, len, u32, start_header)
1808 {
1809         u8 *end = skb_tail_pointer(skb);
1810         u8 *start, *ptr;
1811
1812         if (unlikely(offset > 0xffff))
1813                 goto err_clear;
1814
1815         switch (start_header) {
1816         case BPF_HDR_START_MAC:
1817                 if (unlikely(!skb_mac_header_was_set(skb)))
1818                         goto err_clear;
1819                 start = skb_mac_header(skb);
1820                 break;
1821         case BPF_HDR_START_NET:
1822                 start = skb_network_header(skb);
1823                 break;
1824         default:
1825                 goto err_clear;
1826         }
1827
1828         ptr = start + offset;
1829
1830         if (likely(ptr + len <= end)) {
1831                 memcpy(to, ptr, len);
1832                 return 0;
1833         }
1834
1835 err_clear:
1836         memset(to, 0, len);
1837         return -EFAULT;
1838 }
1839
1840 static const struct bpf_func_proto bpf_skb_load_bytes_relative_proto = {
1841         .func           = bpf_skb_load_bytes_relative,
1842         .gpl_only       = false,
1843         .ret_type       = RET_INTEGER,
1844         .arg1_type      = ARG_PTR_TO_CTX,
1845         .arg2_type      = ARG_ANYTHING,
1846         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1847         .arg4_type      = ARG_CONST_SIZE,
1848         .arg5_type      = ARG_ANYTHING,
1849 };
1850
1851 BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
1852 {
1853         /* Idea is the following: should the needed direct read/write
1854          * test fail during runtime, we can pull in more data and redo
1855          * again, since implicitly, we invalidate previous checks here.
1856          *
1857          * Or, since we know how much we need to make read/writeable,
1858          * this can be done once at the program beginning for direct
1859          * access case. By this we overcome limitations of only current
1860          * headroom being accessible.
1861          */
1862         return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
1863 }
1864
1865 static const struct bpf_func_proto bpf_skb_pull_data_proto = {
1866         .func           = bpf_skb_pull_data,
1867         .gpl_only       = false,
1868         .ret_type       = RET_INTEGER,
1869         .arg1_type      = ARG_PTR_TO_CTX,
1870         .arg2_type      = ARG_ANYTHING,
1871 };
1872
1873 BPF_CALL_1(bpf_sk_fullsock, struct sock *, sk)
1874 {
1875         return sk_fullsock(sk) ? (unsigned long)sk : (unsigned long)NULL;
1876 }
1877
1878 static const struct bpf_func_proto bpf_sk_fullsock_proto = {
1879         .func           = bpf_sk_fullsock,
1880         .gpl_only       = false,
1881         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
1882         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
1883 };
1884
1885 static inline int sk_skb_try_make_writable(struct sk_buff *skb,
1886                                            unsigned int write_len)
1887 {
1888         return __bpf_try_make_writable(skb, write_len);
1889 }
1890
1891 BPF_CALL_2(sk_skb_pull_data, struct sk_buff *, skb, u32, len)
1892 {
1893         /* Idea is the following: should the needed direct read/write
1894          * test fail during runtime, we can pull in more data and redo
1895          * again, since implicitly, we invalidate previous checks here.
1896          *
1897          * Or, since we know how much we need to make read/writeable,
1898          * this can be done once at the program beginning for direct
1899          * access case. By this we overcome limitations of only current
1900          * headroom being accessible.
1901          */
1902         return sk_skb_try_make_writable(skb, len ? : skb_headlen(skb));
1903 }
1904
1905 static const struct bpf_func_proto sk_skb_pull_data_proto = {
1906         .func           = sk_skb_pull_data,
1907         .gpl_only       = false,
1908         .ret_type       = RET_INTEGER,
1909         .arg1_type      = ARG_PTR_TO_CTX,
1910         .arg2_type      = ARG_ANYTHING,
1911 };
1912
1913 BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
1914            u64, from, u64, to, u64, flags)
1915 {
1916         __sum16 *ptr;
1917
1918         if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
1919                 return -EINVAL;
1920         if (unlikely(offset > 0xffff || offset & 1))
1921                 return -EFAULT;
1922         if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1923                 return -EFAULT;
1924
1925         ptr = (__sum16 *)(skb->data + offset);
1926         switch (flags & BPF_F_HDR_FIELD_MASK) {
1927         case 0:
1928                 if (unlikely(from != 0))
1929                         return -EINVAL;
1930
1931                 csum_replace_by_diff(ptr, to);
1932                 break;
1933         case 2:
1934                 csum_replace2(ptr, from, to);
1935                 break;
1936         case 4:
1937                 csum_replace4(ptr, from, to);
1938                 break;
1939         default:
1940                 return -EINVAL;
1941         }
1942
1943         return 0;
1944 }
1945
1946 static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1947         .func           = bpf_l3_csum_replace,
1948         .gpl_only       = false,
1949         .ret_type       = RET_INTEGER,
1950         .arg1_type      = ARG_PTR_TO_CTX,
1951         .arg2_type      = ARG_ANYTHING,
1952         .arg3_type      = ARG_ANYTHING,
1953         .arg4_type      = ARG_ANYTHING,
1954         .arg5_type      = ARG_ANYTHING,
1955 };
1956
1957 BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
1958            u64, from, u64, to, u64, flags)
1959 {
1960         bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1961         bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1962         bool do_mforce = flags & BPF_F_MARK_ENFORCE;
1963         __sum16 *ptr;
1964
1965         if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
1966                                BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK)))
1967                 return -EINVAL;
1968         if (unlikely(offset > 0xffff || offset & 1))
1969                 return -EFAULT;
1970         if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1971                 return -EFAULT;
1972
1973         ptr = (__sum16 *)(skb->data + offset);
1974         if (is_mmzero && !do_mforce && !*ptr)
1975                 return 0;
1976
1977         switch (flags & BPF_F_HDR_FIELD_MASK) {
1978         case 0:
1979                 if (unlikely(from != 0))
1980                         return -EINVAL;
1981
1982                 inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
1983                 break;
1984         case 2:
1985                 inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
1986                 break;
1987         case 4:
1988                 inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
1989                 break;
1990         default:
1991                 return -EINVAL;
1992         }
1993
1994         if (is_mmzero && !*ptr)
1995                 *ptr = CSUM_MANGLED_0;
1996         return 0;
1997 }
1998
1999 static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
2000         .func           = bpf_l4_csum_replace,
2001         .gpl_only       = false,
2002         .ret_type       = RET_INTEGER,
2003         .arg1_type      = ARG_PTR_TO_CTX,
2004         .arg2_type      = ARG_ANYTHING,
2005         .arg3_type      = ARG_ANYTHING,
2006         .arg4_type      = ARG_ANYTHING,
2007         .arg5_type      = ARG_ANYTHING,
2008 };
2009
2010 BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
2011            __be32 *, to, u32, to_size, __wsum, seed)
2012 {
2013         struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
2014         u32 diff_size = from_size + to_size;
2015         int i, j = 0;
2016
2017         /* This is quite flexible, some examples:
2018          *
2019          * from_size == 0, to_size > 0,  seed := csum --> pushing data
2020          * from_size > 0,  to_size == 0, seed := csum --> pulling data
2021          * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
2022          *
2023          * Even for diffing, from_size and to_size don't need to be equal.
2024          */
2025         if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) ||
2026                      diff_size > sizeof(sp->diff)))
2027                 return -EINVAL;
2028
2029         for (i = 0; i < from_size / sizeof(__be32); i++, j++)
2030                 sp->diff[j] = ~from[i];
2031         for (i = 0; i <   to_size / sizeof(__be32); i++, j++)
2032                 sp->diff[j] = to[i];
2033
2034         return csum_partial(sp->diff, diff_size, seed);
2035 }
2036
2037 static const struct bpf_func_proto bpf_csum_diff_proto = {
2038         .func           = bpf_csum_diff,
2039         .gpl_only       = false,
2040         .pkt_access     = true,
2041         .ret_type       = RET_INTEGER,
2042         .arg1_type      = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
2043         .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
2044         .arg3_type      = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
2045         .arg4_type      = ARG_CONST_SIZE_OR_ZERO,
2046         .arg5_type      = ARG_ANYTHING,
2047 };
2048
2049 BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
2050 {
2051         /* The interface is to be used in combination with bpf_csum_diff()
2052          * for direct packet writes. csum rotation for alignment as well
2053          * as emulating csum_sub() can be done from the eBPF program.
2054          */
2055         if (skb->ip_summed == CHECKSUM_COMPLETE)
2056                 return (skb->csum = csum_add(skb->csum, csum));
2057
2058         return -ENOTSUPP;
2059 }
2060
2061 static const struct bpf_func_proto bpf_csum_update_proto = {
2062         .func           = bpf_csum_update,
2063         .gpl_only       = false,
2064         .ret_type       = RET_INTEGER,
2065         .arg1_type      = ARG_PTR_TO_CTX,
2066         .arg2_type      = ARG_ANYTHING,
2067 };
2068
2069 BPF_CALL_2(bpf_csum_level, struct sk_buff *, skb, u64, level)
2070 {
2071         /* The interface is to be used in combination with bpf_skb_adjust_room()
2072          * for encap/decap of packet headers when BPF_F_ADJ_ROOM_NO_CSUM_RESET
2073          * is passed as flags, for example.
2074          */
2075         switch (level) {
2076         case BPF_CSUM_LEVEL_INC:
2077                 __skb_incr_checksum_unnecessary(skb);
2078                 break;
2079         case BPF_CSUM_LEVEL_DEC:
2080                 __skb_decr_checksum_unnecessary(skb);
2081                 break;
2082         case BPF_CSUM_LEVEL_RESET:
2083                 __skb_reset_checksum_unnecessary(skb);
2084                 break;
2085         case BPF_CSUM_LEVEL_QUERY:
2086                 return skb->ip_summed == CHECKSUM_UNNECESSARY ?
2087                        skb->csum_level : -EACCES;
2088         default:
2089                 return -EINVAL;
2090         }
2091
2092         return 0;
2093 }
2094
2095 static const struct bpf_func_proto bpf_csum_level_proto = {
2096         .func           = bpf_csum_level,
2097         .gpl_only       = false,
2098         .ret_type       = RET_INTEGER,
2099         .arg1_type      = ARG_PTR_TO_CTX,
2100         .arg2_type      = ARG_ANYTHING,
2101 };
2102
2103 static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
2104 {
2105         return dev_forward_skb_nomtu(dev, skb);
2106 }
2107
2108 static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
2109                                       struct sk_buff *skb)
2110 {
2111         int ret = ____dev_forward_skb(dev, skb, false);
2112
2113         if (likely(!ret)) {
2114                 skb->dev = dev;
2115                 ret = netif_rx(skb);
2116         }
2117
2118         return ret;
2119 }
2120
2121 static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
2122 {
2123         int ret;
2124
2125         if (dev_xmit_recursion()) {
2126                 net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2127                 kfree_skb(skb);
2128                 return -ENETDOWN;
2129         }
2130
2131         skb->dev = dev;
2132         skb_set_redirected_noclear(skb, skb_at_tc_ingress(skb));
2133         skb_clear_tstamp(skb);
2134
2135         dev_xmit_recursion_inc();
2136         ret = dev_queue_xmit(skb);
2137         dev_xmit_recursion_dec();
2138
2139         return ret;
2140 }
2141
2142 static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
2143                                  u32 flags)
2144 {
2145         unsigned int mlen = skb_network_offset(skb);
2146
2147         if (unlikely(skb->len <= mlen)) {
2148                 kfree_skb(skb);
2149                 return -ERANGE;
2150         }
2151
2152         if (mlen) {
2153                 __skb_pull(skb, mlen);
2154
2155                 /* At ingress, the mac header has already been pulled once.
2156                  * At egress, skb_pospull_rcsum has to be done in case that
2157                  * the skb is originated from ingress (i.e. a forwarded skb)
2158                  * to ensure that rcsum starts at net header.
2159                  */
2160                 if (!skb_at_tc_ingress(skb))
2161                         skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
2162         }
2163         skb_pop_mac_header(skb);
2164         skb_reset_mac_len(skb);
2165         return flags & BPF_F_INGRESS ?
2166                __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
2167 }
2168
2169 static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
2170                                  u32 flags)
2171 {
2172         /* Verify that a link layer header is carried */
2173         if (unlikely(skb->mac_header >= skb->network_header || skb->len == 0)) {
2174                 kfree_skb(skb);
2175                 return -ERANGE;
2176         }
2177
2178         bpf_push_mac_rcsum(skb);
2179         return flags & BPF_F_INGRESS ?
2180                __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
2181 }
2182
2183 static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
2184                           u32 flags)
2185 {
2186         if (dev_is_mac_header_xmit(dev))
2187                 return __bpf_redirect_common(skb, dev, flags);
2188         else
2189                 return __bpf_redirect_no_mac(skb, dev, flags);
2190 }
2191
2192 #if IS_ENABLED(CONFIG_IPV6)
2193 static int bpf_out_neigh_v6(struct net *net, struct sk_buff *skb,
2194                             struct net_device *dev, struct bpf_nh_params *nh)
2195 {
2196         u32 hh_len = LL_RESERVED_SPACE(dev);
2197         const struct in6_addr *nexthop;
2198         struct dst_entry *dst = NULL;
2199         struct neighbour *neigh;
2200
2201         if (dev_xmit_recursion()) {
2202                 net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2203                 goto out_drop;
2204         }
2205
2206         skb->dev = dev;
2207         skb_clear_tstamp(skb);
2208
2209         if (unlikely(skb_headroom(skb) < hh_len && dev->header_ops)) {
2210                 skb = skb_expand_head(skb, hh_len);
2211                 if (!skb)
2212                         return -ENOMEM;
2213         }
2214
2215         rcu_read_lock();
2216         if (!nh) {
2217                 dst = skb_dst(skb);
2218                 nexthop = rt6_nexthop(container_of(dst, struct rt6_info, dst),
2219                                       &ipv6_hdr(skb)->daddr);
2220         } else {
2221                 nexthop = &nh->ipv6_nh;
2222         }
2223         neigh = ip_neigh_gw6(dev, nexthop);
2224         if (likely(!IS_ERR(neigh))) {
2225                 int ret;
2226
2227                 sock_confirm_neigh(skb, neigh);
2228                 local_bh_disable();
2229                 dev_xmit_recursion_inc();
2230                 ret = neigh_output(neigh, skb, false);
2231                 dev_xmit_recursion_dec();
2232                 local_bh_enable();
2233                 rcu_read_unlock();
2234                 return ret;
2235         }
2236         rcu_read_unlock_bh();
2237         if (dst)
2238                 IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES);
2239 out_drop:
2240         kfree_skb(skb);
2241         return -ENETDOWN;
2242 }
2243
2244 static int __bpf_redirect_neigh_v6(struct sk_buff *skb, struct net_device *dev,
2245                                    struct bpf_nh_params *nh)
2246 {
2247         const struct ipv6hdr *ip6h = ipv6_hdr(skb);
2248         struct net *net = dev_net(dev);
2249         int err, ret = NET_XMIT_DROP;
2250
2251         if (!nh) {
2252                 struct dst_entry *dst;
2253                 struct flowi6 fl6 = {
2254                         .flowi6_flags = FLOWI_FLAG_ANYSRC,
2255                         .flowi6_mark  = skb->mark,
2256                         .flowlabel    = ip6_flowinfo(ip6h),
2257                         .flowi6_oif   = dev->ifindex,
2258                         .flowi6_proto = ip6h->nexthdr,
2259                         .daddr        = ip6h->daddr,
2260                         .saddr        = ip6h->saddr,
2261                 };
2262
2263                 dst = ipv6_stub->ipv6_dst_lookup_flow(net, NULL, &fl6, NULL);
2264                 if (IS_ERR(dst))
2265                         goto out_drop;
2266
2267                 skb_dst_set(skb, dst);
2268         } else if (nh->nh_family != AF_INET6) {
2269                 goto out_drop;
2270         }
2271
2272         err = bpf_out_neigh_v6(net, skb, dev, nh);
2273         if (unlikely(net_xmit_eval(err)))
2274                 dev->stats.tx_errors++;
2275         else
2276                 ret = NET_XMIT_SUCCESS;
2277         goto out_xmit;
2278 out_drop:
2279         dev->stats.tx_errors++;
2280         kfree_skb(skb);
2281 out_xmit:
2282         return ret;
2283 }
2284 #else
2285 static int __bpf_redirect_neigh_v6(struct sk_buff *skb, struct net_device *dev,
2286                                    struct bpf_nh_params *nh)
2287 {
2288         kfree_skb(skb);
2289         return NET_XMIT_DROP;
2290 }
2291 #endif /* CONFIG_IPV6 */
2292
2293 #if IS_ENABLED(CONFIG_INET)
2294 static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb,
2295                             struct net_device *dev, struct bpf_nh_params *nh)
2296 {
2297         u32 hh_len = LL_RESERVED_SPACE(dev);
2298         struct neighbour *neigh;
2299         bool is_v6gw = false;
2300
2301         if (dev_xmit_recursion()) {
2302                 net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2303                 goto out_drop;
2304         }
2305
2306         skb->dev = dev;
2307         skb_clear_tstamp(skb);
2308
2309         if (unlikely(skb_headroom(skb) < hh_len && dev->header_ops)) {
2310                 skb = skb_expand_head(skb, hh_len);
2311                 if (!skb)
2312                         return -ENOMEM;
2313         }
2314
2315         rcu_read_lock();
2316         if (!nh) {
2317                 struct dst_entry *dst = skb_dst(skb);
2318                 struct rtable *rt = container_of(dst, struct rtable, dst);
2319
2320                 neigh = ip_neigh_for_gw(rt, skb, &is_v6gw);
2321         } else if (nh->nh_family == AF_INET6) {
2322                 neigh = ip_neigh_gw6(dev, &nh->ipv6_nh);
2323                 is_v6gw = true;
2324         } else if (nh->nh_family == AF_INET) {
2325                 neigh = ip_neigh_gw4(dev, nh->ipv4_nh);
2326         } else {
2327                 rcu_read_unlock();
2328                 goto out_drop;
2329         }
2330
2331         if (likely(!IS_ERR(neigh))) {
2332                 int ret;
2333
2334                 sock_confirm_neigh(skb, neigh);
2335                 local_bh_disable();
2336                 dev_xmit_recursion_inc();
2337                 ret = neigh_output(neigh, skb, is_v6gw);
2338                 dev_xmit_recursion_dec();
2339                 local_bh_enable();
2340                 rcu_read_unlock();
2341                 return ret;
2342         }
2343         rcu_read_unlock();
2344 out_drop:
2345         kfree_skb(skb);
2346         return -ENETDOWN;
2347 }
2348
2349 static int __bpf_redirect_neigh_v4(struct sk_buff *skb, struct net_device *dev,
2350                                    struct bpf_nh_params *nh)
2351 {
2352         const struct iphdr *ip4h = ip_hdr(skb);
2353         struct net *net = dev_net(dev);
2354         int err, ret = NET_XMIT_DROP;
2355
2356         if (!nh) {
2357                 struct flowi4 fl4 = {
2358                         .flowi4_flags = FLOWI_FLAG_ANYSRC,
2359                         .flowi4_mark  = skb->mark,
2360                         .flowi4_tos   = RT_TOS(ip4h->tos),
2361                         .flowi4_oif   = dev->ifindex,
2362                         .flowi4_proto = ip4h->protocol,
2363                         .daddr        = ip4h->daddr,
2364                         .saddr        = ip4h->saddr,
2365                 };
2366                 struct rtable *rt;
2367
2368                 rt = ip_route_output_flow(net, &fl4, NULL);
2369                 if (IS_ERR(rt))
2370                         goto out_drop;
2371                 if (rt->rt_type != RTN_UNICAST && rt->rt_type != RTN_LOCAL) {
2372                         ip_rt_put(rt);
2373                         goto out_drop;
2374                 }
2375
2376                 skb_dst_set(skb, &rt->dst);
2377         }
2378
2379         err = bpf_out_neigh_v4(net, skb, dev, nh);
2380         if (unlikely(net_xmit_eval(err)))
2381                 dev->stats.tx_errors++;
2382         else
2383                 ret = NET_XMIT_SUCCESS;
2384         goto out_xmit;
2385 out_drop:
2386         dev->stats.tx_errors++;
2387         kfree_skb(skb);
2388 out_xmit:
2389         return ret;
2390 }
2391 #else
2392 static int __bpf_redirect_neigh_v4(struct sk_buff *skb, struct net_device *dev,
2393                                    struct bpf_nh_params *nh)
2394 {
2395         kfree_skb(skb);
2396         return NET_XMIT_DROP;
2397 }
2398 #endif /* CONFIG_INET */
2399
2400 static int __bpf_redirect_neigh(struct sk_buff *skb, struct net_device *dev,
2401                                 struct bpf_nh_params *nh)
2402 {
2403         struct ethhdr *ethh = eth_hdr(skb);
2404
2405         if (unlikely(skb->mac_header >= skb->network_header))
2406                 goto out;
2407         bpf_push_mac_rcsum(skb);
2408         if (is_multicast_ether_addr(ethh->h_dest))
2409                 goto out;
2410
2411         skb_pull(skb, sizeof(*ethh));
2412         skb_unset_mac_header(skb);
2413         skb_reset_network_header(skb);
2414
2415         if (skb->protocol == htons(ETH_P_IP))
2416                 return __bpf_redirect_neigh_v4(skb, dev, nh);
2417         else if (skb->protocol == htons(ETH_P_IPV6))
2418                 return __bpf_redirect_neigh_v6(skb, dev, nh);
2419 out:
2420         kfree_skb(skb);
2421         return -ENOTSUPP;
2422 }
2423
2424 /* Internal, non-exposed redirect flags. */
2425 enum {
2426         BPF_F_NEIGH     = (1ULL << 1),
2427         BPF_F_PEER      = (1ULL << 2),
2428         BPF_F_NEXTHOP   = (1ULL << 3),
2429 #define BPF_F_REDIRECT_INTERNAL (BPF_F_NEIGH | BPF_F_PEER | BPF_F_NEXTHOP)
2430 };
2431
2432 BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
2433 {
2434         struct net_device *dev;
2435         struct sk_buff *clone;
2436         int ret;
2437
2438         if (unlikely(flags & (~(BPF_F_INGRESS) | BPF_F_REDIRECT_INTERNAL)))
2439                 return -EINVAL;
2440
2441         dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
2442         if (unlikely(!dev))
2443                 return -EINVAL;
2444
2445         clone = skb_clone(skb, GFP_ATOMIC);
2446         if (unlikely(!clone))
2447                 return -ENOMEM;
2448
2449         /* For direct write, we need to keep the invariant that the skbs
2450          * we're dealing with need to be uncloned. Should uncloning fail
2451          * here, we need to free the just generated clone to unclone once
2452          * again.
2453          */
2454         ret = bpf_try_make_head_writable(skb);
2455         if (unlikely(ret)) {
2456                 kfree_skb(clone);
2457                 return -ENOMEM;
2458         }
2459
2460         return __bpf_redirect(clone, dev, flags);
2461 }
2462
2463 static const struct bpf_func_proto bpf_clone_redirect_proto = {
2464         .func           = bpf_clone_redirect,
2465         .gpl_only       = false,
2466         .ret_type       = RET_INTEGER,
2467         .arg1_type      = ARG_PTR_TO_CTX,
2468         .arg2_type      = ARG_ANYTHING,
2469         .arg3_type      = ARG_ANYTHING,
2470 };
2471
2472 DEFINE_PER_CPU(struct bpf_redirect_info, bpf_redirect_info);
2473 EXPORT_PER_CPU_SYMBOL_GPL(bpf_redirect_info);
2474
2475 static struct net_device *skb_get_peer_dev(struct net_device *dev)
2476 {
2477         const struct net_device_ops *ops = dev->netdev_ops;
2478
2479         if (likely(ops->ndo_get_peer_dev))
2480                 return INDIRECT_CALL_1(ops->ndo_get_peer_dev,
2481                                        netkit_peer_dev, dev);
2482         return NULL;
2483 }
2484
2485 int skb_do_redirect(struct sk_buff *skb)
2486 {
2487         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2488         struct net *net = dev_net(skb->dev);
2489         struct net_device *dev;
2490         u32 flags = ri->flags;
2491
2492         dev = dev_get_by_index_rcu(net, ri->tgt_index);
2493         ri->tgt_index = 0;
2494         ri->flags = 0;
2495         if (unlikely(!dev))
2496                 goto out_drop;
2497         if (flags & BPF_F_PEER) {
2498                 if (unlikely(!skb_at_tc_ingress(skb)))
2499                         goto out_drop;
2500                 dev = skb_get_peer_dev(dev);
2501                 if (unlikely(!dev ||
2502                              !(dev->flags & IFF_UP) ||
2503                              net_eq(net, dev_net(dev))))
2504                         goto out_drop;
2505                 skb->dev = dev;
2506                 dev_sw_netstats_rx_add(dev, skb->len);
2507                 return -EAGAIN;
2508         }
2509         return flags & BPF_F_NEIGH ?
2510                __bpf_redirect_neigh(skb, dev, flags & BPF_F_NEXTHOP ?
2511                                     &ri->nh : NULL) :
2512                __bpf_redirect(skb, dev, flags);
2513 out_drop:
2514         kfree_skb(skb);
2515         return -EINVAL;
2516 }
2517
2518 BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
2519 {
2520         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2521
2522         if (unlikely(flags & (~(BPF_F_INGRESS) | BPF_F_REDIRECT_INTERNAL)))
2523                 return TC_ACT_SHOT;
2524
2525         ri->flags = flags;
2526         ri->tgt_index = ifindex;
2527
2528         return TC_ACT_REDIRECT;
2529 }
2530
2531 static const struct bpf_func_proto bpf_redirect_proto = {
2532         .func           = bpf_redirect,
2533         .gpl_only       = false,
2534         .ret_type       = RET_INTEGER,
2535         .arg1_type      = ARG_ANYTHING,
2536         .arg2_type      = ARG_ANYTHING,
2537 };
2538
2539 BPF_CALL_2(bpf_redirect_peer, u32, ifindex, u64, flags)
2540 {
2541         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2542
2543         if (unlikely(flags))
2544                 return TC_ACT_SHOT;
2545
2546         ri->flags = BPF_F_PEER;
2547         ri->tgt_index = ifindex;
2548
2549         return TC_ACT_REDIRECT;
2550 }
2551
2552 static const struct bpf_func_proto bpf_redirect_peer_proto = {
2553         .func           = bpf_redirect_peer,
2554         .gpl_only       = false,
2555         .ret_type       = RET_INTEGER,
2556         .arg1_type      = ARG_ANYTHING,
2557         .arg2_type      = ARG_ANYTHING,
2558 };
2559
2560 BPF_CALL_4(bpf_redirect_neigh, u32, ifindex, struct bpf_redir_neigh *, params,
2561            int, plen, u64, flags)
2562 {
2563         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2564
2565         if (unlikely((plen && plen < sizeof(*params)) || flags))
2566                 return TC_ACT_SHOT;
2567
2568         ri->flags = BPF_F_NEIGH | (plen ? BPF_F_NEXTHOP : 0);
2569         ri->tgt_index = ifindex;
2570
2571         BUILD_BUG_ON(sizeof(struct bpf_redir_neigh) != sizeof(struct bpf_nh_params));
2572         if (plen)
2573                 memcpy(&ri->nh, params, sizeof(ri->nh));
2574
2575         return TC_ACT_REDIRECT;
2576 }
2577
2578 static const struct bpf_func_proto bpf_redirect_neigh_proto = {
2579         .func           = bpf_redirect_neigh,
2580         .gpl_only       = false,
2581         .ret_type       = RET_INTEGER,
2582         .arg1_type      = ARG_ANYTHING,
2583         .arg2_type      = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
2584         .arg3_type      = ARG_CONST_SIZE_OR_ZERO,
2585         .arg4_type      = ARG_ANYTHING,
2586 };
2587
2588 BPF_CALL_2(bpf_msg_apply_bytes, struct sk_msg *, msg, u32, bytes)
2589 {
2590         msg->apply_bytes = bytes;
2591         return 0;
2592 }
2593
2594 static const struct bpf_func_proto bpf_msg_apply_bytes_proto = {
2595         .func           = bpf_msg_apply_bytes,
2596         .gpl_only       = false,
2597         .ret_type       = RET_INTEGER,
2598         .arg1_type      = ARG_PTR_TO_CTX,
2599         .arg2_type      = ARG_ANYTHING,
2600 };
2601
2602 BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg *, msg, u32, bytes)
2603 {
2604         msg->cork_bytes = bytes;
2605         return 0;
2606 }
2607
2608 static void sk_msg_reset_curr(struct sk_msg *msg)
2609 {
2610         u32 i = msg->sg.start;
2611         u32 len = 0;
2612
2613         do {
2614                 len += sk_msg_elem(msg, i)->length;
2615                 sk_msg_iter_var_next(i);
2616                 if (len >= msg->sg.size)
2617                         break;
2618         } while (i != msg->sg.end);
2619
2620         msg->sg.curr = i;
2621         msg->sg.copybreak = 0;
2622 }
2623
2624 static const struct bpf_func_proto bpf_msg_cork_bytes_proto = {
2625         .func           = bpf_msg_cork_bytes,
2626         .gpl_only       = false,
2627         .ret_type       = RET_INTEGER,
2628         .arg1_type      = ARG_PTR_TO_CTX,
2629         .arg2_type      = ARG_ANYTHING,
2630 };
2631
2632 BPF_CALL_4(bpf_msg_pull_data, struct sk_msg *, msg, u32, start,
2633            u32, end, u64, flags)
2634 {
2635         u32 len = 0, offset = 0, copy = 0, poffset = 0, bytes = end - start;
2636         u32 first_sge, last_sge, i, shift, bytes_sg_total;
2637         struct scatterlist *sge;
2638         u8 *raw, *to, *from;
2639         struct page *page;
2640
2641         if (unlikely(flags || end <= start))
2642                 return -EINVAL;
2643
2644         /* First find the starting scatterlist element */
2645         i = msg->sg.start;
2646         do {
2647                 offset += len;
2648                 len = sk_msg_elem(msg, i)->length;
2649                 if (start < offset + len)
2650                         break;
2651                 sk_msg_iter_var_next(i);
2652         } while (i != msg->sg.end);
2653
2654         if (unlikely(start >= offset + len))
2655                 return -EINVAL;
2656
2657         first_sge = i;
2658         /* The start may point into the sg element so we need to also
2659          * account for the headroom.
2660          */
2661         bytes_sg_total = start - offset + bytes;
2662         if (!test_bit(i, msg->sg.copy) && bytes_sg_total <= len)
2663                 goto out;
2664
2665         /* At this point we need to linearize multiple scatterlist
2666          * elements or a single shared page. Either way we need to
2667          * copy into a linear buffer exclusively owned by BPF. Then
2668          * place the buffer in the scatterlist and fixup the original
2669          * entries by removing the entries now in the linear buffer
2670          * and shifting the remaining entries. For now we do not try
2671          * to copy partial entries to avoid complexity of running out
2672          * of sg_entry slots. The downside is reading a single byte
2673          * will copy the entire sg entry.
2674          */
2675         do {
2676                 copy += sk_msg_elem(msg, i)->length;
2677                 sk_msg_iter_var_next(i);
2678                 if (bytes_sg_total <= copy)
2679                         break;
2680         } while (i != msg->sg.end);
2681         last_sge = i;
2682
2683         if (unlikely(bytes_sg_total > copy))
2684                 return -EINVAL;
2685
2686         page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2687                            get_order(copy));
2688         if (unlikely(!page))
2689                 return -ENOMEM;
2690
2691         raw = page_address(page);
2692         i = first_sge;
2693         do {
2694                 sge = sk_msg_elem(msg, i);
2695                 from = sg_virt(sge);
2696                 len = sge->length;
2697                 to = raw + poffset;
2698
2699                 memcpy(to, from, len);
2700                 poffset += len;
2701                 sge->length = 0;
2702                 put_page(sg_page(sge));
2703
2704                 sk_msg_iter_var_next(i);
2705         } while (i != last_sge);
2706
2707         sg_set_page(&msg->sg.data[first_sge], page, copy, 0);
2708
2709         /* To repair sg ring we need to shift entries. If we only
2710          * had a single entry though we can just replace it and
2711          * be done. Otherwise walk the ring and shift the entries.
2712          */
2713         WARN_ON_ONCE(last_sge == first_sge);
2714         shift = last_sge > first_sge ?
2715                 last_sge - first_sge - 1 :
2716                 NR_MSG_FRAG_IDS - first_sge + last_sge - 1;
2717         if (!shift)
2718                 goto out;
2719
2720         i = first_sge;
2721         sk_msg_iter_var_next(i);
2722         do {
2723                 u32 move_from;
2724
2725                 if (i + shift >= NR_MSG_FRAG_IDS)
2726                         move_from = i + shift - NR_MSG_FRAG_IDS;
2727                 else
2728                         move_from = i + shift;
2729                 if (move_from == msg->sg.end)
2730                         break;
2731
2732                 msg->sg.data[i] = msg->sg.data[move_from];
2733                 msg->sg.data[move_from].length = 0;
2734                 msg->sg.data[move_from].page_link = 0;
2735                 msg->sg.data[move_from].offset = 0;
2736                 sk_msg_iter_var_next(i);
2737         } while (1);
2738
2739         msg->sg.end = msg->sg.end - shift > msg->sg.end ?
2740                       msg->sg.end - shift + NR_MSG_FRAG_IDS :
2741                       msg->sg.end - shift;
2742 out:
2743         sk_msg_reset_curr(msg);
2744         msg->data = sg_virt(&msg->sg.data[first_sge]) + start - offset;
2745         msg->data_end = msg->data + bytes;
2746         return 0;
2747 }
2748
2749 static const struct bpf_func_proto bpf_msg_pull_data_proto = {
2750         .func           = bpf_msg_pull_data,
2751         .gpl_only       = false,
2752         .ret_type       = RET_INTEGER,
2753         .arg1_type      = ARG_PTR_TO_CTX,
2754         .arg2_type      = ARG_ANYTHING,
2755         .arg3_type      = ARG_ANYTHING,
2756         .arg4_type      = ARG_ANYTHING,
2757 };
2758
2759 BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start,
2760            u32, len, u64, flags)
2761 {
2762         struct scatterlist sge, nsge, nnsge, rsge = {0}, *psge;
2763         u32 new, i = 0, l = 0, space, copy = 0, offset = 0;
2764         u8 *raw, *to, *from;
2765         struct page *page;
2766
2767         if (unlikely(flags))
2768                 return -EINVAL;
2769
2770         if (unlikely(len == 0))
2771                 return 0;
2772
2773         /* First find the starting scatterlist element */
2774         i = msg->sg.start;
2775         do {
2776                 offset += l;
2777                 l = sk_msg_elem(msg, i)->length;
2778
2779                 if (start < offset + l)
2780                         break;
2781                 sk_msg_iter_var_next(i);
2782         } while (i != msg->sg.end);
2783
2784         if (start >= offset + l)
2785                 return -EINVAL;
2786
2787         space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2788
2789         /* If no space available will fallback to copy, we need at
2790          * least one scatterlist elem available to push data into
2791          * when start aligns to the beginning of an element or two
2792          * when it falls inside an element. We handle the start equals
2793          * offset case because its the common case for inserting a
2794          * header.
2795          */
2796         if (!space || (space == 1 && start != offset))
2797                 copy = msg->sg.data[i].length;
2798
2799         page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2800                            get_order(copy + len));
2801         if (unlikely(!page))
2802                 return -ENOMEM;
2803
2804         if (copy) {
2805                 int front, back;
2806
2807                 raw = page_address(page);
2808
2809                 psge = sk_msg_elem(msg, i);
2810                 front = start - offset;
2811                 back = psge->length - front;
2812                 from = sg_virt(psge);
2813
2814                 if (front)
2815                         memcpy(raw, from, front);
2816
2817                 if (back) {
2818                         from += front;
2819                         to = raw + front + len;
2820
2821                         memcpy(to, from, back);
2822                 }
2823
2824                 put_page(sg_page(psge));
2825         } else if (start - offset) {
2826                 psge = sk_msg_elem(msg, i);
2827                 rsge = sk_msg_elem_cpy(msg, i);
2828
2829                 psge->length = start - offset;
2830                 rsge.length -= psge->length;
2831                 rsge.offset += start;
2832
2833                 sk_msg_iter_var_next(i);
2834                 sg_unmark_end(psge);
2835                 sg_unmark_end(&rsge);
2836                 sk_msg_iter_next(msg, end);
2837         }
2838
2839         /* Slot(s) to place newly allocated data */
2840         new = i;
2841
2842         /* Shift one or two slots as needed */
2843         if (!copy) {
2844                 sge = sk_msg_elem_cpy(msg, i);
2845
2846                 sk_msg_iter_var_next(i);
2847                 sg_unmark_end(&sge);
2848                 sk_msg_iter_next(msg, end);
2849
2850                 nsge = sk_msg_elem_cpy(msg, i);
2851                 if (rsge.length) {
2852                         sk_msg_iter_var_next(i);
2853                         nnsge = sk_msg_elem_cpy(msg, i);
2854                 }
2855
2856                 while (i != msg->sg.end) {
2857                         msg->sg.data[i] = sge;
2858                         sge = nsge;
2859                         sk_msg_iter_var_next(i);
2860                         if (rsge.length) {
2861                                 nsge = nnsge;
2862                                 nnsge = sk_msg_elem_cpy(msg, i);
2863                         } else {
2864                                 nsge = sk_msg_elem_cpy(msg, i);
2865                         }
2866                 }
2867         }
2868
2869         /* Place newly allocated data buffer */
2870         sk_mem_charge(msg->sk, len);
2871         msg->sg.size += len;
2872         __clear_bit(new, msg->sg.copy);
2873         sg_set_page(&msg->sg.data[new], page, len + copy, 0);
2874         if (rsge.length) {
2875                 get_page(sg_page(&rsge));
2876                 sk_msg_iter_var_next(new);
2877                 msg->sg.data[new] = rsge;
2878         }
2879
2880         sk_msg_reset_curr(msg);
2881         sk_msg_compute_data_pointers(msg);
2882         return 0;
2883 }
2884
2885 static const struct bpf_func_proto bpf_msg_push_data_proto = {
2886         .func           = bpf_msg_push_data,
2887         .gpl_only       = false,
2888         .ret_type       = RET_INTEGER,
2889         .arg1_type      = ARG_PTR_TO_CTX,
2890         .arg2_type      = ARG_ANYTHING,
2891         .arg3_type      = ARG_ANYTHING,
2892         .arg4_type      = ARG_ANYTHING,
2893 };
2894
2895 static void sk_msg_shift_left(struct sk_msg *msg, int i)
2896 {
2897         int prev;
2898
2899         do {
2900                 prev = i;
2901                 sk_msg_iter_var_next(i);
2902                 msg->sg.data[prev] = msg->sg.data[i];
2903         } while (i != msg->sg.end);
2904
2905         sk_msg_iter_prev(msg, end);
2906 }
2907
2908 static void sk_msg_shift_right(struct sk_msg *msg, int i)
2909 {
2910         struct scatterlist tmp, sge;
2911
2912         sk_msg_iter_next(msg, end);
2913         sge = sk_msg_elem_cpy(msg, i);
2914         sk_msg_iter_var_next(i);
2915         tmp = sk_msg_elem_cpy(msg, i);
2916
2917         while (i != msg->sg.end) {
2918                 msg->sg.data[i] = sge;
2919                 sk_msg_iter_var_next(i);
2920                 sge = tmp;
2921                 tmp = sk_msg_elem_cpy(msg, i);
2922         }
2923 }
2924
2925 BPF_CALL_4(bpf_msg_pop_data, struct sk_msg *, msg, u32, start,
2926            u32, len, u64, flags)
2927 {
2928         u32 i = 0, l = 0, space, offset = 0;
2929         u64 last = start + len;
2930         int pop;
2931
2932         if (unlikely(flags))
2933                 return -EINVAL;
2934
2935         /* First find the starting scatterlist element */
2936         i = msg->sg.start;
2937         do {
2938                 offset += l;
2939                 l = sk_msg_elem(msg, i)->length;
2940
2941                 if (start < offset + l)
2942                         break;
2943                 sk_msg_iter_var_next(i);
2944         } while (i != msg->sg.end);
2945
2946         /* Bounds checks: start and pop must be inside message */
2947         if (start >= offset + l || last >= msg->sg.size)
2948                 return -EINVAL;
2949
2950         space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2951
2952         pop = len;
2953         /* --------------| offset
2954          * -| start      |-------- len -------|
2955          *
2956          *  |----- a ----|-------- pop -------|----- b ----|
2957          *  |______________________________________________| length
2958          *
2959          *
2960          * a:   region at front of scatter element to save
2961          * b:   region at back of scatter element to save when length > A + pop
2962          * pop: region to pop from element, same as input 'pop' here will be
2963          *      decremented below per iteration.
2964          *
2965          * Two top-level cases to handle when start != offset, first B is non
2966          * zero and second B is zero corresponding to when a pop includes more
2967          * than one element.
2968          *
2969          * Then if B is non-zero AND there is no space allocate space and
2970          * compact A, B regions into page. If there is space shift ring to
2971          * the rigth free'ing the next element in ring to place B, leaving
2972          * A untouched except to reduce length.
2973          */
2974         if (start != offset) {
2975                 struct scatterlist *nsge, *sge = sk_msg_elem(msg, i);
2976                 int a = start;
2977                 int b = sge->length - pop - a;
2978
2979                 sk_msg_iter_var_next(i);
2980
2981                 if (pop < sge->length - a) {
2982                         if (space) {
2983                                 sge->length = a;
2984                                 sk_msg_shift_right(msg, i);
2985                                 nsge = sk_msg_elem(msg, i);
2986                                 get_page(sg_page(sge));
2987                                 sg_set_page(nsge,
2988                                             sg_page(sge),
2989                                             b, sge->offset + pop + a);
2990                         } else {
2991                                 struct page *page, *orig;
2992                                 u8 *to, *from;
2993
2994                                 page = alloc_pages(__GFP_NOWARN |
2995                                                    __GFP_COMP   | GFP_ATOMIC,
2996                                                    get_order(a + b));
2997                                 if (unlikely(!page))
2998                                         return -ENOMEM;
2999
3000                                 sge->length = a;
3001                                 orig = sg_page(sge);
3002                                 from = sg_virt(sge);
3003                                 to = page_address(page);
3004                                 memcpy(to, from, a);
3005                                 memcpy(to + a, from + a + pop, b);
3006                                 sg_set_page(sge, page, a + b, 0);
3007                                 put_page(orig);
3008                         }
3009                         pop = 0;
3010                 } else if (pop >= sge->length - a) {
3011                         pop -= (sge->length - a);
3012                         sge->length = a;
3013                 }
3014         }
3015
3016         /* From above the current layout _must_ be as follows,
3017          *
3018          * -| offset
3019          * -| start
3020          *
3021          *  |---- pop ---|---------------- b ------------|
3022          *  |____________________________________________| length
3023          *
3024          * Offset and start of the current msg elem are equal because in the
3025          * previous case we handled offset != start and either consumed the
3026          * entire element and advanced to the next element OR pop == 0.
3027          *
3028          * Two cases to handle here are first pop is less than the length
3029          * leaving some remainder b above. Simply adjust the element's layout
3030          * in this case. Or pop >= length of the element so that b = 0. In this
3031          * case advance to next element decrementing pop.
3032          */
3033         while (pop) {
3034                 struct scatterlist *sge = sk_msg_elem(msg, i);
3035
3036                 if (pop < sge->length) {
3037                         sge->length -= pop;
3038                         sge->offset += pop;
3039                         pop = 0;
3040                 } else {
3041                         pop -= sge->length;
3042                         sk_msg_shift_left(msg, i);
3043                 }
3044                 sk_msg_iter_var_next(i);
3045         }
3046
3047         sk_mem_uncharge(msg->sk, len - pop);
3048         msg->sg.size -= (len - pop);
3049         sk_msg_reset_curr(msg);
3050         sk_msg_compute_data_pointers(msg);
3051         return 0;
3052 }
3053
3054 static const struct bpf_func_proto bpf_msg_pop_data_proto = {
3055         .func           = bpf_msg_pop_data,
3056         .gpl_only       = false,
3057         .ret_type       = RET_INTEGER,
3058         .arg1_type      = ARG_PTR_TO_CTX,
3059         .arg2_type      = ARG_ANYTHING,
3060         .arg3_type      = ARG_ANYTHING,
3061         .arg4_type      = ARG_ANYTHING,
3062 };
3063
3064 #ifdef CONFIG_CGROUP_NET_CLASSID
3065 BPF_CALL_0(bpf_get_cgroup_classid_curr)
3066 {
3067         return __task_get_classid(current);
3068 }
3069
3070 const struct bpf_func_proto bpf_get_cgroup_classid_curr_proto = {
3071         .func           = bpf_get_cgroup_classid_curr,
3072         .gpl_only       = false,
3073         .ret_type       = RET_INTEGER,
3074 };
3075
3076 BPF_CALL_1(bpf_skb_cgroup_classid, const struct sk_buff *, skb)
3077 {
3078         struct sock *sk = skb_to_full_sk(skb);
3079
3080         if (!sk || !sk_fullsock(sk))
3081                 return 0;
3082
3083         return sock_cgroup_classid(&sk->sk_cgrp_data);
3084 }
3085
3086 static const struct bpf_func_proto bpf_skb_cgroup_classid_proto = {
3087         .func           = bpf_skb_cgroup_classid,
3088         .gpl_only       = false,
3089         .ret_type       = RET_INTEGER,
3090         .arg1_type      = ARG_PTR_TO_CTX,
3091 };
3092 #endif
3093
3094 BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
3095 {
3096         return task_get_classid(skb);
3097 }
3098
3099 static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
3100         .func           = bpf_get_cgroup_classid,
3101         .gpl_only       = false,
3102         .ret_type       = RET_INTEGER,
3103         .arg1_type      = ARG_PTR_TO_CTX,
3104 };
3105
3106 BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
3107 {
3108         return dst_tclassid(skb);
3109 }
3110
3111 static const struct bpf_func_proto bpf_get_route_realm_proto = {
3112         .func           = bpf_get_route_realm,
3113         .gpl_only       = false,
3114         .ret_type       = RET_INTEGER,
3115         .arg1_type      = ARG_PTR_TO_CTX,
3116 };
3117
3118 BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
3119 {
3120         /* If skb_clear_hash() was called due to mangling, we can
3121          * trigger SW recalculation here. Later access to hash
3122          * can then use the inline skb->hash via context directly
3123          * instead of calling this helper again.
3124          */
3125         return skb_get_hash(skb);
3126 }
3127
3128 static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
3129         .func           = bpf_get_hash_recalc,
3130         .gpl_only       = false,
3131         .ret_type       = RET_INTEGER,
3132         .arg1_type      = ARG_PTR_TO_CTX,
3133 };
3134
3135 BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
3136 {
3137         /* After all direct packet write, this can be used once for
3138          * triggering a lazy recalc on next skb_get_hash() invocation.
3139          */
3140         skb_clear_hash(skb);
3141         return 0;
3142 }
3143
3144 static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
3145         .func           = bpf_set_hash_invalid,
3146         .gpl_only       = false,
3147         .ret_type       = RET_INTEGER,
3148         .arg1_type      = ARG_PTR_TO_CTX,
3149 };
3150
3151 BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
3152 {
3153         /* Set user specified hash as L4(+), so that it gets returned
3154          * on skb_get_hash() call unless BPF prog later on triggers a
3155          * skb_clear_hash().
3156          */
3157         __skb_set_sw_hash(skb, hash, true);
3158         return 0;
3159 }
3160
3161 static const struct bpf_func_proto bpf_set_hash_proto = {
3162         .func           = bpf_set_hash,
3163         .gpl_only       = false,
3164         .ret_type       = RET_INTEGER,
3165         .arg1_type      = ARG_PTR_TO_CTX,
3166         .arg2_type      = ARG_ANYTHING,
3167 };
3168
3169 BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
3170            u16, vlan_tci)
3171 {
3172         int ret;
3173
3174         if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
3175                      vlan_proto != htons(ETH_P_8021AD)))
3176                 vlan_proto = htons(ETH_P_8021Q);
3177
3178         bpf_push_mac_rcsum(skb);
3179         ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
3180         bpf_pull_mac_rcsum(skb);
3181
3182         bpf_compute_data_pointers(skb);
3183         return ret;
3184 }
3185
3186 static const struct bpf_func_proto bpf_skb_vlan_push_proto = {
3187         .func           = bpf_skb_vlan_push,
3188         .gpl_only       = false,
3189         .ret_type       = RET_INTEGER,
3190         .arg1_type      = ARG_PTR_TO_CTX,
3191         .arg2_type      = ARG_ANYTHING,
3192         .arg3_type      = ARG_ANYTHING,
3193 };
3194
3195 BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
3196 {
3197         int ret;
3198
3199         bpf_push_mac_rcsum(skb);
3200         ret = skb_vlan_pop(skb);
3201         bpf_pull_mac_rcsum(skb);
3202
3203         bpf_compute_data_pointers(skb);
3204         return ret;
3205 }
3206
3207 static const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
3208         .func           = bpf_skb_vlan_pop,
3209         .gpl_only       = false,
3210         .ret_type       = RET_INTEGER,
3211         .arg1_type      = ARG_PTR_TO_CTX,
3212 };
3213
3214 static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
3215 {
3216         /* Caller already did skb_cow() with len as headroom,
3217          * so no need to do it here.
3218          */
3219         skb_push(skb, len);
3220         memmove(skb->data, skb->data + len, off);
3221         memset(skb->data + off, 0, len);
3222
3223         /* No skb_postpush_rcsum(skb, skb->data + off, len)
3224          * needed here as it does not change the skb->csum
3225          * result for checksum complete when summing over
3226          * zeroed blocks.
3227          */
3228         return 0;
3229 }
3230
3231 static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
3232 {
3233         void *old_data;
3234
3235         /* skb_ensure_writable() is not needed here, as we're
3236          * already working on an uncloned skb.
3237          */
3238         if (unlikely(!pskb_may_pull(skb, off + len)))
3239                 return -ENOMEM;
3240
3241         old_data = skb->data;
3242         __skb_pull(skb, len);
3243         skb_postpull_rcsum(skb, old_data + off, len);
3244         memmove(skb->data, old_data, off);
3245
3246         return 0;
3247 }
3248
3249 static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
3250 {
3251         bool trans_same = skb->transport_header == skb->network_header;
3252         int ret;
3253
3254         /* There's no need for __skb_push()/__skb_pull() pair to
3255          * get to the start of the mac header as we're guaranteed
3256          * to always start from here under eBPF.
3257          */
3258         ret = bpf_skb_generic_push(skb, off, len);
3259         if (likely(!ret)) {
3260                 skb->mac_header -= len;
3261                 skb->network_header -= len;
3262                 if (trans_same)
3263                         skb->transport_header = skb->network_header;
3264         }
3265
3266         return ret;
3267 }
3268
3269 static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
3270 {
3271         bool trans_same = skb->transport_header == skb->network_header;
3272         int ret;
3273
3274         /* Same here, __skb_push()/__skb_pull() pair not needed. */
3275         ret = bpf_skb_generic_pop(skb, off, len);
3276         if (likely(!ret)) {
3277                 skb->mac_header += len;
3278                 skb->network_header += len;
3279                 if (trans_same)
3280                         skb->transport_header = skb->network_header;
3281         }
3282
3283         return ret;
3284 }
3285
3286 static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
3287 {
3288         const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
3289         u32 off = skb_mac_header_len(skb);
3290         int ret;
3291
3292         ret = skb_cow(skb, len_diff);
3293         if (unlikely(ret < 0))
3294                 return ret;
3295
3296         ret = bpf_skb_net_hdr_push(skb, off, len_diff);
3297         if (unlikely(ret < 0))
3298                 return ret;
3299
3300         if (skb_is_gso(skb)) {
3301                 struct skb_shared_info *shinfo = skb_shinfo(skb);
3302
3303                 /* SKB_GSO_TCPV4 needs to be changed into SKB_GSO_TCPV6. */
3304                 if (shinfo->gso_type & SKB_GSO_TCPV4) {
3305                         shinfo->gso_type &= ~SKB_GSO_TCPV4;
3306                         shinfo->gso_type |=  SKB_GSO_TCPV6;
3307                 }
3308         }
3309
3310         skb->protocol = htons(ETH_P_IPV6);
3311         skb_clear_hash(skb);
3312
3313         return 0;
3314 }
3315
3316 static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
3317 {
3318         const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
3319         u32 off = skb_mac_header_len(skb);
3320         int ret;
3321
3322         ret = skb_unclone(skb, GFP_ATOMIC);
3323         if (unlikely(ret < 0))
3324                 return ret;
3325
3326         ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
3327         if (unlikely(ret < 0))
3328                 return ret;
3329
3330         if (skb_is_gso(skb)) {
3331                 struct skb_shared_info *shinfo = skb_shinfo(skb);
3332
3333                 /* SKB_GSO_TCPV6 needs to be changed into SKB_GSO_TCPV4. */
3334                 if (shinfo->gso_type & SKB_GSO_TCPV6) {
3335                         shinfo->gso_type &= ~SKB_GSO_TCPV6;
3336                         shinfo->gso_type |=  SKB_GSO_TCPV4;
3337                 }
3338         }
3339
3340         skb->protocol = htons(ETH_P_IP);
3341         skb_clear_hash(skb);
3342
3343         return 0;
3344 }
3345
3346 static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
3347 {
3348         __be16 from_proto = skb->protocol;
3349
3350         if (from_proto == htons(ETH_P_IP) &&
3351               to_proto == htons(ETH_P_IPV6))
3352                 return bpf_skb_proto_4_to_6(skb);
3353
3354         if (from_proto == htons(ETH_P_IPV6) &&
3355               to_proto == htons(ETH_P_IP))
3356                 return bpf_skb_proto_6_to_4(skb);
3357
3358         return -ENOTSUPP;
3359 }
3360
3361 BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
3362            u64, flags)
3363 {
3364         int ret;
3365
3366         if (unlikely(flags))
3367                 return -EINVAL;
3368
3369         /* General idea is that this helper does the basic groundwork
3370          * needed for changing the protocol, and eBPF program fills the
3371          * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
3372          * and other helpers, rather than passing a raw buffer here.
3373          *
3374          * The rationale is to keep this minimal and without a need to
3375          * deal with raw packet data. F.e. even if we would pass buffers
3376          * here, the program still needs to call the bpf_lX_csum_replace()
3377          * helpers anyway. Plus, this way we keep also separation of
3378          * concerns, since f.e. bpf_skb_store_bytes() should only take
3379          * care of stores.
3380          *
3381          * Currently, additional options and extension header space are
3382          * not supported, but flags register is reserved so we can adapt
3383          * that. For offloads, we mark packet as dodgy, so that headers
3384          * need to be verified first.
3385          */
3386         ret = bpf_skb_proto_xlat(skb, proto);
3387         bpf_compute_data_pointers(skb);
3388         return ret;
3389 }
3390
3391 static const struct bpf_func_proto bpf_skb_change_proto_proto = {
3392         .func           = bpf_skb_change_proto,
3393         .gpl_only       = false,
3394         .ret_type       = RET_INTEGER,
3395         .arg1_type      = ARG_PTR_TO_CTX,
3396         .arg2_type      = ARG_ANYTHING,
3397         .arg3_type      = ARG_ANYTHING,
3398 };
3399
3400 BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
3401 {
3402         /* We only allow a restricted subset to be changed for now. */
3403         if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
3404                      !skb_pkt_type_ok(pkt_type)))
3405                 return -EINVAL;
3406
3407         skb->pkt_type = pkt_type;
3408         return 0;
3409 }
3410
3411 static const struct bpf_func_proto bpf_skb_change_type_proto = {
3412         .func           = bpf_skb_change_type,
3413         .gpl_only       = false,
3414         .ret_type       = RET_INTEGER,
3415         .arg1_type      = ARG_PTR_TO_CTX,
3416         .arg2_type      = ARG_ANYTHING,
3417 };
3418
3419 static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
3420 {
3421         switch (skb->protocol) {
3422         case htons(ETH_P_IP):
3423                 return sizeof(struct iphdr);
3424         case htons(ETH_P_IPV6):
3425                 return sizeof(struct ipv6hdr);
3426         default:
3427                 return ~0U;
3428         }
3429 }
3430
3431 #define BPF_F_ADJ_ROOM_ENCAP_L3_MASK    (BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 | \
3432                                          BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3433
3434 #define BPF_F_ADJ_ROOM_DECAP_L3_MASK    (BPF_F_ADJ_ROOM_DECAP_L3_IPV4 | \
3435                                          BPF_F_ADJ_ROOM_DECAP_L3_IPV6)
3436
3437 #define BPF_F_ADJ_ROOM_MASK             (BPF_F_ADJ_ROOM_FIXED_GSO | \
3438                                          BPF_F_ADJ_ROOM_ENCAP_L3_MASK | \
3439                                          BPF_F_ADJ_ROOM_ENCAP_L4_GRE | \
3440                                          BPF_F_ADJ_ROOM_ENCAP_L4_UDP | \
3441                                          BPF_F_ADJ_ROOM_ENCAP_L2_ETH | \
3442                                          BPF_F_ADJ_ROOM_ENCAP_L2( \
3443                                           BPF_ADJ_ROOM_ENCAP_L2_MASK) | \
3444                                          BPF_F_ADJ_ROOM_DECAP_L3_MASK)
3445
3446 static int bpf_skb_net_grow(struct sk_buff *skb, u32 off, u32 len_diff,
3447                             u64 flags)
3448 {
3449         u8 inner_mac_len = flags >> BPF_ADJ_ROOM_ENCAP_L2_SHIFT;
3450         bool encap = flags & BPF_F_ADJ_ROOM_ENCAP_L3_MASK;
3451         u16 mac_len = 0, inner_net = 0, inner_trans = 0;
3452         unsigned int gso_type = SKB_GSO_DODGY;
3453         int ret;
3454
3455         if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3456                 /* udp gso_size delineates datagrams, only allow if fixed */
3457                 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3458                     !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3459                         return -ENOTSUPP;
3460         }
3461
3462         ret = skb_cow_head(skb, len_diff);
3463         if (unlikely(ret < 0))
3464                 return ret;
3465
3466         if (encap) {
3467                 if (skb->protocol != htons(ETH_P_IP) &&
3468                     skb->protocol != htons(ETH_P_IPV6))
3469                         return -ENOTSUPP;
3470
3471                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 &&
3472                     flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3473                         return -EINVAL;
3474
3475                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE &&
3476                     flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3477                         return -EINVAL;
3478
3479                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L2_ETH &&
3480                     inner_mac_len < ETH_HLEN)
3481                         return -EINVAL;
3482
3483                 if (skb->encapsulation)
3484                         return -EALREADY;
3485
3486                 mac_len = skb->network_header - skb->mac_header;
3487                 inner_net = skb->network_header;
3488                 if (inner_mac_len > len_diff)
3489                         return -EINVAL;
3490                 inner_trans = skb->transport_header;
3491         }
3492
3493         ret = bpf_skb_net_hdr_push(skb, off, len_diff);
3494         if (unlikely(ret < 0))
3495                 return ret;
3496
3497         if (encap) {
3498                 skb->inner_mac_header = inner_net - inner_mac_len;
3499                 skb->inner_network_header = inner_net;
3500                 skb->inner_transport_header = inner_trans;
3501
3502                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L2_ETH)
3503                         skb_set_inner_protocol(skb, htons(ETH_P_TEB));
3504                 else
3505                         skb_set_inner_protocol(skb, skb->protocol);
3506
3507                 skb->encapsulation = 1;
3508                 skb_set_network_header(skb, mac_len);
3509
3510                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3511                         gso_type |= SKB_GSO_UDP_TUNNEL;
3512                 else if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE)
3513                         gso_type |= SKB_GSO_GRE;
3514                 else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3515                         gso_type |= SKB_GSO_IPXIP6;
3516                 else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3517                         gso_type |= SKB_GSO_IPXIP4;
3518
3519                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE ||
3520                     flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP) {
3521                         int nh_len = flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 ?
3522                                         sizeof(struct ipv6hdr) :
3523                                         sizeof(struct iphdr);
3524
3525                         skb_set_transport_header(skb, mac_len + nh_len);
3526                 }
3527
3528                 /* Match skb->protocol to new outer l3 protocol */
3529                 if (skb->protocol == htons(ETH_P_IP) &&
3530                     flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3531                         skb->protocol = htons(ETH_P_IPV6);
3532                 else if (skb->protocol == htons(ETH_P_IPV6) &&
3533                          flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3534                         skb->protocol = htons(ETH_P_IP);
3535         }
3536
3537         if (skb_is_gso(skb)) {
3538                 struct skb_shared_info *shinfo = skb_shinfo(skb);
3539
3540                 /* Due to header grow, MSS needs to be downgraded. */
3541                 if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3542                         skb_decrease_gso_size(shinfo, len_diff);
3543
3544                 /* Header must be checked, and gso_segs recomputed. */
3545                 shinfo->gso_type |= gso_type;
3546                 shinfo->gso_segs = 0;
3547         }
3548
3549         return 0;
3550 }
3551
3552 static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff,
3553                               u64 flags)
3554 {
3555         int ret;
3556
3557         if (unlikely(flags & ~(BPF_F_ADJ_ROOM_FIXED_GSO |
3558                                BPF_F_ADJ_ROOM_DECAP_L3_MASK |
3559                                BPF_F_ADJ_ROOM_NO_CSUM_RESET)))
3560                 return -EINVAL;
3561
3562         if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3563                 /* udp gso_size delineates datagrams, only allow if fixed */
3564                 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3565                     !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3566                         return -ENOTSUPP;
3567         }
3568
3569         ret = skb_unclone(skb, GFP_ATOMIC);
3570         if (unlikely(ret < 0))
3571                 return ret;
3572
3573         ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
3574         if (unlikely(ret < 0))
3575                 return ret;
3576
3577         /* Match skb->protocol to new outer l3 protocol */
3578         if (skb->protocol == htons(ETH_P_IP) &&
3579             flags & BPF_F_ADJ_ROOM_DECAP_L3_IPV6)
3580                 skb->protocol = htons(ETH_P_IPV6);
3581         else if (skb->protocol == htons(ETH_P_IPV6) &&
3582                  flags & BPF_F_ADJ_ROOM_DECAP_L3_IPV4)
3583                 skb->protocol = htons(ETH_P_IP);
3584
3585         if (skb_is_gso(skb)) {
3586                 struct skb_shared_info *shinfo = skb_shinfo(skb);
3587
3588                 /* Due to header shrink, MSS can be upgraded. */
3589                 if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3590                         skb_increase_gso_size(shinfo, len_diff);
3591
3592                 /* Header must be checked, and gso_segs recomputed. */
3593                 shinfo->gso_type |= SKB_GSO_DODGY;
3594                 shinfo->gso_segs = 0;
3595         }
3596
3597         return 0;
3598 }
3599
3600 #define BPF_SKB_MAX_LEN SKB_MAX_ALLOC
3601
3602 BPF_CALL_4(sk_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
3603            u32, mode, u64, flags)
3604 {
3605         u32 len_diff_abs = abs(len_diff);
3606         bool shrink = len_diff < 0;
3607         int ret = 0;
3608
3609         if (unlikely(flags || mode))
3610                 return -EINVAL;
3611         if (unlikely(len_diff_abs > 0xfffU))
3612                 return -EFAULT;
3613
3614         if (!shrink) {
3615                 ret = skb_cow(skb, len_diff);
3616                 if (unlikely(ret < 0))
3617                         return ret;
3618                 __skb_push(skb, len_diff_abs);
3619                 memset(skb->data, 0, len_diff_abs);
3620         } else {
3621                 if (unlikely(!pskb_may_pull(skb, len_diff_abs)))
3622                         return -ENOMEM;
3623                 __skb_pull(skb, len_diff_abs);
3624         }
3625         if (tls_sw_has_ctx_rx(skb->sk)) {
3626                 struct strp_msg *rxm = strp_msg(skb);
3627
3628                 rxm->full_len += len_diff;
3629         }
3630         return ret;
3631 }
3632
3633 static const struct bpf_func_proto sk_skb_adjust_room_proto = {
3634         .func           = sk_skb_adjust_room,
3635         .gpl_only       = false,
3636         .ret_type       = RET_INTEGER,
3637         .arg1_type      = ARG_PTR_TO_CTX,
3638         .arg2_type      = ARG_ANYTHING,
3639         .arg3_type      = ARG_ANYTHING,
3640         .arg4_type      = ARG_ANYTHING,
3641 };
3642
3643 BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
3644            u32, mode, u64, flags)
3645 {
3646         u32 len_cur, len_diff_abs = abs(len_diff);
3647         u32 len_min = bpf_skb_net_base_len(skb);
3648         u32 len_max = BPF_SKB_MAX_LEN;
3649         __be16 proto = skb->protocol;
3650         bool shrink = len_diff < 0;
3651         u32 off;
3652         int ret;
3653
3654         if (unlikely(flags & ~(BPF_F_ADJ_ROOM_MASK |
3655                                BPF_F_ADJ_ROOM_NO_CSUM_RESET)))
3656                 return -EINVAL;
3657         if (unlikely(len_diff_abs > 0xfffU))
3658                 return -EFAULT;
3659         if (unlikely(proto != htons(ETH_P_IP) &&
3660                      proto != htons(ETH_P_IPV6)))
3661                 return -ENOTSUPP;
3662
3663         off = skb_mac_header_len(skb);
3664         switch (mode) {
3665         case BPF_ADJ_ROOM_NET:
3666                 off += bpf_skb_net_base_len(skb);
3667                 break;
3668         case BPF_ADJ_ROOM_MAC:
3669                 break;
3670         default:
3671                 return -ENOTSUPP;
3672         }
3673
3674         if (flags & BPF_F_ADJ_ROOM_DECAP_L3_MASK) {
3675                 if (!shrink)
3676                         return -EINVAL;
3677
3678                 switch (flags & BPF_F_ADJ_ROOM_DECAP_L3_MASK) {
3679                 case BPF_F_ADJ_ROOM_DECAP_L3_IPV4:
3680                         len_min = sizeof(struct iphdr);
3681                         break;
3682                 case BPF_F_ADJ_ROOM_DECAP_L3_IPV6:
3683                         len_min = sizeof(struct ipv6hdr);
3684                         break;
3685                 default:
3686                         return -EINVAL;
3687                 }
3688         }
3689
3690         len_cur = skb->len - skb_network_offset(skb);
3691         if ((shrink && (len_diff_abs >= len_cur ||
3692                         len_cur - len_diff_abs < len_min)) ||
3693             (!shrink && (skb->len + len_diff_abs > len_max &&
3694                          !skb_is_gso(skb))))
3695                 return -ENOTSUPP;
3696
3697         ret = shrink ? bpf_skb_net_shrink(skb, off, len_diff_abs, flags) :
3698                        bpf_skb_net_grow(skb, off, len_diff_abs, flags);
3699         if (!ret && !(flags & BPF_F_ADJ_ROOM_NO_CSUM_RESET))
3700                 __skb_reset_checksum_unnecessary(skb);
3701
3702         bpf_compute_data_pointers(skb);
3703         return ret;
3704 }
3705
3706 static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
3707         .func           = bpf_skb_adjust_room,
3708         .gpl_only       = false,
3709         .ret_type       = RET_INTEGER,
3710         .arg1_type      = ARG_PTR_TO_CTX,
3711         .arg2_type      = ARG_ANYTHING,
3712         .arg3_type      = ARG_ANYTHING,
3713         .arg4_type      = ARG_ANYTHING,
3714 };
3715
3716 static u32 __bpf_skb_min_len(const struct sk_buff *skb)
3717 {
3718         u32 min_len = skb_network_offset(skb);
3719
3720         if (skb_transport_header_was_set(skb))
3721                 min_len = skb_transport_offset(skb);
3722         if (skb->ip_summed == CHECKSUM_PARTIAL)
3723                 min_len = skb_checksum_start_offset(skb) +
3724                           skb->csum_offset + sizeof(__sum16);
3725         return min_len;
3726 }
3727
3728 static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
3729 {
3730         unsigned int old_len = skb->len;
3731         int ret;
3732
3733         ret = __skb_grow_rcsum(skb, new_len);
3734         if (!ret)
3735                 memset(skb->data + old_len, 0, new_len - old_len);
3736         return ret;
3737 }
3738
3739 static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
3740 {
3741         return __skb_trim_rcsum(skb, new_len);
3742 }
3743
3744 static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len,
3745                                         u64 flags)
3746 {
3747         u32 max_len = BPF_SKB_MAX_LEN;
3748         u32 min_len = __bpf_skb_min_len(skb);
3749         int ret;
3750
3751         if (unlikely(flags || new_len > max_len || new_len < min_len))
3752                 return -EINVAL;
3753         if (skb->encapsulation)
3754                 return -ENOTSUPP;
3755
3756         /* The basic idea of this helper is that it's performing the
3757          * needed work to either grow or trim an skb, and eBPF program
3758          * rewrites the rest via helpers like bpf_skb_store_bytes(),
3759          * bpf_lX_csum_replace() and others rather than passing a raw
3760          * buffer here. This one is a slow path helper and intended
3761          * for replies with control messages.
3762          *
3763          * Like in bpf_skb_change_proto(), we want to keep this rather
3764          * minimal and without protocol specifics so that we are able
3765          * to separate concerns as in bpf_skb_store_bytes() should only
3766          * be the one responsible for writing buffers.
3767          *
3768          * It's really expected to be a slow path operation here for
3769          * control message replies, so we're implicitly linearizing,
3770          * uncloning and drop offloads from the skb by this.
3771          */
3772         ret = __bpf_try_make_writable(skb, skb->len);
3773         if (!ret) {
3774                 if (new_len > skb->len)
3775                         ret = bpf_skb_grow_rcsum(skb, new_len);
3776                 else if (new_len < skb->len)
3777                         ret = bpf_skb_trim_rcsum(skb, new_len);
3778                 if (!ret && skb_is_gso(skb))
3779                         skb_gso_reset(skb);
3780         }
3781         return ret;
3782 }
3783
3784 BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3785            u64, flags)
3786 {
3787         int ret = __bpf_skb_change_tail(skb, new_len, flags);
3788
3789         bpf_compute_data_pointers(skb);
3790         return ret;
3791 }
3792
3793 static const struct bpf_func_proto bpf_skb_change_tail_proto = {
3794         .func           = bpf_skb_change_tail,
3795         .gpl_only       = false,
3796         .ret_type       = RET_INTEGER,
3797         .arg1_type      = ARG_PTR_TO_CTX,
3798         .arg2_type      = ARG_ANYTHING,
3799         .arg3_type      = ARG_ANYTHING,
3800 };
3801
3802 BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3803            u64, flags)
3804 {
3805         return __bpf_skb_change_tail(skb, new_len, flags);
3806 }
3807
3808 static const struct bpf_func_proto sk_skb_change_tail_proto = {
3809         .func           = sk_skb_change_tail,
3810         .gpl_only       = false,
3811         .ret_type       = RET_INTEGER,
3812         .arg1_type      = ARG_PTR_TO_CTX,
3813         .arg2_type      = ARG_ANYTHING,
3814         .arg3_type      = ARG_ANYTHING,
3815 };
3816
3817 static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room,
3818                                         u64 flags)
3819 {
3820         u32 max_len = BPF_SKB_MAX_LEN;
3821         u32 new_len = skb->len + head_room;
3822         int ret;
3823
3824         if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
3825                      new_len < skb->len))
3826                 return -EINVAL;
3827
3828         ret = skb_cow(skb, head_room);
3829         if (likely(!ret)) {
3830                 /* Idea for this helper is that we currently only
3831                  * allow to expand on mac header. This means that
3832                  * skb->protocol network header, etc, stay as is.
3833                  * Compared to bpf_skb_change_tail(), we're more
3834                  * flexible due to not needing to linearize or
3835                  * reset GSO. Intention for this helper is to be
3836                  * used by an L3 skb that needs to push mac header
3837                  * for redirection into L2 device.
3838                  */
3839                 __skb_push(skb, head_room);
3840                 memset(skb->data, 0, head_room);
3841                 skb_reset_mac_header(skb);
3842                 skb_reset_mac_len(skb);
3843         }
3844
3845         return ret;
3846 }
3847
3848 BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
3849            u64, flags)
3850 {
3851         int ret = __bpf_skb_change_head(skb, head_room, flags);
3852
3853         bpf_compute_data_pointers(skb);
3854         return ret;
3855 }
3856
3857 static const struct bpf_func_proto bpf_skb_change_head_proto = {
3858         .func           = bpf_skb_change_head,
3859         .gpl_only       = false,
3860         .ret_type       = RET_INTEGER,
3861         .arg1_type      = ARG_PTR_TO_CTX,
3862         .arg2_type      = ARG_ANYTHING,
3863         .arg3_type      = ARG_ANYTHING,
3864 };
3865
3866 BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room,
3867            u64, flags)
3868 {
3869         return __bpf_skb_change_head(skb, head_room, flags);
3870 }
3871
3872 static const struct bpf_func_proto sk_skb_change_head_proto = {
3873         .func           = sk_skb_change_head,
3874         .gpl_only       = false,
3875         .ret_type       = RET_INTEGER,
3876         .arg1_type      = ARG_PTR_TO_CTX,
3877         .arg2_type      = ARG_ANYTHING,
3878         .arg3_type      = ARG_ANYTHING,
3879 };
3880
3881 BPF_CALL_1(bpf_xdp_get_buff_len, struct xdp_buff*, xdp)
3882 {
3883         return xdp_get_buff_len(xdp);
3884 }
3885
3886 static const struct bpf_func_proto bpf_xdp_get_buff_len_proto = {
3887         .func           = bpf_xdp_get_buff_len,
3888         .gpl_only       = false,
3889         .ret_type       = RET_INTEGER,
3890         .arg1_type      = ARG_PTR_TO_CTX,
3891 };
3892
3893 BTF_ID_LIST_SINGLE(bpf_xdp_get_buff_len_bpf_ids, struct, xdp_buff)
3894
3895 const struct bpf_func_proto bpf_xdp_get_buff_len_trace_proto = {
3896         .func           = bpf_xdp_get_buff_len,
3897         .gpl_only       = false,
3898         .arg1_type      = ARG_PTR_TO_BTF_ID,
3899         .arg1_btf_id    = &bpf_xdp_get_buff_len_bpf_ids[0],
3900 };
3901
3902 static unsigned long xdp_get_metalen(const struct xdp_buff *xdp)
3903 {
3904         return xdp_data_meta_unsupported(xdp) ? 0 :
3905                xdp->data - xdp->data_meta;
3906 }
3907
3908 BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
3909 {
3910         void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3911         unsigned long metalen = xdp_get_metalen(xdp);
3912         void *data_start = xdp_frame_end + metalen;
3913         void *data = xdp->data + offset;
3914
3915         if (unlikely(data < data_start ||
3916                      data > xdp->data_end - ETH_HLEN))
3917                 return -EINVAL;
3918
3919         if (metalen)
3920                 memmove(xdp->data_meta + offset,
3921                         xdp->data_meta, metalen);
3922         xdp->data_meta += offset;
3923         xdp->data = data;
3924
3925         return 0;
3926 }
3927
3928 static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
3929         .func           = bpf_xdp_adjust_head,
3930         .gpl_only       = false,
3931         .ret_type       = RET_INTEGER,
3932         .arg1_type      = ARG_PTR_TO_CTX,
3933         .arg2_type      = ARG_ANYTHING,
3934 };
3935
3936 void bpf_xdp_copy_buf(struct xdp_buff *xdp, unsigned long off,
3937                       void *buf, unsigned long len, bool flush)
3938 {
3939         unsigned long ptr_len, ptr_off = 0;
3940         skb_frag_t *next_frag, *end_frag;
3941         struct skb_shared_info *sinfo;
3942         void *src, *dst;
3943         u8 *ptr_buf;
3944
3945         if (likely(xdp->data_end - xdp->data >= off + len)) {
3946                 src = flush ? buf : xdp->data + off;
3947                 dst = flush ? xdp->data + off : buf;
3948                 memcpy(dst, src, len);
3949                 return;
3950         }
3951
3952         sinfo = xdp_get_shared_info_from_buff(xdp);
3953         end_frag = &sinfo->frags[sinfo->nr_frags];
3954         next_frag = &sinfo->frags[0];
3955
3956         ptr_len = xdp->data_end - xdp->data;
3957         ptr_buf = xdp->data;
3958
3959         while (true) {
3960                 if (off < ptr_off + ptr_len) {
3961                         unsigned long copy_off = off - ptr_off;
3962                         unsigned long copy_len = min(len, ptr_len - copy_off);
3963
3964                         src = flush ? buf : ptr_buf + copy_off;
3965                         dst = flush ? ptr_buf + copy_off : buf;
3966                         memcpy(dst, src, copy_len);
3967
3968                         off += copy_len;
3969                         len -= copy_len;
3970                         buf += copy_len;
3971                 }
3972
3973                 if (!len || next_frag == end_frag)
3974                         break;
3975
3976                 ptr_off += ptr_len;
3977                 ptr_buf = skb_frag_address(next_frag);
3978                 ptr_len = skb_frag_size(next_frag);
3979                 next_frag++;
3980         }
3981 }
3982
3983 void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len)
3984 {
3985         u32 size = xdp->data_end - xdp->data;
3986         struct skb_shared_info *sinfo;
3987         void *addr = xdp->data;
3988         int i;
3989
3990         if (unlikely(offset > 0xffff || len > 0xffff))
3991                 return ERR_PTR(-EFAULT);
3992
3993         if (unlikely(offset + len > xdp_get_buff_len(xdp)))
3994                 return ERR_PTR(-EINVAL);
3995
3996         if (likely(offset < size)) /* linear area */
3997                 goto out;
3998
3999         sinfo = xdp_get_shared_info_from_buff(xdp);
4000         offset -= size;
4001         for (i = 0; i < sinfo->nr_frags; i++) { /* paged area */
4002                 u32 frag_size = skb_frag_size(&sinfo->frags[i]);
4003
4004                 if  (offset < frag_size) {
4005                         addr = skb_frag_address(&sinfo->frags[i]);
4006                         size = frag_size;
4007                         break;
4008                 }
4009                 offset -= frag_size;
4010         }
4011 out:
4012         return offset + len <= size ? addr + offset : NULL;
4013 }
4014
4015 BPF_CALL_4(bpf_xdp_load_bytes, struct xdp_buff *, xdp, u32, offset,
4016            void *, buf, u32, len)
4017 {
4018         void *ptr;
4019
4020         ptr = bpf_xdp_pointer(xdp, offset, len);
4021         if (IS_ERR(ptr))
4022                 return PTR_ERR(ptr);
4023
4024         if (!ptr)
4025                 bpf_xdp_copy_buf(xdp, offset, buf, len, false);
4026         else
4027                 memcpy(buf, ptr, len);
4028
4029         return 0;
4030 }
4031
4032 static const struct bpf_func_proto bpf_xdp_load_bytes_proto = {
4033         .func           = bpf_xdp_load_bytes,
4034         .gpl_only       = false,
4035         .ret_type       = RET_INTEGER,
4036         .arg1_type      = ARG_PTR_TO_CTX,
4037         .arg2_type      = ARG_ANYTHING,
4038         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
4039         .arg4_type      = ARG_CONST_SIZE,
4040 };
4041
4042 int __bpf_xdp_load_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len)
4043 {
4044         return ____bpf_xdp_load_bytes(xdp, offset, buf, len);
4045 }
4046
4047 BPF_CALL_4(bpf_xdp_store_bytes, struct xdp_buff *, xdp, u32, offset,
4048            void *, buf, u32, len)
4049 {
4050         void *ptr;
4051
4052         ptr = bpf_xdp_pointer(xdp, offset, len);
4053         if (IS_ERR(ptr))
4054                 return PTR_ERR(ptr);
4055
4056         if (!ptr)
4057                 bpf_xdp_copy_buf(xdp, offset, buf, len, true);
4058         else
4059                 memcpy(ptr, buf, len);
4060
4061         return 0;
4062 }
4063
4064 static const struct bpf_func_proto bpf_xdp_store_bytes_proto = {
4065         .func           = bpf_xdp_store_bytes,
4066         .gpl_only       = false,
4067         .ret_type       = RET_INTEGER,
4068         .arg1_type      = ARG_PTR_TO_CTX,
4069         .arg2_type      = ARG_ANYTHING,
4070         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
4071         .arg4_type      = ARG_CONST_SIZE,
4072 };
4073
4074 int __bpf_xdp_store_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len)
4075 {
4076         return ____bpf_xdp_store_bytes(xdp, offset, buf, len);
4077 }
4078
4079 static int bpf_xdp_frags_increase_tail(struct xdp_buff *xdp, int offset)
4080 {
4081         struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
4082         skb_frag_t *frag = &sinfo->frags[sinfo->nr_frags - 1];
4083         struct xdp_rxq_info *rxq = xdp->rxq;
4084         unsigned int tailroom;
4085
4086         if (!rxq->frag_size || rxq->frag_size > xdp->frame_sz)
4087                 return -EOPNOTSUPP;
4088
4089         tailroom = rxq->frag_size - skb_frag_size(frag) - skb_frag_off(frag);
4090         if (unlikely(offset > tailroom))
4091                 return -EINVAL;
4092
4093         memset(skb_frag_address(frag) + skb_frag_size(frag), 0, offset);
4094         skb_frag_size_add(frag, offset);
4095         sinfo->xdp_frags_size += offset;
4096         if (rxq->mem.type == MEM_TYPE_XSK_BUFF_POOL)
4097                 xsk_buff_get_tail(xdp)->data_end += offset;
4098
4099         return 0;
4100 }
4101
4102 static void bpf_xdp_shrink_data_zc(struct xdp_buff *xdp, int shrink,
4103                                    struct xdp_mem_info *mem_info, bool release)
4104 {
4105         struct xdp_buff *zc_frag = xsk_buff_get_tail(xdp);
4106
4107         if (release) {
4108                 xsk_buff_del_tail(zc_frag);
4109                 __xdp_return(NULL, mem_info, false, zc_frag);
4110         } else {
4111                 zc_frag->data_end -= shrink;
4112         }
4113 }
4114
4115 static bool bpf_xdp_shrink_data(struct xdp_buff *xdp, skb_frag_t *frag,
4116                                 int shrink)
4117 {
4118         struct xdp_mem_info *mem_info = &xdp->rxq->mem;
4119         bool release = skb_frag_size(frag) == shrink;
4120
4121         if (mem_info->type == MEM_TYPE_XSK_BUFF_POOL) {
4122                 bpf_xdp_shrink_data_zc(xdp, shrink, mem_info, release);
4123                 goto out;
4124         }
4125
4126         if (release) {
4127                 struct page *page = skb_frag_page(frag);
4128
4129                 __xdp_return(page_address(page), mem_info, false, NULL);
4130         }
4131
4132 out:
4133         return release;
4134 }
4135
4136 static int bpf_xdp_frags_shrink_tail(struct xdp_buff *xdp, int offset)
4137 {
4138         struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
4139         int i, n_frags_free = 0, len_free = 0;
4140
4141         if (unlikely(offset > (int)xdp_get_buff_len(xdp) - ETH_HLEN))
4142                 return -EINVAL;
4143
4144         for (i = sinfo->nr_frags - 1; i >= 0 && offset > 0; i--) {
4145                 skb_frag_t *frag = &sinfo->frags[i];
4146                 int shrink = min_t(int, offset, skb_frag_size(frag));
4147
4148                 len_free += shrink;
4149                 offset -= shrink;
4150                 if (bpf_xdp_shrink_data(xdp, frag, shrink)) {
4151                         n_frags_free++;
4152                 } else {
4153                         skb_frag_size_sub(frag, shrink);
4154                         break;
4155                 }
4156         }
4157         sinfo->nr_frags -= n_frags_free;
4158         sinfo->xdp_frags_size -= len_free;
4159
4160         if (unlikely(!sinfo->nr_frags)) {
4161                 xdp_buff_clear_frags_flag(xdp);
4162                 xdp->data_end -= offset;
4163         }
4164
4165         return 0;
4166 }
4167
4168 BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
4169 {
4170         void *data_hard_end = xdp_data_hard_end(xdp); /* use xdp->frame_sz */
4171         void *data_end = xdp->data_end + offset;
4172
4173         if (unlikely(xdp_buff_has_frags(xdp))) { /* non-linear xdp buff */
4174                 if (offset < 0)
4175                         return bpf_xdp_frags_shrink_tail(xdp, -offset);
4176
4177                 return bpf_xdp_frags_increase_tail(xdp, offset);
4178         }
4179
4180         /* Notice that xdp_data_hard_end have reserved some tailroom */
4181         if (unlikely(data_end > data_hard_end))
4182                 return -EINVAL;
4183
4184         if (unlikely(data_end < xdp->data + ETH_HLEN))
4185                 return -EINVAL;
4186
4187         /* Clear memory area on grow, can contain uninit kernel memory */
4188         if (offset > 0)
4189                 memset(xdp->data_end, 0, offset);
4190
4191         xdp->data_end = data_end;
4192
4193         return 0;
4194 }
4195
4196 static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
4197         .func           = bpf_xdp_adjust_tail,
4198         .gpl_only       = false,
4199         .ret_type       = RET_INTEGER,
4200         .arg1_type      = ARG_PTR_TO_CTX,
4201         .arg2_type      = ARG_ANYTHING,
4202 };
4203
4204 BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
4205 {
4206         void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
4207         void *meta = xdp->data_meta + offset;
4208         unsigned long metalen = xdp->data - meta;
4209
4210         if (xdp_data_meta_unsupported(xdp))
4211                 return -ENOTSUPP;
4212         if (unlikely(meta < xdp_frame_end ||
4213                      meta > xdp->data))
4214                 return -EINVAL;
4215         if (unlikely(xdp_metalen_invalid(metalen)))
4216                 return -EACCES;
4217
4218         xdp->data_meta = meta;
4219
4220         return 0;
4221 }
4222
4223 static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
4224         .func           = bpf_xdp_adjust_meta,
4225         .gpl_only       = false,
4226         .ret_type       = RET_INTEGER,
4227         .arg1_type      = ARG_PTR_TO_CTX,
4228         .arg2_type      = ARG_ANYTHING,
4229 };
4230
4231 /**
4232  * DOC: xdp redirect
4233  *
4234  * XDP_REDIRECT works by a three-step process, implemented in the functions
4235  * below:
4236  *
4237  * 1. The bpf_redirect() and bpf_redirect_map() helpers will lookup the target
4238  *    of the redirect and store it (along with some other metadata) in a per-CPU
4239  *    struct bpf_redirect_info.
4240  *
4241  * 2. When the program returns the XDP_REDIRECT return code, the driver will
4242  *    call xdp_do_redirect() which will use the information in struct
4243  *    bpf_redirect_info to actually enqueue the frame into a map type-specific
4244  *    bulk queue structure.
4245  *
4246  * 3. Before exiting its NAPI poll loop, the driver will call
4247  *    xdp_do_flush(), which will flush all the different bulk queues,
4248  *    thus completing the redirect. Note that xdp_do_flush() must be
4249  *    called before napi_complete_done() in the driver, as the
4250  *    XDP_REDIRECT logic relies on being inside a single NAPI instance
4251  *    through to the xdp_do_flush() call for RCU protection of all
4252  *    in-kernel data structures.
4253  */
4254 /*
4255  * Pointers to the map entries will be kept around for this whole sequence of
4256  * steps, protected by RCU. However, there is no top-level rcu_read_lock() in
4257  * the core code; instead, the RCU protection relies on everything happening
4258  * inside a single NAPI poll sequence, which means it's between a pair of calls
4259  * to local_bh_disable()/local_bh_enable().
4260  *
4261  * The map entries are marked as __rcu and the map code makes sure to
4262  * dereference those pointers with rcu_dereference_check() in a way that works
4263  * for both sections that to hold an rcu_read_lock() and sections that are
4264  * called from NAPI without a separate rcu_read_lock(). The code below does not
4265  * use RCU annotations, but relies on those in the map code.
4266  */
4267 void xdp_do_flush(void)
4268 {
4269         __dev_flush();
4270         __cpu_map_flush();
4271         __xsk_map_flush();
4272 }
4273 EXPORT_SYMBOL_GPL(xdp_do_flush);
4274
4275 #if defined(CONFIG_DEBUG_NET) && defined(CONFIG_BPF_SYSCALL)
4276 void xdp_do_check_flushed(struct napi_struct *napi)
4277 {
4278         bool ret;
4279
4280         ret = dev_check_flush();
4281         ret |= cpu_map_check_flush();
4282         ret |= xsk_map_check_flush();
4283
4284         WARN_ONCE(ret, "Missing xdp_do_flush() invocation after NAPI by %ps\n",
4285                   napi->poll);
4286 }
4287 #endif
4288
4289 void bpf_clear_redirect_map(struct bpf_map *map)
4290 {
4291         struct bpf_redirect_info *ri;
4292         int cpu;
4293
4294         for_each_possible_cpu(cpu) {
4295                 ri = per_cpu_ptr(&bpf_redirect_info, cpu);
4296                 /* Avoid polluting remote cacheline due to writes if
4297                  * not needed. Once we pass this test, we need the
4298                  * cmpxchg() to make sure it hasn't been changed in
4299                  * the meantime by remote CPU.
4300                  */
4301                 if (unlikely(READ_ONCE(ri->map) == map))
4302                         cmpxchg(&ri->map, map, NULL);
4303         }
4304 }
4305
4306 DEFINE_STATIC_KEY_FALSE(bpf_master_redirect_enabled_key);
4307 EXPORT_SYMBOL_GPL(bpf_master_redirect_enabled_key);
4308
4309 u32 xdp_master_redirect(struct xdp_buff *xdp)
4310 {
4311         struct net_device *master, *slave;
4312         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
4313
4314         master = netdev_master_upper_dev_get_rcu(xdp->rxq->dev);
4315         slave = master->netdev_ops->ndo_xdp_get_xmit_slave(master, xdp);
4316         if (slave && slave != xdp->rxq->dev) {
4317                 /* The target device is different from the receiving device, so
4318                  * redirect it to the new device.
4319                  * Using XDP_REDIRECT gets the correct behaviour from XDP enabled
4320                  * drivers to unmap the packet from their rx ring.
4321                  */
4322                 ri->tgt_index = slave->ifindex;
4323                 ri->map_id = INT_MAX;
4324                 ri->map_type = BPF_MAP_TYPE_UNSPEC;
4325                 return XDP_REDIRECT;
4326         }
4327         return XDP_TX;
4328 }
4329 EXPORT_SYMBOL_GPL(xdp_master_redirect);
4330
4331 static inline int __xdp_do_redirect_xsk(struct bpf_redirect_info *ri,
4332                                         struct net_device *dev,
4333                                         struct xdp_buff *xdp,
4334                                         struct bpf_prog *xdp_prog)
4335 {
4336         enum bpf_map_type map_type = ri->map_type;
4337         void *fwd = ri->tgt_value;
4338         u32 map_id = ri->map_id;
4339         int err;
4340
4341         ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4342         ri->map_type = BPF_MAP_TYPE_UNSPEC;
4343
4344         err = __xsk_map_redirect(fwd, xdp);
4345         if (unlikely(err))
4346                 goto err;
4347
4348         _trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4349         return 0;
4350 err:
4351         _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4352         return err;
4353 }
4354
4355 static __always_inline int __xdp_do_redirect_frame(struct bpf_redirect_info *ri,
4356                                                    struct net_device *dev,
4357                                                    struct xdp_frame *xdpf,
4358                                                    struct bpf_prog *xdp_prog)
4359 {
4360         enum bpf_map_type map_type = ri->map_type;
4361         void *fwd = ri->tgt_value;
4362         u32 map_id = ri->map_id;
4363         struct bpf_map *map;
4364         int err;
4365
4366         ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4367         ri->map_type = BPF_MAP_TYPE_UNSPEC;
4368
4369         if (unlikely(!xdpf)) {
4370                 err = -EOVERFLOW;
4371                 goto err;
4372         }
4373
4374         switch (map_type) {
4375         case BPF_MAP_TYPE_DEVMAP:
4376                 fallthrough;
4377         case BPF_MAP_TYPE_DEVMAP_HASH:
4378                 map = READ_ONCE(ri->map);
4379                 if (unlikely(map)) {
4380                         WRITE_ONCE(ri->map, NULL);
4381                         err = dev_map_enqueue_multi(xdpf, dev, map,
4382                                                     ri->flags & BPF_F_EXCLUDE_INGRESS);
4383                 } else {
4384                         err = dev_map_enqueue(fwd, xdpf, dev);
4385                 }
4386                 break;
4387         case BPF_MAP_TYPE_CPUMAP:
4388                 err = cpu_map_enqueue(fwd, xdpf, dev);
4389                 break;
4390         case BPF_MAP_TYPE_UNSPEC:
4391                 if (map_id == INT_MAX) {
4392                         fwd = dev_get_by_index_rcu(dev_net(dev), ri->tgt_index);
4393                         if (unlikely(!fwd)) {
4394                                 err = -EINVAL;
4395                                 break;
4396                         }
4397                         err = dev_xdp_enqueue(fwd, xdpf, dev);
4398                         break;
4399                 }
4400                 fallthrough;
4401         default:
4402                 err = -EBADRQC;
4403         }
4404
4405         if (unlikely(err))
4406                 goto err;
4407
4408         _trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4409         return 0;
4410 err:
4411         _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4412         return err;
4413 }
4414
4415 int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
4416                     struct bpf_prog *xdp_prog)
4417 {
4418         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
4419         enum bpf_map_type map_type = ri->map_type;
4420
4421         if (map_type == BPF_MAP_TYPE_XSKMAP)
4422                 return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
4423
4424         return __xdp_do_redirect_frame(ri, dev, xdp_convert_buff_to_frame(xdp),
4425                                        xdp_prog);
4426 }
4427 EXPORT_SYMBOL_GPL(xdp_do_redirect);
4428
4429 int xdp_do_redirect_frame(struct net_device *dev, struct xdp_buff *xdp,
4430                           struct xdp_frame *xdpf, struct bpf_prog *xdp_prog)
4431 {
4432         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
4433         enum bpf_map_type map_type = ri->map_type;
4434
4435         if (map_type == BPF_MAP_TYPE_XSKMAP)
4436                 return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
4437
4438         return __xdp_do_redirect_frame(ri, dev, xdpf, xdp_prog);
4439 }
4440 EXPORT_SYMBOL_GPL(xdp_do_redirect_frame);
4441
4442 static int xdp_do_generic_redirect_map(struct net_device *dev,
4443                                        struct sk_buff *skb,
4444                                        struct xdp_buff *xdp,
4445                                        struct bpf_prog *xdp_prog,
4446                                        void *fwd,
4447                                        enum bpf_map_type map_type, u32 map_id)
4448 {
4449         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
4450         struct bpf_map *map;
4451         int err;
4452
4453         switch (map_type) {
4454         case BPF_MAP_TYPE_DEVMAP:
4455                 fallthrough;
4456         case BPF_MAP_TYPE_DEVMAP_HASH:
4457                 map = READ_ONCE(ri->map);
4458                 if (unlikely(map)) {
4459                         WRITE_ONCE(ri->map, NULL);
4460                         err = dev_map_redirect_multi(dev, skb, xdp_prog, map,
4461                                                      ri->flags & BPF_F_EXCLUDE_INGRESS);
4462                 } else {
4463                         err = dev_map_generic_redirect(fwd, skb, xdp_prog);
4464                 }
4465                 if (unlikely(err))
4466                         goto err;
4467                 break;
4468         case BPF_MAP_TYPE_XSKMAP:
4469                 err = xsk_generic_rcv(fwd, xdp);
4470                 if (err)
4471                         goto err;
4472                 consume_skb(skb);
4473                 break;
4474         case BPF_MAP_TYPE_CPUMAP:
4475                 err = cpu_map_generic_redirect(fwd, skb);
4476                 if (unlikely(err))
4477                         goto err;
4478                 break;
4479         default:
4480                 err = -EBADRQC;
4481                 goto err;
4482         }
4483
4484         _trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4485         return 0;
4486 err:
4487         _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4488         return err;
4489 }
4490
4491 int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
4492                             struct xdp_buff *xdp, struct bpf_prog *xdp_prog)
4493 {
4494         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
4495         enum bpf_map_type map_type = ri->map_type;
4496         void *fwd = ri->tgt_value;
4497         u32 map_id = ri->map_id;
4498         int err;
4499
4500         ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4501         ri->map_type = BPF_MAP_TYPE_UNSPEC;
4502
4503         if (map_type == BPF_MAP_TYPE_UNSPEC && map_id == INT_MAX) {
4504                 fwd = dev_get_by_index_rcu(dev_net(dev), ri->tgt_index);
4505                 if (unlikely(!fwd)) {
4506                         err = -EINVAL;
4507                         goto err;
4508                 }
4509
4510                 err = xdp_ok_fwd_dev(fwd, skb->len);
4511                 if (unlikely(err))
4512                         goto err;
4513
4514                 skb->dev = fwd;
4515                 _trace_xdp_redirect(dev, xdp_prog, ri->tgt_index);
4516                 generic_xdp_tx(skb, xdp_prog);
4517                 return 0;
4518         }
4519
4520         return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog, fwd, map_type, map_id);
4521 err:
4522         _trace_xdp_redirect_err(dev, xdp_prog, ri->tgt_index, err);
4523         return err;
4524 }
4525
4526 BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
4527 {
4528         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
4529
4530         if (unlikely(flags))
4531                 return XDP_ABORTED;
4532
4533         /* NB! Map type UNSPEC and map_id == INT_MAX (never generated
4534          * by map_idr) is used for ifindex based XDP redirect.
4535          */
4536         ri->tgt_index = ifindex;
4537         ri->map_id = INT_MAX;
4538         ri->map_type = BPF_MAP_TYPE_UNSPEC;
4539
4540         return XDP_REDIRECT;
4541 }
4542
4543 static const struct bpf_func_proto bpf_xdp_redirect_proto = {
4544         .func           = bpf_xdp_redirect,
4545         .gpl_only       = false,
4546         .ret_type       = RET_INTEGER,
4547         .arg1_type      = ARG_ANYTHING,
4548         .arg2_type      = ARG_ANYTHING,
4549 };
4550
4551 BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u64, key,
4552            u64, flags)
4553 {
4554         return map->ops->map_redirect(map, key, flags);
4555 }
4556
4557 static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
4558         .func           = bpf_xdp_redirect_map,
4559         .gpl_only       = false,
4560         .ret_type       = RET_INTEGER,
4561         .arg1_type      = ARG_CONST_MAP_PTR,
4562         .arg2_type      = ARG_ANYTHING,
4563         .arg3_type      = ARG_ANYTHING,
4564 };
4565
4566 static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
4567                                   unsigned long off, unsigned long len)
4568 {
4569         void *ptr = skb_header_pointer(skb, off, len, dst_buff);
4570
4571         if (unlikely(!ptr))
4572                 return len;
4573         if (ptr != dst_buff)
4574                 memcpy(dst_buff, ptr, len);
4575
4576         return 0;
4577 }
4578
4579 BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
4580            u64, flags, void *, meta, u64, meta_size)
4581 {
4582         u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
4583
4584         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
4585                 return -EINVAL;
4586         if (unlikely(!skb || skb_size > skb->len))
4587                 return -EFAULT;
4588
4589         return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
4590                                 bpf_skb_copy);
4591 }
4592
4593 static const struct bpf_func_proto bpf_skb_event_output_proto = {
4594         .func           = bpf_skb_event_output,
4595         .gpl_only       = true,
4596         .ret_type       = RET_INTEGER,
4597         .arg1_type      = ARG_PTR_TO_CTX,
4598         .arg2_type      = ARG_CONST_MAP_PTR,
4599         .arg3_type      = ARG_ANYTHING,
4600         .arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
4601         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
4602 };
4603
4604 BTF_ID_LIST_SINGLE(bpf_skb_output_btf_ids, struct, sk_buff)
4605
4606 const struct bpf_func_proto bpf_skb_output_proto = {
4607         .func           = bpf_skb_event_output,
4608         .gpl_only       = true,
4609         .ret_type       = RET_INTEGER,
4610         .arg1_type      = ARG_PTR_TO_BTF_ID,
4611         .arg1_btf_id    = &bpf_skb_output_btf_ids[0],
4612         .arg2_type      = ARG_CONST_MAP_PTR,
4613         .arg3_type      = ARG_ANYTHING,
4614         .arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
4615         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
4616 };
4617
4618 static unsigned short bpf_tunnel_key_af(u64 flags)
4619 {
4620         return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
4621 }
4622
4623 BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
4624            u32, size, u64, flags)
4625 {
4626         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
4627         u8 compat[sizeof(struct bpf_tunnel_key)];
4628         void *to_orig = to;
4629         int err;
4630
4631         if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6 |
4632                                          BPF_F_TUNINFO_FLAGS)))) {
4633                 err = -EINVAL;
4634                 goto err_clear;
4635         }
4636         if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
4637                 err = -EPROTO;
4638                 goto err_clear;
4639         }
4640         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
4641                 err = -EINVAL;
4642                 switch (size) {
4643                 case offsetof(struct bpf_tunnel_key, local_ipv6[0]):
4644                 case offsetof(struct bpf_tunnel_key, tunnel_label):
4645                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
4646                         goto set_compat;
4647                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
4648                         /* Fixup deprecated structure layouts here, so we have
4649                          * a common path later on.
4650                          */
4651                         if (ip_tunnel_info_af(info) != AF_INET)
4652                                 goto err_clear;
4653 set_compat:
4654                         to = (struct bpf_tunnel_key *)compat;
4655                         break;
4656                 default:
4657                         goto err_clear;
4658                 }
4659         }
4660
4661         to->tunnel_id = be64_to_cpu(info->key.tun_id);
4662         to->tunnel_tos = info->key.tos;
4663         to->tunnel_ttl = info->key.ttl;
4664         if (flags & BPF_F_TUNINFO_FLAGS)
4665                 to->tunnel_flags = info->key.tun_flags;
4666         else
4667                 to->tunnel_ext = 0;
4668
4669         if (flags & BPF_F_TUNINFO_IPV6) {
4670                 memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
4671                        sizeof(to->remote_ipv6));
4672                 memcpy(to->local_ipv6, &info->key.u.ipv6.dst,
4673                        sizeof(to->local_ipv6));
4674                 to->tunnel_label = be32_to_cpu(info->key.label);
4675         } else {
4676                 to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
4677                 memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4678                 to->local_ipv4 = be32_to_cpu(info->key.u.ipv4.dst);
4679                 memset(&to->local_ipv6[1], 0, sizeof(__u32) * 3);
4680                 to->tunnel_label = 0;
4681         }
4682
4683         if (unlikely(size != sizeof(struct bpf_tunnel_key)))
4684                 memcpy(to_orig, to, size);
4685
4686         return 0;
4687 err_clear:
4688         memset(to_orig, 0, size);
4689         return err;
4690 }
4691
4692 static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
4693         .func           = bpf_skb_get_tunnel_key,
4694         .gpl_only       = false,
4695         .ret_type       = RET_INTEGER,
4696         .arg1_type      = ARG_PTR_TO_CTX,
4697         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
4698         .arg3_type      = ARG_CONST_SIZE,
4699         .arg4_type      = ARG_ANYTHING,
4700 };
4701
4702 BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
4703 {
4704         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
4705         int err;
4706
4707         if (unlikely(!info ||
4708                      !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
4709                 err = -ENOENT;
4710                 goto err_clear;
4711         }
4712         if (unlikely(size < info->options_len)) {
4713                 err = -ENOMEM;
4714                 goto err_clear;
4715         }
4716
4717         ip_tunnel_info_opts_get(to, info);
4718         if (size > info->options_len)
4719                 memset(to + info->options_len, 0, size - info->options_len);
4720
4721         return info->options_len;
4722 err_clear:
4723         memset(to, 0, size);
4724         return err;
4725 }
4726
4727 static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
4728         .func           = bpf_skb_get_tunnel_opt,
4729         .gpl_only       = false,
4730         .ret_type       = RET_INTEGER,
4731         .arg1_type      = ARG_PTR_TO_CTX,
4732         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
4733         .arg3_type      = ARG_CONST_SIZE,
4734 };
4735
4736 static struct metadata_dst __percpu *md_dst;
4737
4738 BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
4739            const struct bpf_tunnel_key *, from, u32, size, u64, flags)
4740 {
4741         struct metadata_dst *md = this_cpu_ptr(md_dst);
4742         u8 compat[sizeof(struct bpf_tunnel_key)];
4743         struct ip_tunnel_info *info;
4744
4745         if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
4746                                BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER |
4747                                BPF_F_NO_TUNNEL_KEY)))
4748                 return -EINVAL;
4749         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
4750                 switch (size) {
4751                 case offsetof(struct bpf_tunnel_key, local_ipv6[0]):
4752                 case offsetof(struct bpf_tunnel_key, tunnel_label):
4753                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
4754                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
4755                         /* Fixup deprecated structure layouts here, so we have
4756                          * a common path later on.
4757                          */
4758                         memcpy(compat, from, size);
4759                         memset(compat + size, 0, sizeof(compat) - size);
4760                         from = (const struct bpf_tunnel_key *) compat;
4761                         break;
4762                 default:
4763                         return -EINVAL;
4764                 }
4765         }
4766         if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
4767                      from->tunnel_ext))
4768                 return -EINVAL;
4769
4770         skb_dst_drop(skb);
4771         dst_hold((struct dst_entry *) md);
4772         skb_dst_set(skb, (struct dst_entry *) md);
4773
4774         info = &md->u.tun_info;
4775         memset(info, 0, sizeof(*info));
4776         info->mode = IP_TUNNEL_INFO_TX;
4777
4778         info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
4779         if (flags & BPF_F_DONT_FRAGMENT)
4780                 info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;
4781         if (flags & BPF_F_ZERO_CSUM_TX)
4782                 info->key.tun_flags &= ~TUNNEL_CSUM;
4783         if (flags & BPF_F_SEQ_NUMBER)
4784                 info->key.tun_flags |= TUNNEL_SEQ;
4785         if (flags & BPF_F_NO_TUNNEL_KEY)
4786                 info->key.tun_flags &= ~TUNNEL_KEY;
4787
4788         info->key.tun_id = cpu_to_be64(from->tunnel_id);
4789         info->key.tos = from->tunnel_tos;
4790         info->key.ttl = from->tunnel_ttl;
4791
4792         if (flags & BPF_F_TUNINFO_IPV6) {
4793                 info->mode |= IP_TUNNEL_INFO_IPV6;
4794                 memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
4795                        sizeof(from->remote_ipv6));
4796                 memcpy(&info->key.u.ipv6.src, from->local_ipv6,
4797                        sizeof(from->local_ipv6));
4798                 info->key.label = cpu_to_be32(from->tunnel_label) &
4799                                   IPV6_FLOWLABEL_MASK;
4800         } else {
4801                 info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
4802                 info->key.u.ipv4.src = cpu_to_be32(from->local_ipv4);
4803                 info->key.flow_flags = FLOWI_FLAG_ANYSRC;
4804         }
4805
4806         return 0;
4807 }
4808
4809 static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
4810         .func           = bpf_skb_set_tunnel_key,
4811         .gpl_only       = false,
4812         .ret_type       = RET_INTEGER,
4813         .arg1_type      = ARG_PTR_TO_CTX,
4814         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
4815         .arg3_type      = ARG_CONST_SIZE,
4816         .arg4_type      = ARG_ANYTHING,
4817 };
4818
4819 BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
4820            const u8 *, from, u32, size)
4821 {
4822         struct ip_tunnel_info *info = skb_tunnel_info(skb);
4823         const struct metadata_dst *md = this_cpu_ptr(md_dst);
4824
4825         if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
4826                 return -EINVAL;
4827         if (unlikely(size > IP_TUNNEL_OPTS_MAX))
4828                 return -ENOMEM;
4829
4830         ip_tunnel_info_opts_set(info, from, size, TUNNEL_OPTIONS_PRESENT);
4831
4832         return 0;
4833 }
4834
4835 static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
4836         .func           = bpf_skb_set_tunnel_opt,
4837         .gpl_only       = false,
4838         .ret_type       = RET_INTEGER,
4839         .arg1_type      = ARG_PTR_TO_CTX,
4840         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
4841         .arg3_type      = ARG_CONST_SIZE,
4842 };
4843
4844 static const struct bpf_func_proto *
4845 bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
4846 {
4847         if (!md_dst) {
4848                 struct metadata_dst __percpu *tmp;
4849
4850                 tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
4851                                                 METADATA_IP_TUNNEL,
4852                                                 GFP_KERNEL);
4853                 if (!tmp)
4854                         return NULL;
4855                 if (cmpxchg(&md_dst, NULL, tmp))
4856                         metadata_dst_free_percpu(tmp);
4857         }
4858
4859         switch (which) {
4860         case BPF_FUNC_skb_set_tunnel_key:
4861                 return &bpf_skb_set_tunnel_key_proto;
4862         case BPF_FUNC_skb_set_tunnel_opt:
4863                 return &bpf_skb_set_tunnel_opt_proto;
4864         default:
4865                 return NULL;
4866         }
4867 }
4868
4869 BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
4870            u32, idx)
4871 {
4872         struct bpf_array *array = container_of(map, struct bpf_array, map);
4873         struct cgroup *cgrp;
4874         struct sock *sk;
4875
4876         sk = skb_to_full_sk(skb);
4877         if (!sk || !sk_fullsock(sk))
4878                 return -ENOENT;
4879         if (unlikely(idx >= array->map.max_entries))
4880                 return -E2BIG;
4881
4882         cgrp = READ_ONCE(array->ptrs[idx]);
4883         if (unlikely(!cgrp))
4884                 return -EAGAIN;
4885
4886         return sk_under_cgroup_hierarchy(sk, cgrp);
4887 }
4888
4889 static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
4890         .func           = bpf_skb_under_cgroup,
4891         .gpl_only       = false,
4892         .ret_type       = RET_INTEGER,
4893         .arg1_type      = ARG_PTR_TO_CTX,
4894         .arg2_type      = ARG_CONST_MAP_PTR,
4895         .arg3_type      = ARG_ANYTHING,
4896 };
4897
4898 #ifdef CONFIG_SOCK_CGROUP_DATA
4899 static inline u64 __bpf_sk_cgroup_id(struct sock *sk)
4900 {
4901         struct cgroup *cgrp;
4902
4903         sk = sk_to_full_sk(sk);
4904         if (!sk || !sk_fullsock(sk))
4905                 return 0;
4906
4907         cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4908         return cgroup_id(cgrp);
4909 }
4910
4911 BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
4912 {
4913         return __bpf_sk_cgroup_id(skb->sk);
4914 }
4915
4916 static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
4917         .func           = bpf_skb_cgroup_id,
4918         .gpl_only       = false,
4919         .ret_type       = RET_INTEGER,
4920         .arg1_type      = ARG_PTR_TO_CTX,
4921 };
4922
4923 static inline u64 __bpf_sk_ancestor_cgroup_id(struct sock *sk,
4924                                               int ancestor_level)
4925 {
4926         struct cgroup *ancestor;
4927         struct cgroup *cgrp;
4928
4929         sk = sk_to_full_sk(sk);
4930         if (!sk || !sk_fullsock(sk))
4931                 return 0;
4932
4933         cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4934         ancestor = cgroup_ancestor(cgrp, ancestor_level);
4935         if (!ancestor)
4936                 return 0;
4937
4938         return cgroup_id(ancestor);
4939 }
4940
4941 BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
4942            ancestor_level)
4943 {
4944         return __bpf_sk_ancestor_cgroup_id(skb->sk, ancestor_level);
4945 }
4946
4947 static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
4948         .func           = bpf_skb_ancestor_cgroup_id,
4949         .gpl_only       = false,
4950         .ret_type       = RET_INTEGER,
4951         .arg1_type      = ARG_PTR_TO_CTX,
4952         .arg2_type      = ARG_ANYTHING,
4953 };
4954
4955 BPF_CALL_1(bpf_sk_cgroup_id, struct sock *, sk)
4956 {
4957         return __bpf_sk_cgroup_id(sk);
4958 }
4959
4960 static const struct bpf_func_proto bpf_sk_cgroup_id_proto = {
4961         .func           = bpf_sk_cgroup_id,
4962         .gpl_only       = false,
4963         .ret_type       = RET_INTEGER,
4964         .arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
4965 };
4966
4967 BPF_CALL_2(bpf_sk_ancestor_cgroup_id, struct sock *, sk, int, ancestor_level)
4968 {
4969         return __bpf_sk_ancestor_cgroup_id(sk, ancestor_level);
4970 }
4971
4972 static const struct bpf_func_proto bpf_sk_ancestor_cgroup_id_proto = {
4973         .func           = bpf_sk_ancestor_cgroup_id,
4974         .gpl_only       = false,
4975         .ret_type       = RET_INTEGER,
4976         .arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
4977         .arg2_type      = ARG_ANYTHING,
4978 };
4979 #endif
4980
4981 static unsigned long bpf_xdp_copy(void *dst, const void *ctx,
4982                                   unsigned long off, unsigned long len)
4983 {
4984         struct xdp_buff *xdp = (struct xdp_buff *)ctx;
4985
4986         bpf_xdp_copy_buf(xdp, off, dst, len, false);
4987         return 0;
4988 }
4989
4990 BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
4991            u64, flags, void *, meta, u64, meta_size)
4992 {
4993         u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
4994
4995         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
4996                 return -EINVAL;
4997
4998         if (unlikely(!xdp || xdp_size > xdp_get_buff_len(xdp)))
4999                 return -EFAULT;
5000
5001         return bpf_event_output(map, flags, meta, meta_size, xdp,
5002                                 xdp_size, bpf_xdp_copy);
5003 }
5004
5005 static const struct bpf_func_proto bpf_xdp_event_output_proto = {
5006         .func           = bpf_xdp_event_output,
5007         .gpl_only       = true,
5008         .ret_type       = RET_INTEGER,
5009         .arg1_type      = ARG_PTR_TO_CTX,
5010         .arg2_type      = ARG_CONST_MAP_PTR,
5011         .arg3_type      = ARG_ANYTHING,
5012         .arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
5013         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
5014 };
5015
5016 BTF_ID_LIST_SINGLE(bpf_xdp_output_btf_ids, struct, xdp_buff)
5017
5018 const struct bpf_func_proto bpf_xdp_output_proto = {
5019         .func           = bpf_xdp_event_output,
5020         .gpl_only       = true,
5021         .ret_type       = RET_INTEGER,
5022         .arg1_type      = ARG_PTR_TO_BTF_ID,
5023         .arg1_btf_id    = &bpf_xdp_output_btf_ids[0],
5024         .arg2_type      = ARG_CONST_MAP_PTR,
5025         .arg3_type      = ARG_ANYTHING,
5026         .arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
5027         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
5028 };
5029
5030 BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
5031 {
5032         return skb->sk ? __sock_gen_cookie(skb->sk) : 0;
5033 }
5034
5035 static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
5036         .func           = bpf_get_socket_cookie,
5037         .gpl_only       = false,
5038         .ret_type       = RET_INTEGER,
5039         .arg1_type      = ARG_PTR_TO_CTX,
5040 };
5041
5042 BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
5043 {
5044         return __sock_gen_cookie(ctx->sk);
5045 }
5046
5047 static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
5048         .func           = bpf_get_socket_cookie_sock_addr,
5049         .gpl_only       = false,
5050         .ret_type       = RET_INTEGER,
5051         .arg1_type      = ARG_PTR_TO_CTX,
5052 };
5053
5054 BPF_CALL_1(bpf_get_socket_cookie_sock, struct sock *, ctx)
5055 {
5056         return __sock_gen_cookie(ctx);
5057 }
5058
5059 static const struct bpf_func_proto bpf_get_socket_cookie_sock_proto = {
5060         .func           = bpf_get_socket_cookie_sock,
5061         .gpl_only       = false,
5062         .ret_type       = RET_INTEGER,
5063         .arg1_type      = ARG_PTR_TO_CTX,
5064 };
5065
5066 BPF_CALL_1(bpf_get_socket_ptr_cookie, struct sock *, sk)
5067 {
5068         return sk ? sock_gen_cookie(sk) : 0;
5069 }
5070
5071 const struct bpf_func_proto bpf_get_socket_ptr_cookie_proto = {
5072         .func           = bpf_get_socket_ptr_cookie,
5073         .gpl_only       = false,
5074         .ret_type       = RET_INTEGER,
5075         .arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON | PTR_MAYBE_NULL,
5076 };
5077
5078 BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
5079 {
5080         return __sock_gen_cookie(ctx->sk);
5081 }
5082
5083 static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
5084         .func           = bpf_get_socket_cookie_sock_ops,
5085         .gpl_only       = false,
5086         .ret_type       = RET_INTEGER,
5087         .arg1_type      = ARG_PTR_TO_CTX,
5088 };
5089
5090 static u64 __bpf_get_netns_cookie(struct sock *sk)
5091 {
5092         const struct net *net = sk ? sock_net(sk) : &init_net;
5093
5094         return net->net_cookie;
5095 }
5096
5097 BPF_CALL_1(bpf_get_netns_cookie_sock, struct sock *, ctx)
5098 {
5099         return __bpf_get_netns_cookie(ctx);
5100 }
5101
5102 static const struct bpf_func_proto bpf_get_netns_cookie_sock_proto = {
5103         .func           = bpf_get_netns_cookie_sock,
5104         .gpl_only       = false,
5105         .ret_type       = RET_INTEGER,
5106         .arg1_type      = ARG_PTR_TO_CTX_OR_NULL,
5107 };
5108
5109 BPF_CALL_1(bpf_get_netns_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
5110 {
5111         return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5112 }
5113
5114 static const struct bpf_func_proto bpf_get_netns_cookie_sock_addr_proto = {
5115         .func           = bpf_get_netns_cookie_sock_addr,
5116         .gpl_only       = false,
5117         .ret_type       = RET_INTEGER,
5118         .arg1_type      = ARG_PTR_TO_CTX_OR_NULL,
5119 };
5120
5121 BPF_CALL_1(bpf_get_netns_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
5122 {
5123         return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5124 }
5125
5126 static const struct bpf_func_proto bpf_get_netns_cookie_sock_ops_proto = {
5127         .func           = bpf_get_netns_cookie_sock_ops,
5128         .gpl_only       = false,
5129         .ret_type       = RET_INTEGER,
5130         .arg1_type      = ARG_PTR_TO_CTX_OR_NULL,
5131 };
5132
5133 BPF_CALL_1(bpf_get_netns_cookie_sk_msg, struct sk_msg *, ctx)
5134 {
5135         return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5136 }
5137
5138 static const struct bpf_func_proto bpf_get_netns_cookie_sk_msg_proto = {
5139         .func           = bpf_get_netns_cookie_sk_msg,
5140         .gpl_only       = false,
5141         .ret_type       = RET_INTEGER,
5142         .arg1_type      = ARG_PTR_TO_CTX_OR_NULL,
5143 };
5144
5145 BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
5146 {
5147         struct sock *sk = sk_to_full_sk(skb->sk);
5148         kuid_t kuid;
5149
5150         if (!sk || !sk_fullsock(sk))
5151                 return overflowuid;
5152         kuid = sock_net_uid(sock_net(sk), sk);
5153         return from_kuid_munged(sock_net(sk)->user_ns, kuid);
5154 }
5155
5156 static const struct bpf_func_proto bpf_get_socket_uid_proto = {
5157         .func           = bpf_get_socket_uid,
5158         .gpl_only       = false,
5159         .ret_type       = RET_INTEGER,
5160         .arg1_type      = ARG_PTR_TO_CTX,
5161 };
5162
5163 static int sol_socket_sockopt(struct sock *sk, int optname,
5164                               char *optval, int *optlen,
5165                               bool getopt)
5166 {
5167         switch (optname) {
5168         case SO_REUSEADDR:
5169         case SO_SNDBUF:
5170         case SO_RCVBUF:
5171         case SO_KEEPALIVE:
5172         case SO_PRIORITY:
5173         case SO_REUSEPORT:
5174         case SO_RCVLOWAT:
5175         case SO_MARK:
5176         case SO_MAX_PACING_RATE:
5177         case SO_BINDTOIFINDEX:
5178         case SO_TXREHASH:
5179                 if (*optlen != sizeof(int))
5180                         return -EINVAL;
5181                 break;
5182         case SO_BINDTODEVICE:
5183                 break;
5184         default:
5185                 return -EINVAL;
5186         }
5187
5188         if (getopt) {
5189                 if (optname == SO_BINDTODEVICE)
5190                         return -EINVAL;
5191                 return sk_getsockopt(sk, SOL_SOCKET, optname,
5192                                      KERNEL_SOCKPTR(optval),
5193                                      KERNEL_SOCKPTR(optlen));
5194         }
5195
5196         return sk_setsockopt(sk, SOL_SOCKET, optname,
5197                              KERNEL_SOCKPTR(optval), *optlen);
5198 }
5199
5200 static int bpf_sol_tcp_setsockopt(struct sock *sk, int optname,
5201                                   char *optval, int optlen)
5202 {
5203         struct tcp_sock *tp = tcp_sk(sk);
5204         unsigned long timeout;
5205         int val;
5206
5207         if (optlen != sizeof(int))
5208                 return -EINVAL;
5209
5210         val = *(int *)optval;
5211
5212         /* Only some options are supported */
5213         switch (optname) {
5214         case TCP_BPF_IW:
5215                 if (val <= 0 || tp->data_segs_out > tp->syn_data)
5216                         return -EINVAL;
5217                 tcp_snd_cwnd_set(tp, val);
5218                 break;
5219         case TCP_BPF_SNDCWND_CLAMP:
5220                 if (val <= 0)
5221                         return -EINVAL;
5222                 tp->snd_cwnd_clamp = val;
5223                 tp->snd_ssthresh = val;
5224                 break;
5225         case TCP_BPF_DELACK_MAX:
5226                 timeout = usecs_to_jiffies(val);
5227                 if (timeout > TCP_DELACK_MAX ||
5228                     timeout < TCP_TIMEOUT_MIN)
5229                         return -EINVAL;
5230                 inet_csk(sk)->icsk_delack_max = timeout;
5231                 break;
5232         case TCP_BPF_RTO_MIN:
5233                 timeout = usecs_to_jiffies(val);
5234                 if (timeout > TCP_RTO_MIN ||
5235                     timeout < TCP_TIMEOUT_MIN)
5236                         return -EINVAL;
5237                 inet_csk(sk)->icsk_rto_min = timeout;
5238                 break;
5239         default:
5240                 return -EINVAL;
5241         }
5242
5243         return 0;
5244 }
5245
5246 static int sol_tcp_sockopt_congestion(struct sock *sk, char *optval,
5247                                       int *optlen, bool getopt)
5248 {
5249         struct tcp_sock *tp;
5250         int ret;
5251
5252         if (*optlen < 2)
5253                 return -EINVAL;
5254
5255         if (getopt) {
5256                 if (!inet_csk(sk)->icsk_ca_ops)
5257                         return -EINVAL;
5258                 /* BPF expects NULL-terminated tcp-cc string */
5259                 optval[--(*optlen)] = '\0';
5260                 return do_tcp_getsockopt(sk, SOL_TCP, TCP_CONGESTION,
5261                                          KERNEL_SOCKPTR(optval),
5262                                          KERNEL_SOCKPTR(optlen));
5263         }
5264
5265         /* "cdg" is the only cc that alloc a ptr
5266          * in inet_csk_ca area.  The bpf-tcp-cc may
5267          * overwrite this ptr after switching to cdg.
5268          */
5269         if (*optlen >= sizeof("cdg") - 1 && !strncmp("cdg", optval, *optlen))
5270                 return -ENOTSUPP;
5271
5272         /* It stops this looping
5273          *
5274          * .init => bpf_setsockopt(tcp_cc) => .init =>
5275          * bpf_setsockopt(tcp_cc)" => .init => ....
5276          *
5277          * The second bpf_setsockopt(tcp_cc) is not allowed
5278          * in order to break the loop when both .init
5279          * are the same bpf prog.
5280          *
5281          * This applies even the second bpf_setsockopt(tcp_cc)
5282          * does not cause a loop.  This limits only the first
5283          * '.init' can call bpf_setsockopt(TCP_CONGESTION) to
5284          * pick a fallback cc (eg. peer does not support ECN)
5285          * and the second '.init' cannot fallback to
5286          * another.
5287          */
5288         tp = tcp_sk(sk);
5289         if (tp->bpf_chg_cc_inprogress)
5290                 return -EBUSY;
5291
5292         tp->bpf_chg_cc_inprogress = 1;
5293         ret = do_tcp_setsockopt(sk, SOL_TCP, TCP_CONGESTION,
5294                                 KERNEL_SOCKPTR(optval), *optlen);
5295         tp->bpf_chg_cc_inprogress = 0;
5296         return ret;
5297 }
5298
5299 static int sol_tcp_sockopt(struct sock *sk, int optname,
5300                            char *optval, int *optlen,
5301                            bool getopt)
5302 {
5303         if (sk->sk_protocol != IPPROTO_TCP)
5304                 return -EINVAL;
5305
5306         switch (optname) {
5307         case TCP_NODELAY:
5308         case TCP_MAXSEG:
5309         case TCP_KEEPIDLE:
5310         case TCP_KEEPINTVL:
5311         case TCP_KEEPCNT:
5312         case TCP_SYNCNT:
5313         case TCP_WINDOW_CLAMP:
5314         case TCP_THIN_LINEAR_TIMEOUTS:
5315         case TCP_USER_TIMEOUT:
5316         case TCP_NOTSENT_LOWAT:
5317         case TCP_SAVE_SYN:
5318                 if (*optlen != sizeof(int))
5319                         return -EINVAL;
5320                 break;
5321         case TCP_CONGESTION:
5322                 return sol_tcp_sockopt_congestion(sk, optval, optlen, getopt);
5323         case TCP_SAVED_SYN:
5324                 if (*optlen < 1)
5325                         return -EINVAL;
5326                 break;
5327         default:
5328                 if (getopt)
5329                         return -EINVAL;
5330                 return bpf_sol_tcp_setsockopt(sk, optname, optval, *optlen);
5331         }
5332
5333         if (getopt) {
5334                 if (optname == TCP_SAVED_SYN) {
5335                         struct tcp_sock *tp = tcp_sk(sk);
5336
5337                         if (!tp->saved_syn ||
5338                             *optlen > tcp_saved_syn_len(tp->saved_syn))
5339                                 return -EINVAL;
5340                         memcpy(optval, tp->saved_syn->data, *optlen);
5341                         /* It cannot free tp->saved_syn here because it
5342                          * does not know if the user space still needs it.
5343                          */
5344                         return 0;
5345                 }
5346
5347                 return do_tcp_getsockopt(sk, SOL_TCP, optname,
5348                                          KERNEL_SOCKPTR(optval),
5349                                          KERNEL_SOCKPTR(optlen));
5350         }
5351
5352         return do_tcp_setsockopt(sk, SOL_TCP, optname,
5353                                  KERNEL_SOCKPTR(optval), *optlen);
5354 }
5355
5356 static int sol_ip_sockopt(struct sock *sk, int optname,
5357                           char *optval, int *optlen,
5358                           bool getopt)
5359 {
5360         if (sk->sk_family != AF_INET)
5361                 return -EINVAL;
5362
5363         switch (optname) {
5364         case IP_TOS:
5365                 if (*optlen != sizeof(int))
5366                         return -EINVAL;
5367                 break;
5368         default:
5369                 return -EINVAL;
5370         }
5371
5372         if (getopt)
5373                 return do_ip_getsockopt(sk, SOL_IP, optname,
5374                                         KERNEL_SOCKPTR(optval),
5375                                         KERNEL_SOCKPTR(optlen));
5376
5377         return do_ip_setsockopt(sk, SOL_IP, optname,
5378                                 KERNEL_SOCKPTR(optval), *optlen);
5379 }
5380
5381 static int sol_ipv6_sockopt(struct sock *sk, int optname,
5382                             char *optval, int *optlen,
5383                             bool getopt)
5384 {
5385         if (sk->sk_family != AF_INET6)
5386                 return -EINVAL;
5387
5388         switch (optname) {
5389         case IPV6_TCLASS:
5390         case IPV6_AUTOFLOWLABEL:
5391                 if (*optlen != sizeof(int))
5392                         return -EINVAL;
5393                 break;
5394         default:
5395                 return -EINVAL;
5396         }
5397
5398         if (getopt)
5399                 return ipv6_bpf_stub->ipv6_getsockopt(sk, SOL_IPV6, optname,
5400                                                       KERNEL_SOCKPTR(optval),
5401                                                       KERNEL_SOCKPTR(optlen));
5402
5403         return ipv6_bpf_stub->ipv6_setsockopt(sk, SOL_IPV6, optname,
5404                                               KERNEL_SOCKPTR(optval), *optlen);
5405 }
5406
5407 static int __bpf_setsockopt(struct sock *sk, int level, int optname,
5408                             char *optval, int optlen)
5409 {
5410         if (!sk_fullsock(sk))
5411                 return -EINVAL;
5412
5413         if (level == SOL_SOCKET)
5414                 return sol_socket_sockopt(sk, optname, optval, &optlen, false);
5415         else if (IS_ENABLED(CONFIG_INET) && level == SOL_IP)
5416                 return sol_ip_sockopt(sk, optname, optval, &optlen, false);
5417         else if (IS_ENABLED(CONFIG_IPV6) && level == SOL_IPV6)
5418                 return sol_ipv6_sockopt(sk, optname, optval, &optlen, false);
5419         else if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP)
5420                 return sol_tcp_sockopt(sk, optname, optval, &optlen, false);
5421
5422         return -EINVAL;
5423 }
5424
5425 static int _bpf_setsockopt(struct sock *sk, int level, int optname,
5426                            char *optval, int optlen)
5427 {
5428         if (sk_fullsock(sk))
5429                 sock_owned_by_me(sk);
5430         return __bpf_setsockopt(sk, level, optname, optval, optlen);
5431 }
5432
5433 static int __bpf_getsockopt(struct sock *sk, int level, int optname,
5434                             char *optval, int optlen)
5435 {
5436         int err, saved_optlen = optlen;
5437
5438         if (!sk_fullsock(sk)) {
5439                 err = -EINVAL;
5440                 goto done;
5441         }
5442
5443         if (level == SOL_SOCKET)
5444                 err = sol_socket_sockopt(sk, optname, optval, &optlen, true);
5445         else if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP)
5446                 err = sol_tcp_sockopt(sk, optname, optval, &optlen, true);
5447         else if (IS_ENABLED(CONFIG_INET) && level == SOL_IP)
5448                 err = sol_ip_sockopt(sk, optname, optval, &optlen, true);
5449         else if (IS_ENABLED(CONFIG_IPV6) && level == SOL_IPV6)
5450                 err = sol_ipv6_sockopt(sk, optname, optval, &optlen, true);
5451         else
5452                 err = -EINVAL;
5453
5454 done:
5455         if (err)
5456                 optlen = 0;
5457         if (optlen < saved_optlen)
5458                 memset(optval + optlen, 0, saved_optlen - optlen);
5459         return err;
5460 }
5461
5462 static int _bpf_getsockopt(struct sock *sk, int level, int optname,
5463                            char *optval, int optlen)
5464 {
5465         if (sk_fullsock(sk))
5466                 sock_owned_by_me(sk);
5467         return __bpf_getsockopt(sk, level, optname, optval, optlen);
5468 }
5469
5470 BPF_CALL_5(bpf_sk_setsockopt, struct sock *, sk, int, level,
5471            int, optname, char *, optval, int, optlen)
5472 {
5473         return _bpf_setsockopt(sk, level, optname, optval, optlen);
5474 }
5475
5476 const struct bpf_func_proto bpf_sk_setsockopt_proto = {
5477         .func           = bpf_sk_setsockopt,
5478         .gpl_only       = false,
5479         .ret_type       = RET_INTEGER,
5480         .arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5481         .arg2_type      = ARG_ANYTHING,
5482         .arg3_type      = ARG_ANYTHING,
5483         .arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
5484         .arg5_type      = ARG_CONST_SIZE,
5485 };
5486
5487 BPF_CALL_5(bpf_sk_getsockopt, struct sock *, sk, int, level,
5488            int, optname, char *, optval, int, optlen)
5489 {
5490         return _bpf_getsockopt(sk, level, optname, optval, optlen);
5491 }
5492
5493 const struct bpf_func_proto bpf_sk_getsockopt_proto = {
5494         .func           = bpf_sk_getsockopt,
5495         .gpl_only       = false,
5496         .ret_type       = RET_INTEGER,
5497         .arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5498         .arg2_type      = ARG_ANYTHING,
5499         .arg3_type      = ARG_ANYTHING,
5500         .arg4_type      = ARG_PTR_TO_UNINIT_MEM,
5501         .arg5_type      = ARG_CONST_SIZE,
5502 };
5503
5504 BPF_CALL_5(bpf_unlocked_sk_setsockopt, struct sock *, sk, int, level,
5505            int, optname, char *, optval, int, optlen)
5506 {
5507         return __bpf_setsockopt(sk, level, optname, optval, optlen);
5508 }
5509
5510 const struct bpf_func_proto bpf_unlocked_sk_setsockopt_proto = {
5511         .func           = bpf_unlocked_sk_setsockopt,
5512         .gpl_only       = false,
5513         .ret_type       = RET_INTEGER,
5514         .arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5515         .arg2_type      = ARG_ANYTHING,
5516         .arg3_type      = ARG_ANYTHING,
5517         .arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
5518         .arg5_type      = ARG_CONST_SIZE,
5519 };
5520
5521 BPF_CALL_5(bpf_unlocked_sk_getsockopt, struct sock *, sk, int, level,
5522            int, optname, char *, optval, int, optlen)
5523 {
5524         return __bpf_getsockopt(sk, level, optname, optval, optlen);
5525 }
5526
5527 const struct bpf_func_proto bpf_unlocked_sk_getsockopt_proto = {
5528         .func           = bpf_unlocked_sk_getsockopt,
5529         .gpl_only       = false,
5530         .ret_type       = RET_INTEGER,
5531         .arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5532         .arg2_type      = ARG_ANYTHING,
5533         .arg3_type      = ARG_ANYTHING,
5534         .arg4_type      = ARG_PTR_TO_UNINIT_MEM,
5535         .arg5_type      = ARG_CONST_SIZE,
5536 };
5537
5538 BPF_CALL_5(bpf_sock_addr_setsockopt, struct bpf_sock_addr_kern *, ctx,
5539            int, level, int, optname, char *, optval, int, optlen)
5540 {
5541         return _bpf_setsockopt(ctx->sk, level, optname, optval, optlen);
5542 }
5543
5544 static const struct bpf_func_proto bpf_sock_addr_setsockopt_proto = {
5545         .func           = bpf_sock_addr_setsockopt,
5546         .gpl_only       = false,
5547         .ret_type       = RET_INTEGER,
5548         .arg1_type      = ARG_PTR_TO_CTX,
5549         .arg2_type      = ARG_ANYTHING,
5550         .arg3_type      = ARG_ANYTHING,
5551         .arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
5552         .arg5_type      = ARG_CONST_SIZE,
5553 };
5554
5555 BPF_CALL_5(bpf_sock_addr_getsockopt, struct bpf_sock_addr_kern *, ctx,
5556            int, level, int, optname, char *, optval, int, optlen)
5557 {
5558         return _bpf_getsockopt(ctx->sk, level, optname, optval, optlen);
5559 }
5560
5561 static const struct bpf_func_proto bpf_sock_addr_getsockopt_proto = {
5562         .func           = bpf_sock_addr_getsockopt,
5563         .gpl_only       = false,
5564         .ret_type       = RET_INTEGER,
5565         .arg1_type      = ARG_PTR_TO_CTX,
5566         .arg2_type      = ARG_ANYTHING,
5567         .arg3_type      = ARG_ANYTHING,
5568         .arg4_type      = ARG_PTR_TO_UNINIT_MEM,
5569         .arg5_type      = ARG_CONST_SIZE,
5570 };
5571
5572 BPF_CALL_5(bpf_sock_ops_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
5573            int, level, int, optname, char *, optval, int, optlen)
5574 {
5575         return _bpf_setsockopt(bpf_sock->sk, level, optname, optval, optlen);
5576 }
5577
5578 static const struct bpf_func_proto bpf_sock_ops_setsockopt_proto = {
5579         .func           = bpf_sock_ops_setsockopt,
5580         .gpl_only       = false,
5581         .ret_type       = RET_INTEGER,
5582         .arg1_type      = ARG_PTR_TO_CTX,
5583         .arg2_type      = ARG_ANYTHING,
5584         .arg3_type      = ARG_ANYTHING,
5585         .arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
5586         .arg5_type      = ARG_CONST_SIZE,
5587 };
5588
5589 static int bpf_sock_ops_get_syn(struct bpf_sock_ops_kern *bpf_sock,
5590                                 int optname, const u8 **start)
5591 {
5592         struct sk_buff *syn_skb = bpf_sock->syn_skb;
5593         const u8 *hdr_start;
5594         int ret;
5595
5596         if (syn_skb) {
5597                 /* sk is a request_sock here */
5598
5599                 if (optname == TCP_BPF_SYN) {
5600                         hdr_start = syn_skb->data;
5601                         ret = tcp_hdrlen(syn_skb);
5602                 } else if (optname == TCP_BPF_SYN_IP) {
5603                         hdr_start = skb_network_header(syn_skb);
5604                         ret = skb_network_header_len(syn_skb) +
5605                                 tcp_hdrlen(syn_skb);
5606                 } else {
5607                         /* optname == TCP_BPF_SYN_MAC */
5608                         hdr_start = skb_mac_header(syn_skb);
5609                         ret = skb_mac_header_len(syn_skb) +
5610                                 skb_network_header_len(syn_skb) +
5611                                 tcp_hdrlen(syn_skb);
5612                 }
5613         } else {
5614                 struct sock *sk = bpf_sock->sk;
5615                 struct saved_syn *saved_syn;
5616
5617                 if (sk->sk_state == TCP_NEW_SYN_RECV)
5618                         /* synack retransmit. bpf_sock->syn_skb will
5619                          * not be available.  It has to resort to
5620                          * saved_syn (if it is saved).
5621                          */
5622                         saved_syn = inet_reqsk(sk)->saved_syn;
5623                 else
5624                         saved_syn = tcp_sk(sk)->saved_syn;
5625
5626                 if (!saved_syn)
5627                         return -ENOENT;
5628
5629                 if (optname == TCP_BPF_SYN) {
5630                         hdr_start = saved_syn->data +
5631                                 saved_syn->mac_hdrlen +
5632                                 saved_syn->network_hdrlen;
5633                         ret = saved_syn->tcp_hdrlen;
5634                 } else if (optname == TCP_BPF_SYN_IP) {
5635                         hdr_start = saved_syn->data +
5636                                 saved_syn->mac_hdrlen;
5637                         ret = saved_syn->network_hdrlen +
5638                                 saved_syn->tcp_hdrlen;
5639                 } else {
5640                         /* optname == TCP_BPF_SYN_MAC */
5641
5642                         /* TCP_SAVE_SYN may not have saved the mac hdr */
5643                         if (!saved_syn->mac_hdrlen)
5644                                 return -ENOENT;
5645
5646                         hdr_start = saved_syn->data;
5647                         ret = saved_syn->mac_hdrlen +
5648                                 saved_syn->network_hdrlen +
5649                                 saved_syn->tcp_hdrlen;
5650                 }
5651         }
5652
5653         *start = hdr_start;
5654         return ret;
5655 }
5656
5657 BPF_CALL_5(bpf_sock_ops_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
5658            int, level, int, optname, char *, optval, int, optlen)
5659 {
5660         if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP &&
5661             optname >= TCP_BPF_SYN && optname <= TCP_BPF_SYN_MAC) {
5662                 int ret, copy_len = 0;
5663                 const u8 *start;
5664
5665                 ret = bpf_sock_ops_get_syn(bpf_sock, optname, &start);
5666                 if (ret > 0) {
5667                         copy_len = ret;
5668                         if (optlen < copy_len) {
5669                                 copy_len = optlen;
5670                                 ret = -ENOSPC;
5671                         }
5672
5673                         memcpy(optval, start, copy_len);
5674                 }
5675
5676                 /* Zero out unused buffer at the end */
5677                 memset(optval + copy_len, 0, optlen - copy_len);
5678
5679                 return ret;
5680         }
5681
5682         return _bpf_getsockopt(bpf_sock->sk, level, optname, optval, optlen);
5683 }
5684
5685 static const struct bpf_func_proto bpf_sock_ops_getsockopt_proto = {
5686         .func           = bpf_sock_ops_getsockopt,
5687         .gpl_only       = false,
5688         .ret_type       = RET_INTEGER,
5689         .arg1_type      = ARG_PTR_TO_CTX,
5690         .arg2_type      = ARG_ANYTHING,
5691         .arg3_type      = ARG_ANYTHING,
5692         .arg4_type      = ARG_PTR_TO_UNINIT_MEM,
5693         .arg5_type      = ARG_CONST_SIZE,
5694 };
5695
5696 BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
5697            int, argval)
5698 {
5699         struct sock *sk = bpf_sock->sk;
5700         int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
5701
5702         if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
5703                 return -EINVAL;
5704
5705         tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
5706
5707         return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
5708 }
5709
5710 static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
5711         .func           = bpf_sock_ops_cb_flags_set,
5712         .gpl_only       = false,
5713         .ret_type       = RET_INTEGER,
5714         .arg1_type      = ARG_PTR_TO_CTX,
5715         .arg2_type      = ARG_ANYTHING,
5716 };
5717
5718 const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly;
5719 EXPORT_SYMBOL_GPL(ipv6_bpf_stub);
5720
5721 BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
5722            int, addr_len)
5723 {
5724 #ifdef CONFIG_INET
5725         struct sock *sk = ctx->sk;
5726         u32 flags = BIND_FROM_BPF;
5727         int err;
5728
5729         err = -EINVAL;
5730         if (addr_len < offsetofend(struct sockaddr, sa_family))
5731                 return err;
5732         if (addr->sa_family == AF_INET) {
5733                 if (addr_len < sizeof(struct sockaddr_in))
5734                         return err;
5735                 if (((struct sockaddr_in *)addr)->sin_port == htons(0))
5736                         flags |= BIND_FORCE_ADDRESS_NO_PORT;
5737                 return __inet_bind(sk, addr, addr_len, flags);
5738 #if IS_ENABLED(CONFIG_IPV6)
5739         } else if (addr->sa_family == AF_INET6) {
5740                 if (addr_len < SIN6_LEN_RFC2133)
5741                         return err;
5742                 if (((struct sockaddr_in6 *)addr)->sin6_port == htons(0))
5743                         flags |= BIND_FORCE_ADDRESS_NO_PORT;
5744                 /* ipv6_bpf_stub cannot be NULL, since it's called from
5745                  * bpf_cgroup_inet6_connect hook and ipv6 is already loaded
5746                  */
5747                 return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, flags);
5748 #endif /* CONFIG_IPV6 */
5749         }
5750 #endif /* CONFIG_INET */
5751
5752         return -EAFNOSUPPORT;
5753 }
5754
5755 static const struct bpf_func_proto bpf_bind_proto = {
5756         .func           = bpf_bind,
5757         .gpl_only       = false,
5758         .ret_type       = RET_INTEGER,
5759         .arg1_type      = ARG_PTR_TO_CTX,
5760         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
5761         .arg3_type      = ARG_CONST_SIZE,
5762 };
5763
5764 #ifdef CONFIG_XFRM
5765
5766 #if (IS_BUILTIN(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) || \
5767     (IS_MODULE(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
5768
5769 struct metadata_dst __percpu *xfrm_bpf_md_dst;
5770 EXPORT_SYMBOL_GPL(xfrm_bpf_md_dst);
5771
5772 #endif
5773
5774 BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
5775            struct bpf_xfrm_state *, to, u32, size, u64, flags)
5776 {
5777         const struct sec_path *sp = skb_sec_path(skb);
5778         const struct xfrm_state *x;
5779
5780         if (!sp || unlikely(index >= sp->len || flags))
5781                 goto err_clear;
5782
5783         x = sp->xvec[index];
5784
5785         if (unlikely(size != sizeof(struct bpf_xfrm_state)))
5786                 goto err_clear;
5787
5788         to->reqid = x->props.reqid;
5789         to->spi = x->id.spi;
5790         to->family = x->props.family;
5791         to->ext = 0;
5792
5793         if (to->family == AF_INET6) {
5794                 memcpy(to->remote_ipv6, x->props.saddr.a6,
5795                        sizeof(to->remote_ipv6));
5796         } else {
5797                 to->remote_ipv4 = x->props.saddr.a4;
5798                 memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
5799         }
5800
5801         return 0;
5802 err_clear:
5803         memset(to, 0, size);
5804         return -EINVAL;
5805 }
5806
5807 static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
5808         .func           = bpf_skb_get_xfrm_state,
5809         .gpl_only       = false,
5810         .ret_type       = RET_INTEGER,
5811         .arg1_type      = ARG_PTR_TO_CTX,
5812         .arg2_type      = ARG_ANYTHING,
5813         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
5814         .arg4_type      = ARG_CONST_SIZE,
5815         .arg5_type      = ARG_ANYTHING,
5816 };
5817 #endif
5818
5819 #if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
5820 static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params, u32 mtu)
5821 {
5822         params->h_vlan_TCI = 0;
5823         params->h_vlan_proto = 0;
5824         if (mtu)
5825                 params->mtu_result = mtu; /* union with tot_len */
5826
5827         return 0;
5828 }
5829 #endif
5830
5831 #if IS_ENABLED(CONFIG_INET)
5832 static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
5833                                u32 flags, bool check_mtu)
5834 {
5835         struct fib_nh_common *nhc;
5836         struct in_device *in_dev;
5837         struct neighbour *neigh;
5838         struct net_device *dev;
5839         struct fib_result res;
5840         struct flowi4 fl4;
5841         u32 mtu = 0;
5842         int err;
5843
5844         dev = dev_get_by_index_rcu(net, params->ifindex);
5845         if (unlikely(!dev))
5846                 return -ENODEV;
5847
5848         /* verify forwarding is enabled on this interface */
5849         in_dev = __in_dev_get_rcu(dev);
5850         if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
5851                 return BPF_FIB_LKUP_RET_FWD_DISABLED;
5852
5853         if (flags & BPF_FIB_LOOKUP_OUTPUT) {
5854                 fl4.flowi4_iif = 1;
5855                 fl4.flowi4_oif = params->ifindex;
5856         } else {
5857                 fl4.flowi4_iif = params->ifindex;
5858                 fl4.flowi4_oif = 0;
5859         }
5860         fl4.flowi4_tos = params->tos & IPTOS_RT_MASK;
5861         fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
5862         fl4.flowi4_flags = 0;
5863
5864         fl4.flowi4_proto = params->l4_protocol;
5865         fl4.daddr = params->ipv4_dst;
5866         fl4.saddr = params->ipv4_src;
5867         fl4.fl4_sport = params->sport;
5868         fl4.fl4_dport = params->dport;
5869         fl4.flowi4_multipath_hash = 0;
5870
5871         if (flags & BPF_FIB_LOOKUP_DIRECT) {
5872                 u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
5873                 struct fib_table *tb;
5874
5875                 if (flags & BPF_FIB_LOOKUP_TBID) {
5876                         tbid = params->tbid;
5877                         /* zero out for vlan output */
5878                         params->tbid = 0;
5879                 }
5880
5881                 tb = fib_get_table(net, tbid);
5882                 if (unlikely(!tb))
5883                         return BPF_FIB_LKUP_RET_NOT_FWDED;
5884
5885                 err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
5886         } else {
5887                 fl4.flowi4_mark = 0;
5888                 fl4.flowi4_secid = 0;
5889                 fl4.flowi4_tun_key.tun_id = 0;
5890                 fl4.flowi4_uid = sock_net_uid(net, NULL);
5891
5892                 err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
5893         }
5894
5895         if (err) {
5896                 /* map fib lookup errors to RTN_ type */
5897                 if (err == -EINVAL)
5898                         return BPF_FIB_LKUP_RET_BLACKHOLE;
5899                 if (err == -EHOSTUNREACH)
5900                         return BPF_FIB_LKUP_RET_UNREACHABLE;
5901                 if (err == -EACCES)
5902                         return BPF_FIB_LKUP_RET_PROHIBIT;
5903
5904                 return BPF_FIB_LKUP_RET_NOT_FWDED;
5905         }
5906
5907         if (res.type != RTN_UNICAST)
5908                 return BPF_FIB_LKUP_RET_NOT_FWDED;
5909
5910         if (fib_info_num_path(res.fi) > 1)
5911                 fib_select_path(net, &res, &fl4, NULL);
5912
5913         if (check_mtu) {
5914                 mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
5915                 if (params->tot_len > mtu) {
5916                         params->mtu_result = mtu; /* union with tot_len */
5917                         return BPF_FIB_LKUP_RET_FRAG_NEEDED;
5918                 }
5919         }
5920
5921         nhc = res.nhc;
5922
5923         /* do not handle lwt encaps right now */
5924         if (nhc->nhc_lwtstate)
5925                 return BPF_FIB_LKUP_RET_UNSUPP_LWT;
5926
5927         dev = nhc->nhc_dev;
5928
5929         params->rt_metric = res.fi->fib_priority;
5930         params->ifindex = dev->ifindex;
5931
5932         if (flags & BPF_FIB_LOOKUP_SRC)
5933                 params->ipv4_src = fib_result_prefsrc(net, &res);
5934
5935         /* xdp and cls_bpf programs are run in RCU-bh so
5936          * rcu_read_lock_bh is not needed here
5937          */
5938         if (likely(nhc->nhc_gw_family != AF_INET6)) {
5939                 if (nhc->nhc_gw_family)
5940                         params->ipv4_dst = nhc->nhc_gw.ipv4;
5941         } else {
5942                 struct in6_addr *dst = (struct in6_addr *)params->ipv6_dst;
5943
5944                 params->family = AF_INET6;
5945                 *dst = nhc->nhc_gw.ipv6;
5946         }
5947
5948         if (flags & BPF_FIB_LOOKUP_SKIP_NEIGH)
5949                 goto set_fwd_params;
5950
5951         if (likely(nhc->nhc_gw_family != AF_INET6))
5952                 neigh = __ipv4_neigh_lookup_noref(dev,
5953                                                   (__force u32)params->ipv4_dst);
5954         else
5955                 neigh = __ipv6_neigh_lookup_noref_stub(dev, params->ipv6_dst);
5956
5957         if (!neigh || !(READ_ONCE(neigh->nud_state) & NUD_VALID))
5958                 return BPF_FIB_LKUP_RET_NO_NEIGH;
5959         memcpy(params->dmac, neigh->ha, ETH_ALEN);
5960         memcpy(params->smac, dev->dev_addr, ETH_ALEN);
5961
5962 set_fwd_params:
5963         return bpf_fib_set_fwd_params(params, mtu);
5964 }
5965 #endif
5966
5967 #if IS_ENABLED(CONFIG_IPV6)
5968 static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
5969                                u32 flags, bool check_mtu)
5970 {
5971         struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
5972         struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
5973         struct fib6_result res = {};
5974         struct neighbour *neigh;
5975         struct net_device *dev;
5976         struct inet6_dev *idev;
5977         struct flowi6 fl6;
5978         int strict = 0;
5979         int oif, err;
5980         u32 mtu = 0;
5981
5982         /* link local addresses are never forwarded */
5983         if (rt6_need_strict(dst) || rt6_need_strict(src))
5984                 return BPF_FIB_LKUP_RET_NOT_FWDED;
5985
5986         dev = dev_get_by_index_rcu(net, params->ifindex);
5987         if (unlikely(!dev))
5988                 return -ENODEV;
5989
5990         idev = __in6_dev_get_safely(dev);
5991         if (unlikely(!idev || !idev->cnf.forwarding))
5992                 return BPF_FIB_LKUP_RET_FWD_DISABLED;
5993
5994         if (flags & BPF_FIB_LOOKUP_OUTPUT) {
5995                 fl6.flowi6_iif = 1;
5996                 oif = fl6.flowi6_oif = params->ifindex;
5997         } else {
5998                 oif = fl6.flowi6_iif = params->ifindex;
5999                 fl6.flowi6_oif = 0;
6000                 strict = RT6_LOOKUP_F_HAS_SADDR;
6001         }
6002         fl6.flowlabel = params->flowinfo;
6003         fl6.flowi6_scope = 0;
6004         fl6.flowi6_flags = 0;
6005         fl6.mp_hash = 0;
6006
6007         fl6.flowi6_proto = params->l4_protocol;
6008         fl6.daddr = *dst;
6009         fl6.saddr = *src;
6010         fl6.fl6_sport = params->sport;
6011         fl6.fl6_dport = params->dport;
6012
6013         if (flags & BPF_FIB_LOOKUP_DIRECT) {
6014                 u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
6015                 struct fib6_table *tb;
6016
6017                 if (flags & BPF_FIB_LOOKUP_TBID) {
6018                         tbid = params->tbid;
6019                         /* zero out for vlan output */
6020                         params->tbid = 0;
6021                 }
6022
6023                 tb = ipv6_stub->fib6_get_table(net, tbid);
6024                 if (unlikely(!tb))
6025                         return BPF_FIB_LKUP_RET_NOT_FWDED;
6026
6027                 err = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, &res,
6028                                                    strict);
6029         } else {
6030                 fl6.flowi6_mark = 0;
6031                 fl6.flowi6_secid = 0;
6032                 fl6.flowi6_tun_key.tun_id = 0;
6033                 fl6.flowi6_uid = sock_net_uid(net, NULL);
6034
6035                 err = ipv6_stub->fib6_lookup(net, oif, &fl6, &res, strict);
6036         }
6037
6038         if (unlikely(err || IS_ERR_OR_NULL(res.f6i) ||
6039                      res.f6i == net->ipv6.fib6_null_entry))
6040                 return BPF_FIB_LKUP_RET_NOT_FWDED;
6041
6042         switch (res.fib6_type) {
6043         /* only unicast is forwarded */
6044         case RTN_UNICAST:
6045                 break;
6046         case RTN_BLACKHOLE:
6047                 return BPF_FIB_LKUP_RET_BLACKHOLE;
6048         case RTN_UNREACHABLE:
6049                 return BPF_FIB_LKUP_RET_UNREACHABLE;
6050         case RTN_PROHIBIT:
6051                 return BPF_FIB_LKUP_RET_PROHIBIT;
6052         default:
6053                 return BPF_FIB_LKUP_RET_NOT_FWDED;
6054         }
6055
6056         ipv6_stub->fib6_select_path(net, &res, &fl6, fl6.flowi6_oif,
6057                                     fl6.flowi6_oif != 0, NULL, strict);
6058
6059         if (check_mtu) {
6060                 mtu = ipv6_stub->ip6_mtu_from_fib6(&res, dst, src);
6061                 if (params->tot_len > mtu) {
6062                         params->mtu_result = mtu; /* union with tot_len */
6063                         return BPF_FIB_LKUP_RET_FRAG_NEEDED;
6064                 }
6065         }
6066
6067         if (res.nh->fib_nh_lws)
6068                 return BPF_FIB_LKUP_RET_UNSUPP_LWT;
6069
6070         if (res.nh->fib_nh_gw_family)
6071                 *dst = res.nh->fib_nh_gw6;
6072
6073         dev = res.nh->fib_nh_dev;
6074         params->rt_metric = res.f6i->fib6_metric;
6075         params->ifindex = dev->ifindex;
6076
6077         if (flags & BPF_FIB_LOOKUP_SRC) {
6078                 if (res.f6i->fib6_prefsrc.plen) {
6079                         *src = res.f6i->fib6_prefsrc.addr;
6080                 } else {
6081                         err = ipv6_bpf_stub->ipv6_dev_get_saddr(net, dev,
6082                                                                 &fl6.daddr, 0,
6083                                                                 src);
6084                         if (err)
6085                                 return BPF_FIB_LKUP_RET_NO_SRC_ADDR;
6086                 }
6087         }
6088
6089         if (flags & BPF_FIB_LOOKUP_SKIP_NEIGH)
6090                 goto set_fwd_params;
6091
6092         /* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
6093          * not needed here.
6094          */
6095         neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
6096         if (!neigh || !(READ_ONCE(neigh->nud_state) & NUD_VALID))
6097                 return BPF_FIB_LKUP_RET_NO_NEIGH;
6098         memcpy(params->dmac, neigh->ha, ETH_ALEN);
6099         memcpy(params->smac, dev->dev_addr, ETH_ALEN);
6100
6101 set_fwd_params:
6102         return bpf_fib_set_fwd_params(params, mtu);
6103 }
6104 #endif
6105
6106 #define BPF_FIB_LOOKUP_MASK (BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT | \
6107                              BPF_FIB_LOOKUP_SKIP_NEIGH | BPF_FIB_LOOKUP_TBID | \
6108                              BPF_FIB_LOOKUP_SRC)
6109
6110 BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
6111            struct bpf_fib_lookup *, params, int, plen, u32, flags)
6112 {
6113         if (plen < sizeof(*params))
6114                 return -EINVAL;
6115
6116         if (flags & ~BPF_FIB_LOOKUP_MASK)
6117                 return -EINVAL;
6118
6119         switch (params->family) {
6120 #if IS_ENABLED(CONFIG_INET)
6121         case AF_INET:
6122                 return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
6123                                            flags, true);
6124 #endif
6125 #if IS_ENABLED(CONFIG_IPV6)
6126         case AF_INET6:
6127                 return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
6128                                            flags, true);
6129 #endif
6130         }
6131         return -EAFNOSUPPORT;
6132 }
6133
6134 static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
6135         .func           = bpf_xdp_fib_lookup,
6136         .gpl_only       = true,
6137         .ret_type       = RET_INTEGER,
6138         .arg1_type      = ARG_PTR_TO_CTX,
6139         .arg2_type      = ARG_PTR_TO_MEM,
6140         .arg3_type      = ARG_CONST_SIZE,
6141         .arg4_type      = ARG_ANYTHING,
6142 };
6143
6144 BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
6145            struct bpf_fib_lookup *, params, int, plen, u32, flags)
6146 {
6147         struct net *net = dev_net(skb->dev);
6148         int rc = -EAFNOSUPPORT;
6149         bool check_mtu = false;
6150
6151         if (plen < sizeof(*params))
6152                 return -EINVAL;
6153
6154         if (flags & ~BPF_FIB_LOOKUP_MASK)
6155                 return -EINVAL;
6156
6157         if (params->tot_len)
6158                 check_mtu = true;
6159
6160         switch (params->family) {
6161 #if IS_ENABLED(CONFIG_INET)
6162         case AF_INET:
6163                 rc = bpf_ipv4_fib_lookup(net, params, flags, check_mtu);
6164                 break;
6165 #endif
6166 #if IS_ENABLED(CONFIG_IPV6)
6167         case AF_INET6:
6168                 rc = bpf_ipv6_fib_lookup(net, params, flags, check_mtu);
6169                 break;
6170 #endif
6171         }
6172
6173         if (rc == BPF_FIB_LKUP_RET_SUCCESS && !check_mtu) {
6174                 struct net_device *dev;
6175
6176                 /* When tot_len isn't provided by user, check skb
6177                  * against MTU of FIB lookup resulting net_device
6178                  */
6179                 dev = dev_get_by_index_rcu(net, params->ifindex);
6180                 if (!is_skb_forwardable(dev, skb))
6181                         rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
6182
6183                 params->mtu_result = dev->mtu; /* union with tot_len */
6184         }
6185
6186         return rc;
6187 }
6188
6189 static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
6190         .func           = bpf_skb_fib_lookup,
6191         .gpl_only       = true,
6192         .ret_type       = RET_INTEGER,
6193         .arg1_type      = ARG_PTR_TO_CTX,
6194         .arg2_type      = ARG_PTR_TO_MEM,
6195         .arg3_type      = ARG_CONST_SIZE,
6196         .arg4_type      = ARG_ANYTHING,
6197 };
6198
6199 static struct net_device *__dev_via_ifindex(struct net_device *dev_curr,
6200                                             u32 ifindex)
6201 {
6202         struct net *netns = dev_net(dev_curr);
6203
6204         /* Non-redirect use-cases can use ifindex=0 and save ifindex lookup */
6205         if (ifindex == 0)
6206                 return dev_curr;
6207
6208         return dev_get_by_index_rcu(netns, ifindex);
6209 }
6210
6211 BPF_CALL_5(bpf_skb_check_mtu, struct sk_buff *, skb,
6212            u32, ifindex, u32 *, mtu_len, s32, len_diff, u64, flags)
6213 {
6214         int ret = BPF_MTU_CHK_RET_FRAG_NEEDED;
6215         struct net_device *dev = skb->dev;
6216         int skb_len, dev_len;
6217         int mtu;
6218
6219         if (unlikely(flags & ~(BPF_MTU_CHK_SEGS)))
6220                 return -EINVAL;
6221
6222         if (unlikely(flags & BPF_MTU_CHK_SEGS && (len_diff || *mtu_len)))
6223                 return -EINVAL;
6224
6225         dev = __dev_via_ifindex(dev, ifindex);
6226         if (unlikely(!dev))
6227                 return -ENODEV;
6228
6229         mtu = READ_ONCE(dev->mtu);
6230
6231         dev_len = mtu + dev->hard_header_len;
6232
6233         /* If set use *mtu_len as input, L3 as iph->tot_len (like fib_lookup) */
6234         skb_len = *mtu_len ? *mtu_len + dev->hard_header_len : skb->len;
6235
6236         skb_len += len_diff; /* minus result pass check */
6237         if (skb_len <= dev_len) {
6238                 ret = BPF_MTU_CHK_RET_SUCCESS;
6239                 goto out;
6240         }
6241         /* At this point, skb->len exceed MTU, but as it include length of all
6242          * segments, it can still be below MTU.  The SKB can possibly get
6243          * re-segmented in transmit path (see validate_xmit_skb).  Thus, user
6244          * must choose if segs are to be MTU checked.
6245          */
6246         if (skb_is_gso(skb)) {
6247                 ret = BPF_MTU_CHK_RET_SUCCESS;
6248
6249                 if (flags & BPF_MTU_CHK_SEGS &&
6250                     !skb_gso_validate_network_len(skb, mtu))
6251                         ret = BPF_MTU_CHK_RET_SEGS_TOOBIG;
6252         }
6253 out:
6254         /* BPF verifier guarantees valid pointer */
6255         *mtu_len = mtu;
6256
6257         return ret;
6258 }
6259
6260 BPF_CALL_5(bpf_xdp_check_mtu, struct xdp_buff *, xdp,
6261            u32, ifindex, u32 *, mtu_len, s32, len_diff, u64, flags)
6262 {
6263         struct net_device *dev = xdp->rxq->dev;
6264         int xdp_len = xdp->data_end - xdp->data;
6265         int ret = BPF_MTU_CHK_RET_SUCCESS;
6266         int mtu, dev_len;
6267
6268         /* XDP variant doesn't support multi-buffer segment check (yet) */
6269         if (unlikely(flags))
6270                 return -EINVAL;
6271
6272         dev = __dev_via_ifindex(dev, ifindex);
6273         if (unlikely(!dev))
6274                 return -ENODEV;
6275
6276         mtu = READ_ONCE(dev->mtu);
6277
6278         /* Add L2-header as dev MTU is L3 size */
6279         dev_len = mtu + dev->hard_header_len;
6280
6281         /* Use *mtu_len as input, L3 as iph->tot_len (like fib_lookup) */
6282         if (*mtu_len)
6283                 xdp_len = *mtu_len + dev->hard_header_len;
6284
6285         xdp_len += len_diff; /* minus result pass check */
6286         if (xdp_len > dev_len)
6287                 ret = BPF_MTU_CHK_RET_FRAG_NEEDED;
6288
6289         /* BPF verifier guarantees valid pointer */
6290         *mtu_len = mtu;
6291
6292         return ret;
6293 }
6294
6295 static const struct bpf_func_proto bpf_skb_check_mtu_proto = {
6296         .func           = bpf_skb_check_mtu,
6297         .gpl_only       = true,
6298         .ret_type       = RET_INTEGER,
6299         .arg1_type      = ARG_PTR_TO_CTX,
6300         .arg2_type      = ARG_ANYTHING,
6301         .arg3_type      = ARG_PTR_TO_INT,
6302         .arg4_type      = ARG_ANYTHING,
6303         .arg5_type      = ARG_ANYTHING,
6304 };
6305
6306 static const struct bpf_func_proto bpf_xdp_check_mtu_proto = {
6307         .func           = bpf_xdp_check_mtu,
6308         .gpl_only       = true,
6309         .ret_type       = RET_INTEGER,
6310         .arg1_type      = ARG_PTR_TO_CTX,
6311         .arg2_type      = ARG_ANYTHING,
6312         .arg3_type      = ARG_PTR_TO_INT,
6313         .arg4_type      = ARG_ANYTHING,
6314         .arg5_type      = ARG_ANYTHING,
6315 };
6316
6317 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6318 static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
6319 {
6320         int err;
6321         struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;
6322
6323         if (!seg6_validate_srh(srh, len, false))
6324                 return -EINVAL;
6325
6326         switch (type) {
6327         case BPF_LWT_ENCAP_SEG6_INLINE:
6328                 if (skb->protocol != htons(ETH_P_IPV6))
6329                         return -EBADMSG;
6330
6331                 err = seg6_do_srh_inline(skb, srh);
6332                 break;
6333         case BPF_LWT_ENCAP_SEG6:
6334                 skb_reset_inner_headers(skb);
6335                 skb->encapsulation = 1;
6336                 err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
6337                 break;
6338         default:
6339                 return -EINVAL;
6340         }
6341
6342         bpf_compute_data_pointers(skb);
6343         if (err)
6344                 return err;
6345
6346         skb_set_transport_header(skb, sizeof(struct ipv6hdr));
6347
6348         return seg6_lookup_nexthop(skb, NULL, 0);
6349 }
6350 #endif /* CONFIG_IPV6_SEG6_BPF */
6351
6352 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
6353 static int bpf_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len,
6354                              bool ingress)
6355 {
6356         return bpf_lwt_push_ip_encap(skb, hdr, len, ingress);
6357 }
6358 #endif
6359
6360 BPF_CALL_4(bpf_lwt_in_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
6361            u32, len)
6362 {
6363         switch (type) {
6364 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6365         case BPF_LWT_ENCAP_SEG6:
6366         case BPF_LWT_ENCAP_SEG6_INLINE:
6367                 return bpf_push_seg6_encap(skb, type, hdr, len);
6368 #endif
6369 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
6370         case BPF_LWT_ENCAP_IP:
6371                 return bpf_push_ip_encap(skb, hdr, len, true /* ingress */);
6372 #endif
6373         default:
6374                 return -EINVAL;
6375         }
6376 }
6377
6378 BPF_CALL_4(bpf_lwt_xmit_push_encap, struct sk_buff *, skb, u32, type,
6379            void *, hdr, u32, len)
6380 {
6381         switch (type) {
6382 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
6383         case BPF_LWT_ENCAP_IP:
6384                 return bpf_push_ip_encap(skb, hdr, len, false /* egress */);
6385 #endif
6386         default:
6387                 return -EINVAL;
6388         }
6389 }
6390
6391 static const struct bpf_func_proto bpf_lwt_in_push_encap_proto = {
6392         .func           = bpf_lwt_in_push_encap,
6393         .gpl_only       = false,
6394         .ret_type       = RET_INTEGER,
6395         .arg1_type      = ARG_PTR_TO_CTX,
6396         .arg2_type      = ARG_ANYTHING,
6397         .arg3_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6398         .arg4_type      = ARG_CONST_SIZE
6399 };
6400
6401 static const struct bpf_func_proto bpf_lwt_xmit_push_encap_proto = {
6402         .func           = bpf_lwt_xmit_push_encap,
6403         .gpl_only       = false,
6404         .ret_type       = RET_INTEGER,
6405         .arg1_type      = ARG_PTR_TO_CTX,
6406         .arg2_type      = ARG_ANYTHING,
6407         .arg3_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6408         .arg4_type      = ARG_CONST_SIZE
6409 };
6410
6411 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6412 BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
6413            const void *, from, u32, len)
6414 {
6415         struct seg6_bpf_srh_state *srh_state =
6416                 this_cpu_ptr(&seg6_bpf_srh_states);
6417         struct ipv6_sr_hdr *srh = srh_state->srh;
6418         void *srh_tlvs, *srh_end, *ptr;
6419         int srhoff = 0;
6420
6421         if (srh == NULL)
6422                 return -EINVAL;
6423
6424         srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
6425         srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
6426
6427         ptr = skb->data + offset;
6428         if (ptr >= srh_tlvs && ptr + len <= srh_end)
6429                 srh_state->valid = false;
6430         else if (ptr < (void *)&srh->flags ||
6431                  ptr + len > (void *)&srh->segments)
6432                 return -EFAULT;
6433
6434         if (unlikely(bpf_try_make_writable(skb, offset + len)))
6435                 return -EFAULT;
6436         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
6437                 return -EINVAL;
6438         srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
6439
6440         memcpy(skb->data + offset, from, len);
6441         return 0;
6442 }
6443
6444 static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
6445         .func           = bpf_lwt_seg6_store_bytes,
6446         .gpl_only       = false,
6447         .ret_type       = RET_INTEGER,
6448         .arg1_type      = ARG_PTR_TO_CTX,
6449         .arg2_type      = ARG_ANYTHING,
6450         .arg3_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6451         .arg4_type      = ARG_CONST_SIZE
6452 };
6453
6454 static void bpf_update_srh_state(struct sk_buff *skb)
6455 {
6456         struct seg6_bpf_srh_state *srh_state =
6457                 this_cpu_ptr(&seg6_bpf_srh_states);
6458         int srhoff = 0;
6459
6460         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) {
6461                 srh_state->srh = NULL;
6462         } else {
6463                 srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
6464                 srh_state->hdrlen = srh_state->srh->hdrlen << 3;
6465                 srh_state->valid = true;
6466         }
6467 }
6468
6469 BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
6470            u32, action, void *, param, u32, param_len)
6471 {
6472         struct seg6_bpf_srh_state *srh_state =
6473                 this_cpu_ptr(&seg6_bpf_srh_states);
6474         int hdroff = 0;
6475         int err;
6476
6477         switch (action) {
6478         case SEG6_LOCAL_ACTION_END_X:
6479                 if (!seg6_bpf_has_valid_srh(skb))
6480                         return -EBADMSG;
6481                 if (param_len != sizeof(struct in6_addr))
6482                         return -EINVAL;
6483                 return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
6484         case SEG6_LOCAL_ACTION_END_T:
6485                 if (!seg6_bpf_has_valid_srh(skb))
6486                         return -EBADMSG;
6487                 if (param_len != sizeof(int))
6488                         return -EINVAL;
6489                 return seg6_lookup_nexthop(skb, NULL, *(int *)param);
6490         case SEG6_LOCAL_ACTION_END_DT6:
6491                 if (!seg6_bpf_has_valid_srh(skb))
6492                         return -EBADMSG;
6493                 if (param_len != sizeof(int))
6494                         return -EINVAL;
6495
6496                 if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
6497                         return -EBADMSG;
6498                 if (!pskb_pull(skb, hdroff))
6499                         return -EBADMSG;
6500
6501                 skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
6502                 skb_reset_network_header(skb);
6503                 skb_reset_transport_header(skb);
6504                 skb->encapsulation = 0;
6505
6506                 bpf_compute_data_pointers(skb);
6507                 bpf_update_srh_state(skb);
6508                 return seg6_lookup_nexthop(skb, NULL, *(int *)param);
6509         case SEG6_LOCAL_ACTION_END_B6:
6510                 if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
6511                         return -EBADMSG;
6512                 err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
6513                                           param, param_len);
6514                 if (!err)
6515                         bpf_update_srh_state(skb);
6516
6517                 return err;
6518         case SEG6_LOCAL_ACTION_END_B6_ENCAP:
6519                 if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
6520                         return -EBADMSG;
6521                 err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
6522                                           param, param_len);
6523                 if (!err)
6524                         bpf_update_srh_state(skb);
6525
6526                 return err;
6527         default:
6528                 return -EINVAL;
6529         }
6530 }
6531
6532 static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
6533         .func           = bpf_lwt_seg6_action,
6534         .gpl_only       = false,
6535         .ret_type       = RET_INTEGER,
6536         .arg1_type      = ARG_PTR_TO_CTX,
6537         .arg2_type      = ARG_ANYTHING,
6538         .arg3_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6539         .arg4_type      = ARG_CONST_SIZE
6540 };
6541
6542 BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
6543            s32, len)
6544 {
6545         struct seg6_bpf_srh_state *srh_state =
6546                 this_cpu_ptr(&seg6_bpf_srh_states);
6547         struct ipv6_sr_hdr *srh = srh_state->srh;
6548         void *srh_end, *srh_tlvs, *ptr;
6549         struct ipv6hdr *hdr;
6550         int srhoff = 0;
6551         int ret;
6552
6553         if (unlikely(srh == NULL))
6554                 return -EINVAL;
6555
6556         srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
6557                         ((srh->first_segment + 1) << 4));
6558         srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
6559                         srh_state->hdrlen);
6560         ptr = skb->data + offset;
6561
6562         if (unlikely(ptr < srh_tlvs || ptr > srh_end))
6563                 return -EFAULT;
6564         if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
6565                 return -EFAULT;
6566
6567         if (len > 0) {
6568                 ret = skb_cow_head(skb, len);
6569                 if (unlikely(ret < 0))
6570                         return ret;
6571
6572                 ret = bpf_skb_net_hdr_push(skb, offset, len);
6573         } else {
6574                 ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
6575         }
6576
6577         bpf_compute_data_pointers(skb);
6578         if (unlikely(ret < 0))
6579                 return ret;
6580
6581         hdr = (struct ipv6hdr *)skb->data;
6582         hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
6583
6584         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
6585                 return -EINVAL;
6586         srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
6587         srh_state->hdrlen += len;
6588         srh_state->valid = false;
6589         return 0;
6590 }
6591
6592 static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
6593         .func           = bpf_lwt_seg6_adjust_srh,
6594         .gpl_only       = false,
6595         .ret_type       = RET_INTEGER,
6596         .arg1_type      = ARG_PTR_TO_CTX,
6597         .arg2_type      = ARG_ANYTHING,
6598         .arg3_type      = ARG_ANYTHING,
6599 };
6600 #endif /* CONFIG_IPV6_SEG6_BPF */
6601
6602 #ifdef CONFIG_INET
6603 static struct sock *sk_lookup(struct net *net, struct bpf_sock_tuple *tuple,
6604                               int dif, int sdif, u8 family, u8 proto)
6605 {
6606         struct inet_hashinfo *hinfo = net->ipv4.tcp_death_row.hashinfo;
6607         bool refcounted = false;
6608         struct sock *sk = NULL;
6609
6610         if (family == AF_INET) {
6611                 __be32 src4 = tuple->ipv4.saddr;
6612                 __be32 dst4 = tuple->ipv4.daddr;
6613
6614                 if (proto == IPPROTO_TCP)
6615                         sk = __inet_lookup(net, hinfo, NULL, 0,
6616                                            src4, tuple->ipv4.sport,
6617                                            dst4, tuple->ipv4.dport,
6618                                            dif, sdif, &refcounted);
6619                 else
6620                         sk = __udp4_lib_lookup(net, src4, tuple->ipv4.sport,
6621                                                dst4, tuple->ipv4.dport,
6622                                                dif, sdif, net->ipv4.udp_table, NULL);
6623 #if IS_ENABLED(CONFIG_IPV6)
6624         } else {
6625                 struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr;
6626                 struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr;
6627
6628                 if (proto == IPPROTO_TCP)
6629                         sk = __inet6_lookup(net, hinfo, NULL, 0,
6630                                             src6, tuple->ipv6.sport,
6631                                             dst6, ntohs(tuple->ipv6.dport),
6632                                             dif, sdif, &refcounted);
6633                 else if (likely(ipv6_bpf_stub))
6634                         sk = ipv6_bpf_stub->udp6_lib_lookup(net,
6635                                                             src6, tuple->ipv6.sport,
6636                                                             dst6, tuple->ipv6.dport,
6637                                                             dif, sdif,
6638                                                             net->ipv4.udp_table, NULL);
6639 #endif
6640         }
6641
6642         if (unlikely(sk && !refcounted && !sock_flag(sk, SOCK_RCU_FREE))) {
6643                 WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
6644                 sk = NULL;
6645         }
6646         return sk;
6647 }
6648
6649 /* bpf_skc_lookup performs the core lookup for different types of sockets,
6650  * taking a reference on the socket if it doesn't have the flag SOCK_RCU_FREE.
6651  */
6652 static struct sock *
6653 __bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6654                  struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
6655                  u64 flags, int sdif)
6656 {
6657         struct sock *sk = NULL;
6658         struct net *net;
6659         u8 family;
6660
6661         if (len == sizeof(tuple->ipv4))
6662                 family = AF_INET;
6663         else if (len == sizeof(tuple->ipv6))
6664                 family = AF_INET6;
6665         else
6666                 return NULL;
6667
6668         if (unlikely(flags || !((s32)netns_id < 0 || netns_id <= S32_MAX)))
6669                 goto out;
6670
6671         if (sdif < 0) {
6672                 if (family == AF_INET)
6673                         sdif = inet_sdif(skb);
6674                 else
6675                         sdif = inet6_sdif(skb);
6676         }
6677
6678         if ((s32)netns_id < 0) {
6679                 net = caller_net;
6680                 sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
6681         } else {
6682                 net = get_net_ns_by_id(caller_net, netns_id);
6683                 if (unlikely(!net))
6684                         goto out;
6685                 sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
6686                 put_net(net);
6687         }
6688
6689 out:
6690         return sk;
6691 }
6692
6693 static struct sock *
6694 __bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6695                 struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
6696                 u64 flags, int sdif)
6697 {
6698         struct sock *sk = __bpf_skc_lookup(skb, tuple, len, caller_net,
6699                                            ifindex, proto, netns_id, flags,
6700                                            sdif);
6701
6702         if (sk) {
6703                 struct sock *sk2 = sk_to_full_sk(sk);
6704
6705                 /* sk_to_full_sk() may return (sk)->rsk_listener, so make sure the original sk
6706                  * sock refcnt is decremented to prevent a request_sock leak.
6707                  */
6708                 if (!sk_fullsock(sk2))
6709                         sk2 = NULL;
6710                 if (sk2 != sk) {
6711                         sock_gen_put(sk);
6712                         /* Ensure there is no need to bump sk2 refcnt */
6713                         if (unlikely(sk2 && !sock_flag(sk2, SOCK_RCU_FREE))) {
6714                                 WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
6715                                 return NULL;
6716                         }
6717                         sk = sk2;
6718                 }
6719         }
6720
6721         return sk;
6722 }
6723
6724 static struct sock *
6725 bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6726                u8 proto, u64 netns_id, u64 flags)
6727 {
6728         struct net *caller_net;
6729         int ifindex;
6730
6731         if (skb->dev) {
6732                 caller_net = dev_net(skb->dev);
6733                 ifindex = skb->dev->ifindex;
6734         } else {
6735                 caller_net = sock_net(skb->sk);
6736                 ifindex = 0;
6737         }
6738
6739         return __bpf_skc_lookup(skb, tuple, len, caller_net, ifindex, proto,
6740                                 netns_id, flags, -1);
6741 }
6742
6743 static struct sock *
6744 bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6745               u8 proto, u64 netns_id, u64 flags)
6746 {
6747         struct sock *sk = bpf_skc_lookup(skb, tuple, len, proto, netns_id,
6748                                          flags);
6749
6750         if (sk) {
6751                 struct sock *sk2 = sk_to_full_sk(sk);
6752
6753                 /* sk_to_full_sk() may return (sk)->rsk_listener, so make sure the original sk
6754                  * sock refcnt is decremented to prevent a request_sock leak.
6755                  */
6756                 if (!sk_fullsock(sk2))
6757                         sk2 = NULL;
6758                 if (sk2 != sk) {
6759                         sock_gen_put(sk);
6760                         /* Ensure there is no need to bump sk2 refcnt */
6761                         if (unlikely(sk2 && !sock_flag(sk2, SOCK_RCU_FREE))) {
6762                                 WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
6763                                 return NULL;
6764                         }
6765                         sk = sk2;
6766                 }
6767         }
6768
6769         return sk;
6770 }
6771
6772 BPF_CALL_5(bpf_skc_lookup_tcp, struct sk_buff *, skb,
6773            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6774 {
6775         return (unsigned long)bpf_skc_lookup(skb, tuple, len, IPPROTO_TCP,
6776                                              netns_id, flags);
6777 }
6778
6779 static const struct bpf_func_proto bpf_skc_lookup_tcp_proto = {
6780         .func           = bpf_skc_lookup_tcp,
6781         .gpl_only       = false,
6782         .pkt_access     = true,
6783         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
6784         .arg1_type      = ARG_PTR_TO_CTX,
6785         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6786         .arg3_type      = ARG_CONST_SIZE,
6787         .arg4_type      = ARG_ANYTHING,
6788         .arg5_type      = ARG_ANYTHING,
6789 };
6790
6791 BPF_CALL_5(bpf_sk_lookup_tcp, struct sk_buff *, skb,
6792            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6793 {
6794         return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_TCP,
6795                                             netns_id, flags);
6796 }
6797
6798 static const struct bpf_func_proto bpf_sk_lookup_tcp_proto = {
6799         .func           = bpf_sk_lookup_tcp,
6800         .gpl_only       = false,
6801         .pkt_access     = true,
6802         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
6803         .arg1_type      = ARG_PTR_TO_CTX,
6804         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6805         .arg3_type      = ARG_CONST_SIZE,
6806         .arg4_type      = ARG_ANYTHING,
6807         .arg5_type      = ARG_ANYTHING,
6808 };
6809
6810 BPF_CALL_5(bpf_sk_lookup_udp, struct sk_buff *, skb,
6811            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6812 {
6813         return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_UDP,
6814                                             netns_id, flags);
6815 }
6816
6817 static const struct bpf_func_proto bpf_sk_lookup_udp_proto = {
6818         .func           = bpf_sk_lookup_udp,
6819         .gpl_only       = false,
6820         .pkt_access     = true,
6821         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
6822         .arg1_type      = ARG_PTR_TO_CTX,
6823         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6824         .arg3_type      = ARG_CONST_SIZE,
6825         .arg4_type      = ARG_ANYTHING,
6826         .arg5_type      = ARG_ANYTHING,
6827 };
6828
6829 BPF_CALL_5(bpf_tc_skc_lookup_tcp, struct sk_buff *, skb,
6830            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6831 {
6832         struct net_device *dev = skb->dev;
6833         int ifindex = dev->ifindex, sdif = dev_sdif(dev);
6834         struct net *caller_net = dev_net(dev);
6835
6836         return (unsigned long)__bpf_skc_lookup(skb, tuple, len, caller_net,
6837                                                ifindex, IPPROTO_TCP, netns_id,
6838                                                flags, sdif);
6839 }
6840
6841 static const struct bpf_func_proto bpf_tc_skc_lookup_tcp_proto = {
6842         .func           = bpf_tc_skc_lookup_tcp,
6843         .gpl_only       = false,
6844         .pkt_access     = true,
6845         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
6846         .arg1_type      = ARG_PTR_TO_CTX,
6847         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6848         .arg3_type      = ARG_CONST_SIZE,
6849         .arg4_type      = ARG_ANYTHING,
6850         .arg5_type      = ARG_ANYTHING,
6851 };
6852
6853 BPF_CALL_5(bpf_tc_sk_lookup_tcp, struct sk_buff *, skb,
6854            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6855 {
6856         struct net_device *dev = skb->dev;
6857         int ifindex = dev->ifindex, sdif = dev_sdif(dev);
6858         struct net *caller_net = dev_net(dev);
6859
6860         return (unsigned long)__bpf_sk_lookup(skb, tuple, len, caller_net,
6861                                               ifindex, IPPROTO_TCP, netns_id,
6862                                               flags, sdif);
6863 }
6864
6865 static const struct bpf_func_proto bpf_tc_sk_lookup_tcp_proto = {
6866         .func           = bpf_tc_sk_lookup_tcp,
6867         .gpl_only       = false,
6868         .pkt_access     = true,
6869         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
6870         .arg1_type      = ARG_PTR_TO_CTX,
6871         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6872         .arg3_type      = ARG_CONST_SIZE,
6873         .arg4_type      = ARG_ANYTHING,
6874         .arg5_type      = ARG_ANYTHING,
6875 };
6876
6877 BPF_CALL_5(bpf_tc_sk_lookup_udp, struct sk_buff *, skb,
6878            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6879 {
6880         struct net_device *dev = skb->dev;
6881         int ifindex = dev->ifindex, sdif = dev_sdif(dev);
6882         struct net *caller_net = dev_net(dev);
6883
6884         return (unsigned long)__bpf_sk_lookup(skb, tuple, len, caller_net,
6885                                               ifindex, IPPROTO_UDP, netns_id,
6886                                               flags, sdif);
6887 }
6888
6889 static const struct bpf_func_proto bpf_tc_sk_lookup_udp_proto = {
6890         .func           = bpf_tc_sk_lookup_udp,
6891         .gpl_only       = false,
6892         .pkt_access     = true,
6893         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
6894         .arg1_type      = ARG_PTR_TO_CTX,
6895         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6896         .arg3_type      = ARG_CONST_SIZE,
6897         .arg4_type      = ARG_ANYTHING,
6898         .arg5_type      = ARG_ANYTHING,
6899 };
6900
6901 BPF_CALL_1(bpf_sk_release, struct sock *, sk)
6902 {
6903         if (sk && sk_is_refcounted(sk))
6904                 sock_gen_put(sk);
6905         return 0;
6906 }
6907
6908 static const struct bpf_func_proto bpf_sk_release_proto = {
6909         .func           = bpf_sk_release,
6910         .gpl_only       = false,
6911         .ret_type       = RET_INTEGER,
6912         .arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON | OBJ_RELEASE,
6913 };
6914
6915 BPF_CALL_5(bpf_xdp_sk_lookup_udp, struct xdp_buff *, ctx,
6916            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
6917 {
6918         struct net_device *dev = ctx->rxq->dev;
6919         int ifindex = dev->ifindex, sdif = dev_sdif(dev);
6920         struct net *caller_net = dev_net(dev);
6921
6922         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
6923                                               ifindex, IPPROTO_UDP, netns_id,
6924                                               flags, sdif);
6925 }
6926
6927 static const struct bpf_func_proto bpf_xdp_sk_lookup_udp_proto = {
6928         .func           = bpf_xdp_sk_lookup_udp,
6929         .gpl_only       = false,
6930         .pkt_access     = true,
6931         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
6932         .arg1_type      = ARG_PTR_TO_CTX,
6933         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6934         .arg3_type      = ARG_CONST_SIZE,
6935         .arg4_type      = ARG_ANYTHING,
6936         .arg5_type      = ARG_ANYTHING,
6937 };
6938
6939 BPF_CALL_5(bpf_xdp_skc_lookup_tcp, struct xdp_buff *, ctx,
6940            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
6941 {
6942         struct net_device *dev = ctx->rxq->dev;
6943         int ifindex = dev->ifindex, sdif = dev_sdif(dev);
6944         struct net *caller_net = dev_net(dev);
6945
6946         return (unsigned long)__bpf_skc_lookup(NULL, tuple, len, caller_net,
6947                                                ifindex, IPPROTO_TCP, netns_id,
6948                                                flags, sdif);
6949 }
6950
6951 static const struct bpf_func_proto bpf_xdp_skc_lookup_tcp_proto = {
6952         .func           = bpf_xdp_skc_lookup_tcp,
6953         .gpl_only       = false,
6954         .pkt_access     = true,
6955         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
6956         .arg1_type      = ARG_PTR_TO_CTX,
6957         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6958         .arg3_type      = ARG_CONST_SIZE,
6959         .arg4_type      = ARG_ANYTHING,
6960         .arg5_type      = ARG_ANYTHING,
6961 };
6962
6963 BPF_CALL_5(bpf_xdp_sk_lookup_tcp, struct xdp_buff *, ctx,
6964            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
6965 {
6966         struct net_device *dev = ctx->rxq->dev;
6967         int ifindex = dev->ifindex, sdif = dev_sdif(dev);
6968         struct net *caller_net = dev_net(dev);
6969
6970         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
6971                                               ifindex, IPPROTO_TCP, netns_id,
6972                                               flags, sdif);
6973 }
6974
6975 static const struct bpf_func_proto bpf_xdp_sk_lookup_tcp_proto = {
6976         .func           = bpf_xdp_sk_lookup_tcp,
6977         .gpl_only       = false,
6978         .pkt_access     = true,
6979         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
6980         .arg1_type      = ARG_PTR_TO_CTX,
6981         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6982         .arg3_type      = ARG_CONST_SIZE,
6983         .arg4_type      = ARG_ANYTHING,
6984         .arg5_type      = ARG_ANYTHING,
6985 };
6986
6987 BPF_CALL_5(bpf_sock_addr_skc_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
6988            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6989 {
6990         return (unsigned long)__bpf_skc_lookup(NULL, tuple, len,
6991                                                sock_net(ctx->sk), 0,
6992                                                IPPROTO_TCP, netns_id, flags,
6993                                                -1);
6994 }
6995
6996 static const struct bpf_func_proto bpf_sock_addr_skc_lookup_tcp_proto = {
6997         .func           = bpf_sock_addr_skc_lookup_tcp,
6998         .gpl_only       = false,
6999         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
7000         .arg1_type      = ARG_PTR_TO_CTX,
7001         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7002         .arg3_type      = ARG_CONST_SIZE,
7003         .arg4_type      = ARG_ANYTHING,
7004         .arg5_type      = ARG_ANYTHING,
7005 };
7006
7007 BPF_CALL_5(bpf_sock_addr_sk_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
7008            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7009 {
7010         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
7011                                               sock_net(ctx->sk), 0, IPPROTO_TCP,
7012                                               netns_id, flags, -1);
7013 }
7014
7015 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_tcp_proto = {
7016         .func           = bpf_sock_addr_sk_lookup_tcp,
7017         .gpl_only       = false,
7018         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
7019         .arg1_type      = ARG_PTR_TO_CTX,
7020         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7021         .arg3_type      = ARG_CONST_SIZE,
7022         .arg4_type      = ARG_ANYTHING,
7023         .arg5_type      = ARG_ANYTHING,
7024 };
7025
7026 BPF_CALL_5(bpf_sock_addr_sk_lookup_udp, struct bpf_sock_addr_kern *, ctx,
7027            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7028 {
7029         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
7030                                               sock_net(ctx->sk), 0, IPPROTO_UDP,
7031                                               netns_id, flags, -1);
7032 }
7033
7034 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_udp_proto = {
7035         .func           = bpf_sock_addr_sk_lookup_udp,
7036         .gpl_only       = false,
7037         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
7038         .arg1_type      = ARG_PTR_TO_CTX,
7039         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7040         .arg3_type      = ARG_CONST_SIZE,
7041         .arg4_type      = ARG_ANYTHING,
7042         .arg5_type      = ARG_ANYTHING,
7043 };
7044
7045 bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
7046                                   struct bpf_insn_access_aux *info)
7047 {
7048         if (off < 0 || off >= offsetofend(struct bpf_tcp_sock,
7049                                           icsk_retransmits))
7050                 return false;
7051
7052         if (off % size != 0)
7053                 return false;
7054
7055         switch (off) {
7056         case offsetof(struct bpf_tcp_sock, bytes_received):
7057         case offsetof(struct bpf_tcp_sock, bytes_acked):
7058                 return size == sizeof(__u64);
7059         default:
7060                 return size == sizeof(__u32);
7061         }
7062 }
7063
7064 u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
7065                                     const struct bpf_insn *si,
7066                                     struct bpf_insn *insn_buf,
7067                                     struct bpf_prog *prog, u32 *target_size)
7068 {
7069         struct bpf_insn *insn = insn_buf;
7070
7071 #define BPF_TCP_SOCK_GET_COMMON(FIELD)                                  \
7072         do {                                                            \
7073                 BUILD_BUG_ON(sizeof_field(struct tcp_sock, FIELD) >     \
7074                              sizeof_field(struct bpf_tcp_sock, FIELD)); \
7075                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_sock, FIELD),\
7076                                       si->dst_reg, si->src_reg,         \
7077                                       offsetof(struct tcp_sock, FIELD)); \
7078         } while (0)
7079
7080 #define BPF_INET_SOCK_GET_COMMON(FIELD)                                 \
7081         do {                                                            \
7082                 BUILD_BUG_ON(sizeof_field(struct inet_connection_sock,  \
7083                                           FIELD) >                      \
7084                              sizeof_field(struct bpf_tcp_sock, FIELD)); \
7085                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                 \
7086                                         struct inet_connection_sock,    \
7087                                         FIELD),                         \
7088                                       si->dst_reg, si->src_reg,         \
7089                                       offsetof(                         \
7090                                         struct inet_connection_sock,    \
7091                                         FIELD));                        \
7092         } while (0)
7093
7094         BTF_TYPE_EMIT(struct bpf_tcp_sock);
7095
7096         switch (si->off) {
7097         case offsetof(struct bpf_tcp_sock, rtt_min):
7098                 BUILD_BUG_ON(sizeof_field(struct tcp_sock, rtt_min) !=
7099                              sizeof(struct minmax));
7100                 BUILD_BUG_ON(sizeof(struct minmax) <
7101                              sizeof(struct minmax_sample));
7102
7103                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7104                                       offsetof(struct tcp_sock, rtt_min) +
7105                                       offsetof(struct minmax_sample, v));
7106                 break;
7107         case offsetof(struct bpf_tcp_sock, snd_cwnd):
7108                 BPF_TCP_SOCK_GET_COMMON(snd_cwnd);
7109                 break;
7110         case offsetof(struct bpf_tcp_sock, srtt_us):
7111                 BPF_TCP_SOCK_GET_COMMON(srtt_us);
7112                 break;
7113         case offsetof(struct bpf_tcp_sock, snd_ssthresh):
7114                 BPF_TCP_SOCK_GET_COMMON(snd_ssthresh);
7115                 break;
7116         case offsetof(struct bpf_tcp_sock, rcv_nxt):
7117                 BPF_TCP_SOCK_GET_COMMON(rcv_nxt);
7118                 break;
7119         case offsetof(struct bpf_tcp_sock, snd_nxt):
7120                 BPF_TCP_SOCK_GET_COMMON(snd_nxt);
7121                 break;
7122         case offsetof(struct bpf_tcp_sock, snd_una):
7123                 BPF_TCP_SOCK_GET_COMMON(snd_una);
7124                 break;
7125         case offsetof(struct bpf_tcp_sock, mss_cache):
7126                 BPF_TCP_SOCK_GET_COMMON(mss_cache);
7127                 break;
7128         case offsetof(struct bpf_tcp_sock, ecn_flags):
7129                 BPF_TCP_SOCK_GET_COMMON(ecn_flags);
7130                 break;
7131         case offsetof(struct bpf_tcp_sock, rate_delivered):
7132                 BPF_TCP_SOCK_GET_COMMON(rate_delivered);
7133                 break;
7134         case offsetof(struct bpf_tcp_sock, rate_interval_us):
7135                 BPF_TCP_SOCK_GET_COMMON(rate_interval_us);
7136                 break;
7137         case offsetof(struct bpf_tcp_sock, packets_out):
7138                 BPF_TCP_SOCK_GET_COMMON(packets_out);
7139                 break;
7140         case offsetof(struct bpf_tcp_sock, retrans_out):
7141                 BPF_TCP_SOCK_GET_COMMON(retrans_out);
7142                 break;
7143         case offsetof(struct bpf_tcp_sock, total_retrans):
7144                 BPF_TCP_SOCK_GET_COMMON(total_retrans);
7145                 break;
7146         case offsetof(struct bpf_tcp_sock, segs_in):
7147                 BPF_TCP_SOCK_GET_COMMON(segs_in);
7148                 break;
7149         case offsetof(struct bpf_tcp_sock, data_segs_in):
7150                 BPF_TCP_SOCK_GET_COMMON(data_segs_in);
7151                 break;
7152         case offsetof(struct bpf_tcp_sock, segs_out):
7153                 BPF_TCP_SOCK_GET_COMMON(segs_out);
7154                 break;
7155         case offsetof(struct bpf_tcp_sock, data_segs_out):
7156                 BPF_TCP_SOCK_GET_COMMON(data_segs_out);
7157                 break;
7158         case offsetof(struct bpf_tcp_sock, lost_out):
7159                 BPF_TCP_SOCK_GET_COMMON(lost_out);
7160                 break;
7161         case offsetof(struct bpf_tcp_sock, sacked_out):
7162                 BPF_TCP_SOCK_GET_COMMON(sacked_out);
7163                 break;
7164         case offsetof(struct bpf_tcp_sock, bytes_received):
7165                 BPF_TCP_SOCK_GET_COMMON(bytes_received);
7166                 break;
7167         case offsetof(struct bpf_tcp_sock, bytes_acked):
7168                 BPF_TCP_SOCK_GET_COMMON(bytes_acked);
7169                 break;
7170         case offsetof(struct bpf_tcp_sock, dsack_dups):
7171                 BPF_TCP_SOCK_GET_COMMON(dsack_dups);
7172                 break;
7173         case offsetof(struct bpf_tcp_sock, delivered):
7174                 BPF_TCP_SOCK_GET_COMMON(delivered);
7175                 break;
7176         case offsetof(struct bpf_tcp_sock, delivered_ce):
7177                 BPF_TCP_SOCK_GET_COMMON(delivered_ce);
7178                 break;
7179         case offsetof(struct bpf_tcp_sock, icsk_retransmits):
7180                 BPF_INET_SOCK_GET_COMMON(icsk_retransmits);
7181                 break;
7182         }
7183
7184         return insn - insn_buf;
7185 }
7186
7187 BPF_CALL_1(bpf_tcp_sock, struct sock *, sk)
7188 {
7189         if (sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP)
7190                 return (unsigned long)sk;
7191
7192         return (unsigned long)NULL;
7193 }
7194
7195 const struct bpf_func_proto bpf_tcp_sock_proto = {
7196         .func           = bpf_tcp_sock,
7197         .gpl_only       = false,
7198         .ret_type       = RET_PTR_TO_TCP_SOCK_OR_NULL,
7199         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
7200 };
7201
7202 BPF_CALL_1(bpf_get_listener_sock, struct sock *, sk)
7203 {
7204         sk = sk_to_full_sk(sk);
7205
7206         if (sk->sk_state == TCP_LISTEN && sock_flag(sk, SOCK_RCU_FREE))
7207                 return (unsigned long)sk;
7208
7209         return (unsigned long)NULL;
7210 }
7211
7212 static const struct bpf_func_proto bpf_get_listener_sock_proto = {
7213         .func           = bpf_get_listener_sock,
7214         .gpl_only       = false,
7215         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
7216         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
7217 };
7218
7219 BPF_CALL_1(bpf_skb_ecn_set_ce, struct sk_buff *, skb)
7220 {
7221         unsigned int iphdr_len;
7222
7223         switch (skb_protocol(skb, true)) {
7224         case cpu_to_be16(ETH_P_IP):
7225                 iphdr_len = sizeof(struct iphdr);
7226                 break;
7227         case cpu_to_be16(ETH_P_IPV6):
7228                 iphdr_len = sizeof(struct ipv6hdr);
7229                 break;
7230         default:
7231                 return 0;
7232         }
7233
7234         if (skb_headlen(skb) < iphdr_len)
7235                 return 0;
7236
7237         if (skb_cloned(skb) && !skb_clone_writable(skb, iphdr_len))
7238                 return 0;
7239
7240         return INET_ECN_set_ce(skb);
7241 }
7242
7243 bool bpf_xdp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
7244                                   struct bpf_insn_access_aux *info)
7245 {
7246         if (off < 0 || off >= offsetofend(struct bpf_xdp_sock, queue_id))
7247                 return false;
7248
7249         if (off % size != 0)
7250                 return false;
7251
7252         switch (off) {
7253         default:
7254                 return size == sizeof(__u32);
7255         }
7256 }
7257
7258 u32 bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,
7259                                     const struct bpf_insn *si,
7260                                     struct bpf_insn *insn_buf,
7261                                     struct bpf_prog *prog, u32 *target_size)
7262 {
7263         struct bpf_insn *insn = insn_buf;
7264
7265 #define BPF_XDP_SOCK_GET(FIELD)                                         \
7266         do {                                                            \
7267                 BUILD_BUG_ON(sizeof_field(struct xdp_sock, FIELD) >     \
7268                              sizeof_field(struct bpf_xdp_sock, FIELD)); \
7269                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_sock, FIELD),\
7270                                       si->dst_reg, si->src_reg,         \
7271                                       offsetof(struct xdp_sock, FIELD)); \
7272         } while (0)
7273
7274         switch (si->off) {
7275         case offsetof(struct bpf_xdp_sock, queue_id):
7276                 BPF_XDP_SOCK_GET(queue_id);
7277                 break;
7278         }
7279
7280         return insn - insn_buf;
7281 }
7282
7283 static const struct bpf_func_proto bpf_skb_ecn_set_ce_proto = {
7284         .func           = bpf_skb_ecn_set_ce,
7285         .gpl_only       = false,
7286         .ret_type       = RET_INTEGER,
7287         .arg1_type      = ARG_PTR_TO_CTX,
7288 };
7289
7290 BPF_CALL_5(bpf_tcp_check_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
7291            struct tcphdr *, th, u32, th_len)
7292 {
7293 #ifdef CONFIG_SYN_COOKIES
7294         int ret;
7295
7296         if (unlikely(!sk || th_len < sizeof(*th)))
7297                 return -EINVAL;
7298
7299         /* sk_listener() allows TCP_NEW_SYN_RECV, which makes no sense here. */
7300         if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
7301                 return -EINVAL;
7302
7303         if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies))
7304                 return -EINVAL;
7305
7306         if (!th->ack || th->rst || th->syn)
7307                 return -ENOENT;
7308
7309         if (unlikely(iph_len < sizeof(struct iphdr)))
7310                 return -EINVAL;
7311
7312         if (tcp_synq_no_recent_overflow(sk))
7313                 return -ENOENT;
7314
7315         /* Both struct iphdr and struct ipv6hdr have the version field at the
7316          * same offset so we can cast to the shorter header (struct iphdr).
7317          */
7318         switch (((struct iphdr *)iph)->version) {
7319         case 4:
7320                 if (sk->sk_family == AF_INET6 && ipv6_only_sock(sk))
7321                         return -EINVAL;
7322
7323                 ret = __cookie_v4_check((struct iphdr *)iph, th);
7324                 break;
7325
7326 #if IS_BUILTIN(CONFIG_IPV6)
7327         case 6:
7328                 if (unlikely(iph_len < sizeof(struct ipv6hdr)))
7329                         return -EINVAL;
7330
7331                 if (sk->sk_family != AF_INET6)
7332                         return -EINVAL;
7333
7334                 ret = __cookie_v6_check((struct ipv6hdr *)iph, th);
7335                 break;
7336 #endif /* CONFIG_IPV6 */
7337
7338         default:
7339                 return -EPROTONOSUPPORT;
7340         }
7341
7342         if (ret > 0)
7343                 return 0;
7344
7345         return -ENOENT;
7346 #else
7347         return -ENOTSUPP;
7348 #endif
7349 }
7350
7351 static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = {
7352         .func           = bpf_tcp_check_syncookie,
7353         .gpl_only       = true,
7354         .pkt_access     = true,
7355         .ret_type       = RET_INTEGER,
7356         .arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
7357         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7358         .arg3_type      = ARG_CONST_SIZE,
7359         .arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7360         .arg5_type      = ARG_CONST_SIZE,
7361 };
7362
7363 BPF_CALL_5(bpf_tcp_gen_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
7364            struct tcphdr *, th, u32, th_len)
7365 {
7366 #ifdef CONFIG_SYN_COOKIES
7367         u32 cookie;
7368         u16 mss;
7369
7370         if (unlikely(!sk || th_len < sizeof(*th) || th_len != th->doff * 4))
7371                 return -EINVAL;
7372
7373         if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
7374                 return -EINVAL;
7375
7376         if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies))
7377                 return -ENOENT;
7378
7379         if (!th->syn || th->ack || th->fin || th->rst)
7380                 return -EINVAL;
7381
7382         if (unlikely(iph_len < sizeof(struct iphdr)))
7383                 return -EINVAL;
7384
7385         /* Both struct iphdr and struct ipv6hdr have the version field at the
7386          * same offset so we can cast to the shorter header (struct iphdr).
7387          */
7388         switch (((struct iphdr *)iph)->version) {
7389         case 4:
7390                 if (sk->sk_family == AF_INET6 && ipv6_only_sock(sk))
7391                         return -EINVAL;
7392
7393                 mss = tcp_v4_get_syncookie(sk, iph, th, &cookie);
7394                 break;
7395
7396 #if IS_BUILTIN(CONFIG_IPV6)
7397         case 6:
7398                 if (unlikely(iph_len < sizeof(struct ipv6hdr)))
7399                         return -EINVAL;
7400
7401                 if (sk->sk_family != AF_INET6)
7402                         return -EINVAL;
7403
7404                 mss = tcp_v6_get_syncookie(sk, iph, th, &cookie);
7405                 break;
7406 #endif /* CONFIG_IPV6 */
7407
7408         default:
7409                 return -EPROTONOSUPPORT;
7410         }
7411         if (mss == 0)
7412                 return -ENOENT;
7413
7414         return cookie | ((u64)mss << 32);
7415 #else
7416         return -EOPNOTSUPP;
7417 #endif /* CONFIG_SYN_COOKIES */
7418 }
7419
7420 static const struct bpf_func_proto bpf_tcp_gen_syncookie_proto = {
7421         .func           = bpf_tcp_gen_syncookie,
7422         .gpl_only       = true, /* __cookie_v*_init_sequence() is GPL */
7423         .pkt_access     = true,
7424         .ret_type       = RET_INTEGER,
7425         .arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
7426         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7427         .arg3_type      = ARG_CONST_SIZE,
7428         .arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7429         .arg5_type      = ARG_CONST_SIZE,
7430 };
7431
7432 BPF_CALL_3(bpf_sk_assign, struct sk_buff *, skb, struct sock *, sk, u64, flags)
7433 {
7434         if (!sk || flags != 0)
7435                 return -EINVAL;
7436         if (!skb_at_tc_ingress(skb))
7437                 return -EOPNOTSUPP;
7438         if (unlikely(dev_net(skb->dev) != sock_net(sk)))
7439                 return -ENETUNREACH;
7440         if (sk_unhashed(sk))
7441                 return -EOPNOTSUPP;
7442         if (sk_is_refcounted(sk) &&
7443             unlikely(!refcount_inc_not_zero(&sk->sk_refcnt)))
7444                 return -ENOENT;
7445
7446         skb_orphan(skb);
7447         skb->sk = sk;
7448         skb->destructor = sock_pfree;
7449
7450         return 0;
7451 }
7452
7453 static const struct bpf_func_proto bpf_sk_assign_proto = {
7454         .func           = bpf_sk_assign,
7455         .gpl_only       = false,
7456         .ret_type       = RET_INTEGER,
7457         .arg1_type      = ARG_PTR_TO_CTX,
7458         .arg2_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
7459         .arg3_type      = ARG_ANYTHING,
7460 };
7461
7462 static const u8 *bpf_search_tcp_opt(const u8 *op, const u8 *opend,
7463                                     u8 search_kind, const u8 *magic,
7464                                     u8 magic_len, bool *eol)
7465 {
7466         u8 kind, kind_len;
7467
7468         *eol = false;
7469
7470         while (op < opend) {
7471                 kind = op[0];
7472
7473                 if (kind == TCPOPT_EOL) {
7474                         *eol = true;
7475                         return ERR_PTR(-ENOMSG);
7476                 } else if (kind == TCPOPT_NOP) {
7477                         op++;
7478                         continue;
7479                 }
7480
7481                 if (opend - op < 2 || opend - op < op[1] || op[1] < 2)
7482                         /* Something is wrong in the received header.
7483                          * Follow the TCP stack's tcp_parse_options()
7484                          * and just bail here.
7485                          */
7486                         return ERR_PTR(-EFAULT);
7487
7488                 kind_len = op[1];
7489                 if (search_kind == kind) {
7490                         if (!magic_len)
7491                                 return op;
7492
7493                         if (magic_len > kind_len - 2)
7494                                 return ERR_PTR(-ENOMSG);
7495
7496                         if (!memcmp(&op[2], magic, magic_len))
7497                                 return op;
7498                 }
7499
7500                 op += kind_len;
7501         }
7502
7503         return ERR_PTR(-ENOMSG);
7504 }
7505
7506 BPF_CALL_4(bpf_sock_ops_load_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
7507            void *, search_res, u32, len, u64, flags)
7508 {
7509         bool eol, load_syn = flags & BPF_LOAD_HDR_OPT_TCP_SYN;
7510         const u8 *op, *opend, *magic, *search = search_res;
7511         u8 search_kind, search_len, copy_len, magic_len;
7512         int ret;
7513
7514         /* 2 byte is the minimal option len except TCPOPT_NOP and
7515          * TCPOPT_EOL which are useless for the bpf prog to learn
7516          * and this helper disallow loading them also.
7517          */
7518         if (len < 2 || flags & ~BPF_LOAD_HDR_OPT_TCP_SYN)
7519                 return -EINVAL;
7520
7521         search_kind = search[0];
7522         search_len = search[1];
7523
7524         if (search_len > len || search_kind == TCPOPT_NOP ||
7525             search_kind == TCPOPT_EOL)
7526                 return -EINVAL;
7527
7528         if (search_kind == TCPOPT_EXP || search_kind == 253) {
7529                 /* 16 or 32 bit magic.  +2 for kind and kind length */
7530                 if (search_len != 4 && search_len != 6)
7531                         return -EINVAL;
7532                 magic = &search[2];
7533                 magic_len = search_len - 2;
7534         } else {
7535                 if (search_len)
7536                         return -EINVAL;
7537                 magic = NULL;
7538                 magic_len = 0;
7539         }
7540
7541         if (load_syn) {
7542                 ret = bpf_sock_ops_get_syn(bpf_sock, TCP_BPF_SYN, &op);
7543                 if (ret < 0)
7544                         return ret;
7545
7546                 opend = op + ret;
7547                 op += sizeof(struct tcphdr);
7548         } else {
7549                 if (!bpf_sock->skb ||
7550                     bpf_sock->op == BPF_SOCK_OPS_HDR_OPT_LEN_CB)
7551                         /* This bpf_sock->op cannot call this helper */
7552                         return -EPERM;
7553
7554                 opend = bpf_sock->skb_data_end;
7555                 op = bpf_sock->skb->data + sizeof(struct tcphdr);
7556         }
7557
7558         op = bpf_search_tcp_opt(op, opend, search_kind, magic, magic_len,
7559                                 &eol);
7560         if (IS_ERR(op))
7561                 return PTR_ERR(op);
7562
7563         copy_len = op[1];
7564         ret = copy_len;
7565         if (copy_len > len) {
7566                 ret = -ENOSPC;
7567                 copy_len = len;
7568         }
7569
7570         memcpy(search_res, op, copy_len);
7571         return ret;
7572 }
7573
7574 static const struct bpf_func_proto bpf_sock_ops_load_hdr_opt_proto = {
7575         .func           = bpf_sock_ops_load_hdr_opt,
7576         .gpl_only       = false,
7577         .ret_type       = RET_INTEGER,
7578         .arg1_type      = ARG_PTR_TO_CTX,
7579         .arg2_type      = ARG_PTR_TO_MEM,
7580         .arg3_type      = ARG_CONST_SIZE,
7581         .arg4_type      = ARG_ANYTHING,
7582 };
7583
7584 BPF_CALL_4(bpf_sock_ops_store_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
7585            const void *, from, u32, len, u64, flags)
7586 {
7587         u8 new_kind, new_kind_len, magic_len = 0, *opend;
7588         const u8 *op, *new_op, *magic = NULL;
7589         struct sk_buff *skb;
7590         bool eol;
7591
7592         if (bpf_sock->op != BPF_SOCK_OPS_WRITE_HDR_OPT_CB)
7593                 return -EPERM;
7594
7595         if (len < 2 || flags)
7596                 return -EINVAL;
7597
7598         new_op = from;
7599         new_kind = new_op[0];
7600         new_kind_len = new_op[1];
7601
7602         if (new_kind_len > len || new_kind == TCPOPT_NOP ||
7603             new_kind == TCPOPT_EOL)
7604                 return -EINVAL;
7605
7606         if (new_kind_len > bpf_sock->remaining_opt_len)
7607                 return -ENOSPC;
7608
7609         /* 253 is another experimental kind */
7610         if (new_kind == TCPOPT_EXP || new_kind == 253)  {
7611                 if (new_kind_len < 4)
7612                         return -EINVAL;
7613                 /* Match for the 2 byte magic also.
7614                  * RFC 6994: the magic could be 2 or 4 bytes.
7615                  * Hence, matching by 2 byte only is on the
7616                  * conservative side but it is the right
7617                  * thing to do for the 'search-for-duplication'
7618                  * purpose.
7619                  */
7620                 magic = &new_op[2];
7621                 magic_len = 2;
7622         }
7623
7624         /* Check for duplication */
7625         skb = bpf_sock->skb;
7626         op = skb->data + sizeof(struct tcphdr);
7627         opend = bpf_sock->skb_data_end;
7628
7629         op = bpf_search_tcp_opt(op, opend, new_kind, magic, magic_len,
7630                                 &eol);
7631         if (!IS_ERR(op))
7632                 return -EEXIST;
7633
7634         if (PTR_ERR(op) != -ENOMSG)
7635                 return PTR_ERR(op);
7636
7637         if (eol)
7638                 /* The option has been ended.  Treat it as no more
7639                  * header option can be written.
7640                  */
7641                 return -ENOSPC;
7642
7643         /* No duplication found.  Store the header option. */
7644         memcpy(opend, from, new_kind_len);
7645
7646         bpf_sock->remaining_opt_len -= new_kind_len;
7647         bpf_sock->skb_data_end += new_kind_len;
7648
7649         return 0;
7650 }
7651
7652 static const struct bpf_func_proto bpf_sock_ops_store_hdr_opt_proto = {
7653         .func           = bpf_sock_ops_store_hdr_opt,
7654         .gpl_only       = false,
7655         .ret_type       = RET_INTEGER,
7656         .arg1_type      = ARG_PTR_TO_CTX,
7657         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7658         .arg3_type      = ARG_CONST_SIZE,
7659         .arg4_type      = ARG_ANYTHING,
7660 };
7661
7662 BPF_CALL_3(bpf_sock_ops_reserve_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
7663            u32, len, u64, flags)
7664 {
7665         if (bpf_sock->op != BPF_SOCK_OPS_HDR_OPT_LEN_CB)
7666                 return -EPERM;
7667
7668         if (flags || len < 2)
7669                 return -EINVAL;
7670
7671         if (len > bpf_sock->remaining_opt_len)
7672                 return -ENOSPC;
7673
7674         bpf_sock->remaining_opt_len -= len;
7675
7676         return 0;
7677 }
7678
7679 static const struct bpf_func_proto bpf_sock_ops_reserve_hdr_opt_proto = {
7680         .func           = bpf_sock_ops_reserve_hdr_opt,
7681         .gpl_only       = false,
7682         .ret_type       = RET_INTEGER,
7683         .arg1_type      = ARG_PTR_TO_CTX,
7684         .arg2_type      = ARG_ANYTHING,
7685         .arg3_type      = ARG_ANYTHING,
7686 };
7687
7688 BPF_CALL_3(bpf_skb_set_tstamp, struct sk_buff *, skb,
7689            u64, tstamp, u32, tstamp_type)
7690 {
7691         /* skb_clear_delivery_time() is done for inet protocol */
7692         if (skb->protocol != htons(ETH_P_IP) &&
7693             skb->protocol != htons(ETH_P_IPV6))
7694                 return -EOPNOTSUPP;
7695
7696         switch (tstamp_type) {
7697         case BPF_SKB_TSTAMP_DELIVERY_MONO:
7698                 if (!tstamp)
7699                         return -EINVAL;
7700                 skb->tstamp = tstamp;
7701                 skb->mono_delivery_time = 1;
7702                 break;
7703         case BPF_SKB_TSTAMP_UNSPEC:
7704                 if (tstamp)
7705                         return -EINVAL;
7706                 skb->tstamp = 0;
7707                 skb->mono_delivery_time = 0;
7708                 break;
7709         default:
7710                 return -EINVAL;
7711         }
7712
7713         return 0;
7714 }
7715
7716 static const struct bpf_func_proto bpf_skb_set_tstamp_proto = {
7717         .func           = bpf_skb_set_tstamp,
7718         .gpl_only       = false,
7719         .ret_type       = RET_INTEGER,
7720         .arg1_type      = ARG_PTR_TO_CTX,
7721         .arg2_type      = ARG_ANYTHING,
7722         .arg3_type      = ARG_ANYTHING,
7723 };
7724
7725 #ifdef CONFIG_SYN_COOKIES
7726 BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv4, struct iphdr *, iph,
7727            struct tcphdr *, th, u32, th_len)
7728 {
7729         u32 cookie;
7730         u16 mss;
7731
7732         if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
7733                 return -EINVAL;
7734
7735         mss = tcp_parse_mss_option(th, 0) ?: TCP_MSS_DEFAULT;
7736         cookie = __cookie_v4_init_sequence(iph, th, &mss);
7737
7738         return cookie | ((u64)mss << 32);
7739 }
7740
7741 static const struct bpf_func_proto bpf_tcp_raw_gen_syncookie_ipv4_proto = {
7742         .func           = bpf_tcp_raw_gen_syncookie_ipv4,
7743         .gpl_only       = true, /* __cookie_v4_init_sequence() is GPL */
7744         .pkt_access     = true,
7745         .ret_type       = RET_INTEGER,
7746         .arg1_type      = ARG_PTR_TO_FIXED_SIZE_MEM,
7747         .arg1_size      = sizeof(struct iphdr),
7748         .arg2_type      = ARG_PTR_TO_MEM,
7749         .arg3_type      = ARG_CONST_SIZE_OR_ZERO,
7750 };
7751
7752 BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv6, struct ipv6hdr *, iph,
7753            struct tcphdr *, th, u32, th_len)
7754 {
7755 #if IS_BUILTIN(CONFIG_IPV6)
7756         const u16 mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) -
7757                 sizeof(struct ipv6hdr);
7758         u32 cookie;
7759         u16 mss;
7760
7761         if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
7762                 return -EINVAL;
7763
7764         mss = tcp_parse_mss_option(th, 0) ?: mss_clamp;
7765         cookie = __cookie_v6_init_sequence(iph, th, &mss);
7766
7767         return cookie | ((u64)mss << 32);
7768 #else
7769         return -EPROTONOSUPPORT;
7770 #endif
7771 }
7772
7773 static const struct bpf_func_proto bpf_tcp_raw_gen_syncookie_ipv6_proto = {
7774         .func           = bpf_tcp_raw_gen_syncookie_ipv6,
7775         .gpl_only       = true, /* __cookie_v6_init_sequence() is GPL */
7776         .pkt_access     = true,
7777         .ret_type       = RET_INTEGER,
7778         .arg1_type      = ARG_PTR_TO_FIXED_SIZE_MEM,
7779         .arg1_size      = sizeof(struct ipv6hdr),
7780         .arg2_type      = ARG_PTR_TO_MEM,
7781         .arg3_type      = ARG_CONST_SIZE_OR_ZERO,
7782 };
7783
7784 BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv4, struct iphdr *, iph,
7785            struct tcphdr *, th)
7786 {
7787         if (__cookie_v4_check(iph, th) > 0)
7788                 return 0;
7789
7790         return -EACCES;
7791 }
7792
7793 static const struct bpf_func_proto bpf_tcp_raw_check_syncookie_ipv4_proto = {
7794         .func           = bpf_tcp_raw_check_syncookie_ipv4,
7795         .gpl_only       = true, /* __cookie_v4_check is GPL */
7796         .pkt_access     = true,
7797         .ret_type       = RET_INTEGER,
7798         .arg1_type      = ARG_PTR_TO_FIXED_SIZE_MEM,
7799         .arg1_size      = sizeof(struct iphdr),
7800         .arg2_type      = ARG_PTR_TO_FIXED_SIZE_MEM,
7801         .arg2_size      = sizeof(struct tcphdr),
7802 };
7803
7804 BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv6, struct ipv6hdr *, iph,
7805            struct tcphdr *, th)
7806 {
7807 #if IS_BUILTIN(CONFIG_IPV6)
7808         if (__cookie_v6_check(iph, th) > 0)
7809                 return 0;
7810
7811         return -EACCES;
7812 #else
7813         return -EPROTONOSUPPORT;
7814 #endif
7815 }
7816
7817 static const struct bpf_func_proto bpf_tcp_raw_check_syncookie_ipv6_proto = {
7818         .func           = bpf_tcp_raw_check_syncookie_ipv6,
7819         .gpl_only       = true, /* __cookie_v6_check is GPL */
7820         .pkt_access     = true,
7821         .ret_type       = RET_INTEGER,
7822         .arg1_type      = ARG_PTR_TO_FIXED_SIZE_MEM,
7823         .arg1_size      = sizeof(struct ipv6hdr),
7824         .arg2_type      = ARG_PTR_TO_FIXED_SIZE_MEM,
7825         .arg2_size      = sizeof(struct tcphdr),
7826 };
7827 #endif /* CONFIG_SYN_COOKIES */
7828
7829 #endif /* CONFIG_INET */
7830
7831 bool bpf_helper_changes_pkt_data(void *func)
7832 {
7833         if (func == bpf_skb_vlan_push ||
7834             func == bpf_skb_vlan_pop ||
7835             func == bpf_skb_store_bytes ||
7836             func == bpf_skb_change_proto ||
7837             func == bpf_skb_change_head ||
7838             func == sk_skb_change_head ||
7839             func == bpf_skb_change_tail ||
7840             func == sk_skb_change_tail ||
7841             func == bpf_skb_adjust_room ||
7842             func == sk_skb_adjust_room ||
7843             func == bpf_skb_pull_data ||
7844             func == sk_skb_pull_data ||
7845             func == bpf_clone_redirect ||
7846             func == bpf_l3_csum_replace ||
7847             func == bpf_l4_csum_replace ||
7848             func == bpf_xdp_adjust_head ||
7849             func == bpf_xdp_adjust_meta ||
7850             func == bpf_msg_pull_data ||
7851             func == bpf_msg_push_data ||
7852             func == bpf_msg_pop_data ||
7853             func == bpf_xdp_adjust_tail ||
7854 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
7855             func == bpf_lwt_seg6_store_bytes ||
7856             func == bpf_lwt_seg6_adjust_srh ||
7857             func == bpf_lwt_seg6_action ||
7858 #endif
7859 #ifdef CONFIG_INET
7860             func == bpf_sock_ops_store_hdr_opt ||
7861 #endif
7862             func == bpf_lwt_in_push_encap ||
7863             func == bpf_lwt_xmit_push_encap)
7864                 return true;
7865
7866         return false;
7867 }
7868
7869 const struct bpf_func_proto bpf_event_output_data_proto __weak;
7870 const struct bpf_func_proto bpf_sk_storage_get_cg_sock_proto __weak;
7871
7872 static const struct bpf_func_proto *
7873 sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
7874 {
7875         const struct bpf_func_proto *func_proto;
7876
7877         func_proto = cgroup_common_func_proto(func_id, prog);
7878         if (func_proto)
7879                 return func_proto;
7880
7881         func_proto = cgroup_current_func_proto(func_id, prog);
7882         if (func_proto)
7883                 return func_proto;
7884
7885         switch (func_id) {
7886         case BPF_FUNC_get_socket_cookie:
7887                 return &bpf_get_socket_cookie_sock_proto;
7888         case BPF_FUNC_get_netns_cookie:
7889                 return &bpf_get_netns_cookie_sock_proto;
7890         case BPF_FUNC_perf_event_output:
7891                 return &bpf_event_output_data_proto;
7892         case BPF_FUNC_sk_storage_get:
7893                 return &bpf_sk_storage_get_cg_sock_proto;
7894         case BPF_FUNC_ktime_get_coarse_ns:
7895                 return &bpf_ktime_get_coarse_ns_proto;
7896         default:
7897                 return bpf_base_func_proto(func_id);
7898         }
7899 }
7900
7901 static const struct bpf_func_proto *
7902 sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
7903 {
7904         const struct bpf_func_proto *func_proto;
7905
7906         func_proto = cgroup_common_func_proto(func_id, prog);
7907         if (func_proto)
7908                 return func_proto;
7909
7910         func_proto = cgroup_current_func_proto(func_id, prog);
7911         if (func_proto)
7912                 return func_proto;
7913
7914         switch (func_id) {
7915         case BPF_FUNC_bind:
7916                 switch (prog->expected_attach_type) {
7917                 case BPF_CGROUP_INET4_CONNECT:
7918                 case BPF_CGROUP_INET6_CONNECT:
7919                         return &bpf_bind_proto;
7920                 default:
7921                         return NULL;
7922                 }
7923         case BPF_FUNC_get_socket_cookie:
7924                 return &bpf_get_socket_cookie_sock_addr_proto;
7925         case BPF_FUNC_get_netns_cookie:
7926                 return &bpf_get_netns_cookie_sock_addr_proto;
7927         case BPF_FUNC_perf_event_output:
7928                 return &bpf_event_output_data_proto;
7929 #ifdef CONFIG_INET
7930         case BPF_FUNC_sk_lookup_tcp:
7931                 return &bpf_sock_addr_sk_lookup_tcp_proto;
7932         case BPF_FUNC_sk_lookup_udp:
7933                 return &bpf_sock_addr_sk_lookup_udp_proto;
7934         case BPF_FUNC_sk_release:
7935                 return &bpf_sk_release_proto;
7936         case BPF_FUNC_skc_lookup_tcp:
7937                 return &bpf_sock_addr_skc_lookup_tcp_proto;
7938 #endif /* CONFIG_INET */
7939         case BPF_FUNC_sk_storage_get:
7940                 return &bpf_sk_storage_get_proto;
7941         case BPF_FUNC_sk_storage_delete:
7942                 return &bpf_sk_storage_delete_proto;
7943         case BPF_FUNC_setsockopt:
7944                 switch (prog->expected_attach_type) {
7945                 case BPF_CGROUP_INET4_BIND:
7946                 case BPF_CGROUP_INET6_BIND:
7947                 case BPF_CGROUP_INET4_CONNECT:
7948                 case BPF_CGROUP_INET6_CONNECT:
7949                 case BPF_CGROUP_UNIX_CONNECT:
7950                 case BPF_CGROUP_UDP4_RECVMSG:
7951                 case BPF_CGROUP_UDP6_RECVMSG:
7952                 case BPF_CGROUP_UNIX_RECVMSG:
7953                 case BPF_CGROUP_UDP4_SENDMSG:
7954                 case BPF_CGROUP_UDP6_SENDMSG:
7955                 case BPF_CGROUP_UNIX_SENDMSG:
7956                 case BPF_CGROUP_INET4_GETPEERNAME:
7957                 case BPF_CGROUP_INET6_GETPEERNAME:
7958                 case BPF_CGROUP_UNIX_GETPEERNAME:
7959                 case BPF_CGROUP_INET4_GETSOCKNAME:
7960                 case BPF_CGROUP_INET6_GETSOCKNAME:
7961                 case BPF_CGROUP_UNIX_GETSOCKNAME:
7962                         return &bpf_sock_addr_setsockopt_proto;
7963                 default:
7964                         return NULL;
7965                 }
7966         case BPF_FUNC_getsockopt:
7967                 switch (prog->expected_attach_type) {
7968                 case BPF_CGROUP_INET4_BIND:
7969                 case BPF_CGROUP_INET6_BIND:
7970                 case BPF_CGROUP_INET4_CONNECT:
7971                 case BPF_CGROUP_INET6_CONNECT:
7972                 case BPF_CGROUP_UNIX_CONNECT:
7973                 case BPF_CGROUP_UDP4_RECVMSG:
7974                 case BPF_CGROUP_UDP6_RECVMSG:
7975                 case BPF_CGROUP_UNIX_RECVMSG:
7976                 case BPF_CGROUP_UDP4_SENDMSG:
7977                 case BPF_CGROUP_UDP6_SENDMSG:
7978                 case BPF_CGROUP_UNIX_SENDMSG:
7979                 case BPF_CGROUP_INET4_GETPEERNAME:
7980                 case BPF_CGROUP_INET6_GETPEERNAME:
7981                 case BPF_CGROUP_UNIX_GETPEERNAME:
7982                 case BPF_CGROUP_INET4_GETSOCKNAME:
7983                 case BPF_CGROUP_INET6_GETSOCKNAME:
7984                 case BPF_CGROUP_UNIX_GETSOCKNAME:
7985                         return &bpf_sock_addr_getsockopt_proto;
7986                 default:
7987                         return NULL;
7988                 }
7989         default:
7990                 return bpf_sk_base_func_proto(func_id);
7991         }
7992 }
7993
7994 static const struct bpf_func_proto *
7995 sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
7996 {
7997         switch (func_id) {
7998         case BPF_FUNC_skb_load_bytes:
7999                 return &bpf_skb_load_bytes_proto;
8000         case BPF_FUNC_skb_load_bytes_relative:
8001                 return &bpf_skb_load_bytes_relative_proto;
8002         case BPF_FUNC_get_socket_cookie:
8003                 return &bpf_get_socket_cookie_proto;
8004         case BPF_FUNC_get_socket_uid:
8005                 return &bpf_get_socket_uid_proto;
8006         case BPF_FUNC_perf_event_output:
8007                 return &bpf_skb_event_output_proto;
8008         default:
8009                 return bpf_sk_base_func_proto(func_id);
8010         }
8011 }
8012
8013 const struct bpf_func_proto bpf_sk_storage_get_proto __weak;
8014 const struct bpf_func_proto bpf_sk_storage_delete_proto __weak;
8015
8016 static const struct bpf_func_proto *
8017 cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8018 {
8019         const struct bpf_func_proto *func_proto;
8020
8021         func_proto = cgroup_common_func_proto(func_id, prog);
8022         if (func_proto)
8023                 return func_proto;
8024
8025         switch (func_id) {
8026         case BPF_FUNC_sk_fullsock:
8027                 return &bpf_sk_fullsock_proto;
8028         case BPF_FUNC_sk_storage_get:
8029                 return &bpf_sk_storage_get_proto;
8030         case BPF_FUNC_sk_storage_delete:
8031                 return &bpf_sk_storage_delete_proto;
8032         case BPF_FUNC_perf_event_output:
8033                 return &bpf_skb_event_output_proto;
8034 #ifdef CONFIG_SOCK_CGROUP_DATA
8035         case BPF_FUNC_skb_cgroup_id:
8036                 return &bpf_skb_cgroup_id_proto;
8037         case BPF_FUNC_skb_ancestor_cgroup_id:
8038                 return &bpf_skb_ancestor_cgroup_id_proto;
8039         case BPF_FUNC_sk_cgroup_id:
8040                 return &bpf_sk_cgroup_id_proto;
8041         case BPF_FUNC_sk_ancestor_cgroup_id:
8042                 return &bpf_sk_ancestor_cgroup_id_proto;
8043 #endif
8044 #ifdef CONFIG_INET
8045         case BPF_FUNC_sk_lookup_tcp:
8046                 return &bpf_sk_lookup_tcp_proto;
8047         case BPF_FUNC_sk_lookup_udp:
8048                 return &bpf_sk_lookup_udp_proto;
8049         case BPF_FUNC_sk_release:
8050                 return &bpf_sk_release_proto;
8051         case BPF_FUNC_skc_lookup_tcp:
8052                 return &bpf_skc_lookup_tcp_proto;
8053         case BPF_FUNC_tcp_sock:
8054                 return &bpf_tcp_sock_proto;
8055         case BPF_FUNC_get_listener_sock:
8056                 return &bpf_get_listener_sock_proto;
8057         case BPF_FUNC_skb_ecn_set_ce:
8058                 return &bpf_skb_ecn_set_ce_proto;
8059 #endif
8060         default:
8061                 return sk_filter_func_proto(func_id, prog);
8062         }
8063 }
8064
8065 static const struct bpf_func_proto *
8066 tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8067 {
8068         switch (func_id) {
8069         case BPF_FUNC_skb_store_bytes:
8070                 return &bpf_skb_store_bytes_proto;
8071         case BPF_FUNC_skb_load_bytes:
8072                 return &bpf_skb_load_bytes_proto;
8073         case BPF_FUNC_skb_load_bytes_relative:
8074                 return &bpf_skb_load_bytes_relative_proto;
8075         case BPF_FUNC_skb_pull_data:
8076                 return &bpf_skb_pull_data_proto;
8077         case BPF_FUNC_csum_diff:
8078                 return &bpf_csum_diff_proto;
8079         case BPF_FUNC_csum_update:
8080                 return &bpf_csum_update_proto;
8081         case BPF_FUNC_csum_level:
8082                 return &bpf_csum_level_proto;
8083         case BPF_FUNC_l3_csum_replace:
8084                 return &bpf_l3_csum_replace_proto;
8085         case BPF_FUNC_l4_csum_replace:
8086                 return &bpf_l4_csum_replace_proto;
8087         case BPF_FUNC_clone_redirect:
8088                 return &bpf_clone_redirect_proto;
8089         case BPF_FUNC_get_cgroup_classid:
8090                 return &bpf_get_cgroup_classid_proto;
8091         case BPF_FUNC_skb_vlan_push:
8092                 return &bpf_skb_vlan_push_proto;
8093         case BPF_FUNC_skb_vlan_pop:
8094                 return &bpf_skb_vlan_pop_proto;
8095         case BPF_FUNC_skb_change_proto:
8096                 return &bpf_skb_change_proto_proto;
8097         case BPF_FUNC_skb_change_type:
8098                 return &bpf_skb_change_type_proto;
8099         case BPF_FUNC_skb_adjust_room:
8100                 return &bpf_skb_adjust_room_proto;
8101         case BPF_FUNC_skb_change_tail:
8102                 return &bpf_skb_change_tail_proto;
8103         case BPF_FUNC_skb_change_head:
8104                 return &bpf_skb_change_head_proto;
8105         case BPF_FUNC_skb_get_tunnel_key:
8106                 return &bpf_skb_get_tunnel_key_proto;
8107         case BPF_FUNC_skb_set_tunnel_key:
8108                 return bpf_get_skb_set_tunnel_proto(func_id);
8109         case BPF_FUNC_skb_get_tunnel_opt:
8110                 return &bpf_skb_get_tunnel_opt_proto;
8111         case BPF_FUNC_skb_set_tunnel_opt:
8112                 return bpf_get_skb_set_tunnel_proto(func_id);
8113         case BPF_FUNC_redirect:
8114                 return &bpf_redirect_proto;
8115         case BPF_FUNC_redirect_neigh:
8116                 return &bpf_redirect_neigh_proto;
8117         case BPF_FUNC_redirect_peer:
8118                 return &bpf_redirect_peer_proto;
8119         case BPF_FUNC_get_route_realm:
8120                 return &bpf_get_route_realm_proto;
8121         case BPF_FUNC_get_hash_recalc:
8122                 return &bpf_get_hash_recalc_proto;
8123         case BPF_FUNC_set_hash_invalid:
8124                 return &bpf_set_hash_invalid_proto;
8125         case BPF_FUNC_set_hash:
8126                 return &bpf_set_hash_proto;
8127         case BPF_FUNC_perf_event_output:
8128                 return &bpf_skb_event_output_proto;
8129         case BPF_FUNC_get_smp_processor_id:
8130                 return &bpf_get_smp_processor_id_proto;
8131         case BPF_FUNC_skb_under_cgroup:
8132                 return &bpf_skb_under_cgroup_proto;
8133         case BPF_FUNC_get_socket_cookie:
8134                 return &bpf_get_socket_cookie_proto;
8135         case BPF_FUNC_get_socket_uid:
8136                 return &bpf_get_socket_uid_proto;
8137         case BPF_FUNC_fib_lookup:
8138                 return &bpf_skb_fib_lookup_proto;
8139         case BPF_FUNC_check_mtu:
8140                 return &bpf_skb_check_mtu_proto;
8141         case BPF_FUNC_sk_fullsock:
8142                 return &bpf_sk_fullsock_proto;
8143         case BPF_FUNC_sk_storage_get:
8144                 return &bpf_sk_storage_get_proto;
8145         case BPF_FUNC_sk_storage_delete:
8146                 return &bpf_sk_storage_delete_proto;
8147 #ifdef CONFIG_XFRM
8148         case BPF_FUNC_skb_get_xfrm_state:
8149                 return &bpf_skb_get_xfrm_state_proto;
8150 #endif
8151 #ifdef CONFIG_CGROUP_NET_CLASSID
8152         case BPF_FUNC_skb_cgroup_classid:
8153                 return &bpf_skb_cgroup_classid_proto;
8154 #endif
8155 #ifdef CONFIG_SOCK_CGROUP_DATA
8156         case BPF_FUNC_skb_cgroup_id:
8157                 return &bpf_skb_cgroup_id_proto;
8158         case BPF_FUNC_skb_ancestor_cgroup_id:
8159                 return &bpf_skb_ancestor_cgroup_id_proto;
8160 #endif
8161 #ifdef CONFIG_INET
8162         case BPF_FUNC_sk_lookup_tcp:
8163                 return &bpf_tc_sk_lookup_tcp_proto;
8164         case BPF_FUNC_sk_lookup_udp:
8165                 return &bpf_tc_sk_lookup_udp_proto;
8166         case BPF_FUNC_sk_release:
8167                 return &bpf_sk_release_proto;
8168         case BPF_FUNC_tcp_sock:
8169                 return &bpf_tcp_sock_proto;
8170         case BPF_FUNC_get_listener_sock:
8171                 return &bpf_get_listener_sock_proto;
8172         case BPF_FUNC_skc_lookup_tcp:
8173                 return &bpf_tc_skc_lookup_tcp_proto;
8174         case BPF_FUNC_tcp_check_syncookie:
8175                 return &bpf_tcp_check_syncookie_proto;
8176         case BPF_FUNC_skb_ecn_set_ce:
8177                 return &bpf_skb_ecn_set_ce_proto;
8178         case BPF_FUNC_tcp_gen_syncookie:
8179                 return &bpf_tcp_gen_syncookie_proto;
8180         case BPF_FUNC_sk_assign:
8181                 return &bpf_sk_assign_proto;
8182         case BPF_FUNC_skb_set_tstamp:
8183                 return &bpf_skb_set_tstamp_proto;
8184 #ifdef CONFIG_SYN_COOKIES
8185         case BPF_FUNC_tcp_raw_gen_syncookie_ipv4:
8186                 return &bpf_tcp_raw_gen_syncookie_ipv4_proto;
8187         case BPF_FUNC_tcp_raw_gen_syncookie_ipv6:
8188                 return &bpf_tcp_raw_gen_syncookie_ipv6_proto;
8189         case BPF_FUNC_tcp_raw_check_syncookie_ipv4:
8190                 return &bpf_tcp_raw_check_syncookie_ipv4_proto;
8191         case BPF_FUNC_tcp_raw_check_syncookie_ipv6:
8192                 return &bpf_tcp_raw_check_syncookie_ipv6_proto;
8193 #endif
8194 #endif
8195         default:
8196                 return bpf_sk_base_func_proto(func_id);
8197         }
8198 }
8199
8200 static const struct bpf_func_proto *
8201 xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8202 {
8203         switch (func_id) {
8204         case BPF_FUNC_perf_event_output:
8205                 return &bpf_xdp_event_output_proto;
8206         case BPF_FUNC_get_smp_processor_id:
8207                 return &bpf_get_smp_processor_id_proto;
8208         case BPF_FUNC_csum_diff:
8209                 return &bpf_csum_diff_proto;
8210         case BPF_FUNC_xdp_adjust_head:
8211                 return &bpf_xdp_adjust_head_proto;
8212         case BPF_FUNC_xdp_adjust_meta:
8213                 return &bpf_xdp_adjust_meta_proto;
8214         case BPF_FUNC_redirect:
8215                 return &bpf_xdp_redirect_proto;
8216         case BPF_FUNC_redirect_map:
8217                 return &bpf_xdp_redirect_map_proto;
8218         case BPF_FUNC_xdp_adjust_tail:
8219                 return &bpf_xdp_adjust_tail_proto;
8220         case BPF_FUNC_xdp_get_buff_len:
8221                 return &bpf_xdp_get_buff_len_proto;
8222         case BPF_FUNC_xdp_load_bytes:
8223                 return &bpf_xdp_load_bytes_proto;
8224         case BPF_FUNC_xdp_store_bytes:
8225                 return &bpf_xdp_store_bytes_proto;
8226         case BPF_FUNC_fib_lookup:
8227                 return &bpf_xdp_fib_lookup_proto;
8228         case BPF_FUNC_check_mtu:
8229                 return &bpf_xdp_check_mtu_proto;
8230 #ifdef CONFIG_INET
8231         case BPF_FUNC_sk_lookup_udp:
8232                 return &bpf_xdp_sk_lookup_udp_proto;
8233         case BPF_FUNC_sk_lookup_tcp:
8234                 return &bpf_xdp_sk_lookup_tcp_proto;
8235         case BPF_FUNC_sk_release:
8236                 return &bpf_sk_release_proto;
8237         case BPF_FUNC_skc_lookup_tcp:
8238                 return &bpf_xdp_skc_lookup_tcp_proto;
8239         case BPF_FUNC_tcp_check_syncookie:
8240                 return &bpf_tcp_check_syncookie_proto;
8241         case BPF_FUNC_tcp_gen_syncookie:
8242                 return &bpf_tcp_gen_syncookie_proto;
8243 #ifdef CONFIG_SYN_COOKIES
8244         case BPF_FUNC_tcp_raw_gen_syncookie_ipv4:
8245                 return &bpf_tcp_raw_gen_syncookie_ipv4_proto;
8246         case BPF_FUNC_tcp_raw_gen_syncookie_ipv6:
8247                 return &bpf_tcp_raw_gen_syncookie_ipv6_proto;
8248         case BPF_FUNC_tcp_raw_check_syncookie_ipv4:
8249                 return &bpf_tcp_raw_check_syncookie_ipv4_proto;
8250         case BPF_FUNC_tcp_raw_check_syncookie_ipv6:
8251                 return &bpf_tcp_raw_check_syncookie_ipv6_proto;
8252 #endif
8253 #endif
8254         default:
8255                 return bpf_sk_base_func_proto(func_id);
8256         }
8257
8258 #if IS_MODULE(CONFIG_NF_CONNTRACK) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)
8259         /* The nf_conn___init type is used in the NF_CONNTRACK kfuncs. The
8260          * kfuncs are defined in two different modules, and we want to be able
8261          * to use them interchangably with the same BTF type ID. Because modules
8262          * can't de-duplicate BTF IDs between each other, we need the type to be
8263          * referenced in the vmlinux BTF or the verifier will get confused about
8264          * the different types. So we add this dummy type reference which will
8265          * be included in vmlinux BTF, allowing both modules to refer to the
8266          * same type ID.
8267          */
8268         BTF_TYPE_EMIT(struct nf_conn___init);
8269 #endif
8270 }
8271
8272 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
8273 const struct bpf_func_proto bpf_sock_hash_update_proto __weak;
8274
8275 static const struct bpf_func_proto *
8276 sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8277 {
8278         const struct bpf_func_proto *func_proto;
8279
8280         func_proto = cgroup_common_func_proto(func_id, prog);
8281         if (func_proto)
8282                 return func_proto;
8283
8284         switch (func_id) {
8285         case BPF_FUNC_setsockopt:
8286                 return &bpf_sock_ops_setsockopt_proto;
8287         case BPF_FUNC_getsockopt:
8288                 return &bpf_sock_ops_getsockopt_proto;
8289         case BPF_FUNC_sock_ops_cb_flags_set:
8290                 return &bpf_sock_ops_cb_flags_set_proto;
8291         case BPF_FUNC_sock_map_update:
8292                 return &bpf_sock_map_update_proto;
8293         case BPF_FUNC_sock_hash_update:
8294                 return &bpf_sock_hash_update_proto;
8295         case BPF_FUNC_get_socket_cookie:
8296                 return &bpf_get_socket_cookie_sock_ops_proto;
8297         case BPF_FUNC_perf_event_output:
8298                 return &bpf_event_output_data_proto;
8299         case BPF_FUNC_sk_storage_get:
8300                 return &bpf_sk_storage_get_proto;
8301         case BPF_FUNC_sk_storage_delete:
8302                 return &bpf_sk_storage_delete_proto;
8303         case BPF_FUNC_get_netns_cookie:
8304                 return &bpf_get_netns_cookie_sock_ops_proto;
8305 #ifdef CONFIG_INET
8306         case BPF_FUNC_load_hdr_opt:
8307                 return &bpf_sock_ops_load_hdr_opt_proto;
8308         case BPF_FUNC_store_hdr_opt:
8309                 return &bpf_sock_ops_store_hdr_opt_proto;
8310         case BPF_FUNC_reserve_hdr_opt:
8311                 return &bpf_sock_ops_reserve_hdr_opt_proto;
8312         case BPF_FUNC_tcp_sock:
8313                 return &bpf_tcp_sock_proto;
8314 #endif /* CONFIG_INET */
8315         default:
8316                 return bpf_sk_base_func_proto(func_id);
8317         }
8318 }
8319
8320 const struct bpf_func_proto bpf_msg_redirect_map_proto __weak;
8321 const struct bpf_func_proto bpf_msg_redirect_hash_proto __weak;
8322
8323 static const struct bpf_func_proto *
8324 sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8325 {
8326         switch (func_id) {
8327         case BPF_FUNC_msg_redirect_map:
8328                 return &bpf_msg_redirect_map_proto;
8329         case BPF_FUNC_msg_redirect_hash:
8330                 return &bpf_msg_redirect_hash_proto;
8331         case BPF_FUNC_msg_apply_bytes:
8332                 return &bpf_msg_apply_bytes_proto;
8333         case BPF_FUNC_msg_cork_bytes:
8334                 return &bpf_msg_cork_bytes_proto;
8335         case BPF_FUNC_msg_pull_data:
8336                 return &bpf_msg_pull_data_proto;
8337         case BPF_FUNC_msg_push_data:
8338                 return &bpf_msg_push_data_proto;
8339         case BPF_FUNC_msg_pop_data:
8340                 return &bpf_msg_pop_data_proto;
8341         case BPF_FUNC_perf_event_output:
8342                 return &bpf_event_output_data_proto;
8343         case BPF_FUNC_get_current_uid_gid:
8344                 return &bpf_get_current_uid_gid_proto;
8345         case BPF_FUNC_get_current_pid_tgid:
8346                 return &bpf_get_current_pid_tgid_proto;
8347         case BPF_FUNC_sk_storage_get:
8348                 return &bpf_sk_storage_get_proto;
8349         case BPF_FUNC_sk_storage_delete:
8350                 return &bpf_sk_storage_delete_proto;
8351         case BPF_FUNC_get_netns_cookie:
8352                 return &bpf_get_netns_cookie_sk_msg_proto;
8353 #ifdef CONFIG_CGROUP_NET_CLASSID
8354         case BPF_FUNC_get_cgroup_classid:
8355                 return &bpf_get_cgroup_classid_curr_proto;
8356 #endif
8357         default:
8358                 return bpf_sk_base_func_proto(func_id);
8359         }
8360 }
8361
8362 const struct bpf_func_proto bpf_sk_redirect_map_proto __weak;
8363 const struct bpf_func_proto bpf_sk_redirect_hash_proto __weak;
8364
8365 static const struct bpf_func_proto *
8366 sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8367 {
8368         switch (func_id) {
8369         case BPF_FUNC_skb_store_bytes:
8370                 return &bpf_skb_store_bytes_proto;
8371         case BPF_FUNC_skb_load_bytes:
8372                 return &bpf_skb_load_bytes_proto;
8373         case BPF_FUNC_skb_pull_data:
8374                 return &sk_skb_pull_data_proto;
8375         case BPF_FUNC_skb_change_tail:
8376                 return &sk_skb_change_tail_proto;
8377         case BPF_FUNC_skb_change_head:
8378                 return &sk_skb_change_head_proto;
8379         case BPF_FUNC_skb_adjust_room:
8380                 return &sk_skb_adjust_room_proto;
8381         case BPF_FUNC_get_socket_cookie:
8382                 return &bpf_get_socket_cookie_proto;
8383         case BPF_FUNC_get_socket_uid:
8384                 return &bpf_get_socket_uid_proto;
8385         case BPF_FUNC_sk_redirect_map:
8386                 return &bpf_sk_redirect_map_proto;
8387         case BPF_FUNC_sk_redirect_hash:
8388                 return &bpf_sk_redirect_hash_proto;
8389         case BPF_FUNC_perf_event_output:
8390                 return &bpf_skb_event_output_proto;
8391 #ifdef CONFIG_INET
8392         case BPF_FUNC_sk_lookup_tcp:
8393                 return &bpf_sk_lookup_tcp_proto;
8394         case BPF_FUNC_sk_lookup_udp:
8395                 return &bpf_sk_lookup_udp_proto;
8396         case BPF_FUNC_sk_release:
8397                 return &bpf_sk_release_proto;
8398         case BPF_FUNC_skc_lookup_tcp:
8399                 return &bpf_skc_lookup_tcp_proto;
8400 #endif
8401         default:
8402                 return bpf_sk_base_func_proto(func_id);
8403         }
8404 }
8405
8406 static const struct bpf_func_proto *
8407 flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8408 {
8409         switch (func_id) {
8410         case BPF_FUNC_skb_load_bytes:
8411                 return &bpf_flow_dissector_load_bytes_proto;
8412         default:
8413                 return bpf_sk_base_func_proto(func_id);
8414         }
8415 }
8416
8417 static const struct bpf_func_proto *
8418 lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8419 {
8420         switch (func_id) {
8421         case BPF_FUNC_skb_load_bytes:
8422                 return &bpf_skb_load_bytes_proto;
8423         case BPF_FUNC_skb_pull_data:
8424                 return &bpf_skb_pull_data_proto;
8425         case BPF_FUNC_csum_diff:
8426                 return &bpf_csum_diff_proto;
8427         case BPF_FUNC_get_cgroup_classid:
8428                 return &bpf_get_cgroup_classid_proto;
8429         case BPF_FUNC_get_route_realm:
8430                 return &bpf_get_route_realm_proto;
8431         case BPF_FUNC_get_hash_recalc:
8432                 return &bpf_get_hash_recalc_proto;
8433         case BPF_FUNC_perf_event_output:
8434                 return &bpf_skb_event_output_proto;
8435         case BPF_FUNC_get_smp_processor_id:
8436                 return &bpf_get_smp_processor_id_proto;
8437         case BPF_FUNC_skb_under_cgroup:
8438                 return &bpf_skb_under_cgroup_proto;
8439         default:
8440                 return bpf_sk_base_func_proto(func_id);
8441         }
8442 }
8443
8444 static const struct bpf_func_proto *
8445 lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8446 {
8447         switch (func_id) {
8448         case BPF_FUNC_lwt_push_encap:
8449                 return &bpf_lwt_in_push_encap_proto;
8450         default:
8451                 return lwt_out_func_proto(func_id, prog);
8452         }
8453 }
8454
8455 static const struct bpf_func_proto *
8456 lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8457 {
8458         switch (func_id) {
8459         case BPF_FUNC_skb_get_tunnel_key:
8460                 return &bpf_skb_get_tunnel_key_proto;
8461         case BPF_FUNC_skb_set_tunnel_key:
8462                 return bpf_get_skb_set_tunnel_proto(func_id);
8463         case BPF_FUNC_skb_get_tunnel_opt:
8464                 return &bpf_skb_get_tunnel_opt_proto;
8465         case BPF_FUNC_skb_set_tunnel_opt:
8466                 return bpf_get_skb_set_tunnel_proto(func_id);
8467         case BPF_FUNC_redirect:
8468                 return &bpf_redirect_proto;
8469         case BPF_FUNC_clone_redirect:
8470                 return &bpf_clone_redirect_proto;
8471         case BPF_FUNC_skb_change_tail:
8472                 return &bpf_skb_change_tail_proto;
8473         case BPF_FUNC_skb_change_head:
8474                 return &bpf_skb_change_head_proto;
8475         case BPF_FUNC_skb_store_bytes:
8476                 return &bpf_skb_store_bytes_proto;
8477         case BPF_FUNC_csum_update:
8478                 return &bpf_csum_update_proto;
8479         case BPF_FUNC_csum_level:
8480                 return &bpf_csum_level_proto;
8481         case BPF_FUNC_l3_csum_replace:
8482                 return &bpf_l3_csum_replace_proto;
8483         case BPF_FUNC_l4_csum_replace:
8484                 return &bpf_l4_csum_replace_proto;
8485         case BPF_FUNC_set_hash_invalid:
8486                 return &bpf_set_hash_invalid_proto;
8487         case BPF_FUNC_lwt_push_encap:
8488                 return &bpf_lwt_xmit_push_encap_proto;
8489         default:
8490                 return lwt_out_func_proto(func_id, prog);
8491         }
8492 }
8493
8494 static const struct bpf_func_proto *
8495 lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8496 {
8497         switch (func_id) {
8498 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
8499         case BPF_FUNC_lwt_seg6_store_bytes:
8500                 return &bpf_lwt_seg6_store_bytes_proto;
8501         case BPF_FUNC_lwt_seg6_action:
8502                 return &bpf_lwt_seg6_action_proto;
8503         case BPF_FUNC_lwt_seg6_adjust_srh:
8504                 return &bpf_lwt_seg6_adjust_srh_proto;
8505 #endif
8506         default:
8507                 return lwt_out_func_proto(func_id, prog);
8508         }
8509 }
8510
8511 static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
8512                                     const struct bpf_prog *prog,
8513                                     struct bpf_insn_access_aux *info)
8514 {
8515         const int size_default = sizeof(__u32);
8516
8517         if (off < 0 || off >= sizeof(struct __sk_buff))
8518                 return false;
8519
8520         /* The verifier guarantees that size > 0. */
8521         if (off % size != 0)
8522                 return false;
8523
8524         switch (off) {
8525         case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8526                 if (off + size > offsetofend(struct __sk_buff, cb[4]))
8527                         return false;
8528                 break;
8529         case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
8530         case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
8531         case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
8532         case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
8533         case bpf_ctx_range(struct __sk_buff, data):
8534         case bpf_ctx_range(struct __sk_buff, data_meta):
8535         case bpf_ctx_range(struct __sk_buff, data_end):
8536                 if (size != size_default)
8537                         return false;
8538                 break;
8539         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
8540                 return false;
8541         case bpf_ctx_range(struct __sk_buff, hwtstamp):
8542                 if (type == BPF_WRITE || size != sizeof(__u64))
8543                         return false;
8544                 break;
8545         case bpf_ctx_range(struct __sk_buff, tstamp):
8546                 if (size != sizeof(__u64))
8547                         return false;
8548                 break;
8549         case offsetof(struct __sk_buff, sk):
8550                 if (type == BPF_WRITE || size != sizeof(__u64))
8551                         return false;
8552                 info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
8553                 break;
8554         case offsetof(struct __sk_buff, tstamp_type):
8555                 return false;
8556         case offsetofend(struct __sk_buff, tstamp_type) ... offsetof(struct __sk_buff, hwtstamp) - 1:
8557                 /* Explicitly prohibit access to padding in __sk_buff. */
8558                 return false;
8559         default:
8560                 /* Only narrow read access allowed for now. */
8561                 if (type == BPF_WRITE) {
8562                         if (size != size_default)
8563                                 return false;
8564                 } else {
8565                         bpf_ctx_record_field_size(info, size_default);
8566                         if (!bpf_ctx_narrow_access_ok(off, size, size_default))
8567                                 return false;
8568                 }
8569         }
8570
8571         return true;
8572 }
8573
8574 static bool sk_filter_is_valid_access(int off, int size,
8575                                       enum bpf_access_type type,
8576                                       const struct bpf_prog *prog,
8577                                       struct bpf_insn_access_aux *info)
8578 {
8579         switch (off) {
8580         case bpf_ctx_range(struct __sk_buff, tc_classid):
8581         case bpf_ctx_range(struct __sk_buff, data):
8582         case bpf_ctx_range(struct __sk_buff, data_meta):
8583         case bpf_ctx_range(struct __sk_buff, data_end):
8584         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
8585         case bpf_ctx_range(struct __sk_buff, tstamp):
8586         case bpf_ctx_range(struct __sk_buff, wire_len):
8587         case bpf_ctx_range(struct __sk_buff, hwtstamp):
8588                 return false;
8589         }
8590
8591         if (type == BPF_WRITE) {
8592                 switch (off) {
8593                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8594                         break;
8595                 default:
8596                         return false;
8597                 }
8598         }
8599
8600         return bpf_skb_is_valid_access(off, size, type, prog, info);
8601 }
8602
8603 static bool cg_skb_is_valid_access(int off, int size,
8604                                    enum bpf_access_type type,
8605                                    const struct bpf_prog *prog,
8606                                    struct bpf_insn_access_aux *info)
8607 {
8608         switch (off) {
8609         case bpf_ctx_range(struct __sk_buff, tc_classid):
8610         case bpf_ctx_range(struct __sk_buff, data_meta):
8611         case bpf_ctx_range(struct __sk_buff, wire_len):
8612                 return false;
8613         case bpf_ctx_range(struct __sk_buff, data):
8614         case bpf_ctx_range(struct __sk_buff, data_end):
8615                 if (!bpf_capable())
8616                         return false;
8617                 break;
8618         }
8619
8620         if (type == BPF_WRITE) {
8621                 switch (off) {
8622                 case bpf_ctx_range(struct __sk_buff, mark):
8623                 case bpf_ctx_range(struct __sk_buff, priority):
8624                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8625                         break;
8626                 case bpf_ctx_range(struct __sk_buff, tstamp):
8627                         if (!bpf_capable())
8628                                 return false;
8629                         break;
8630                 default:
8631                         return false;
8632                 }
8633         }
8634
8635         switch (off) {
8636         case bpf_ctx_range(struct __sk_buff, data):
8637                 info->reg_type = PTR_TO_PACKET;
8638                 break;
8639         case bpf_ctx_range(struct __sk_buff, data_end):
8640                 info->reg_type = PTR_TO_PACKET_END;
8641                 break;
8642         }
8643
8644         return bpf_skb_is_valid_access(off, size, type, prog, info);
8645 }
8646
8647 static bool lwt_is_valid_access(int off, int size,
8648                                 enum bpf_access_type type,
8649                                 const struct bpf_prog *prog,
8650                                 struct bpf_insn_access_aux *info)
8651 {
8652         switch (off) {
8653         case bpf_ctx_range(struct __sk_buff, tc_classid):
8654         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
8655         case bpf_ctx_range(struct __sk_buff, data_meta):
8656         case bpf_ctx_range(struct __sk_buff, tstamp):
8657         case bpf_ctx_range(struct __sk_buff, wire_len):
8658         case bpf_ctx_range(struct __sk_buff, hwtstamp):
8659                 return false;
8660         }
8661
8662         if (type == BPF_WRITE) {
8663                 switch (off) {
8664                 case bpf_ctx_range(struct __sk_buff, mark):
8665                 case bpf_ctx_range(struct __sk_buff, priority):
8666                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8667                         break;
8668                 default:
8669                         return false;
8670                 }
8671         }
8672
8673         switch (off) {
8674         case bpf_ctx_range(struct __sk_buff, data):
8675                 info->reg_type = PTR_TO_PACKET;
8676                 break;
8677         case bpf_ctx_range(struct __sk_buff, data_end):
8678                 info->reg_type = PTR_TO_PACKET_END;
8679                 break;
8680         }
8681
8682         return bpf_skb_is_valid_access(off, size, type, prog, info);
8683 }
8684
8685 /* Attach type specific accesses */
8686 static bool __sock_filter_check_attach_type(int off,
8687                                             enum bpf_access_type access_type,
8688                                             enum bpf_attach_type attach_type)
8689 {
8690         switch (off) {
8691         case offsetof(struct bpf_sock, bound_dev_if):
8692         case offsetof(struct bpf_sock, mark):
8693         case offsetof(struct bpf_sock, priority):
8694                 switch (attach_type) {
8695                 case BPF_CGROUP_INET_SOCK_CREATE:
8696                 case BPF_CGROUP_INET_SOCK_RELEASE:
8697                         goto full_access;
8698                 default:
8699                         return false;
8700                 }
8701         case bpf_ctx_range(struct bpf_sock, src_ip4):
8702                 switch (attach_type) {
8703                 case BPF_CGROUP_INET4_POST_BIND:
8704                         goto read_only;
8705                 default:
8706                         return false;
8707                 }
8708         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
8709                 switch (attach_type) {
8710                 case BPF_CGROUP_INET6_POST_BIND:
8711                         goto read_only;
8712                 default:
8713                         return false;
8714                 }
8715         case bpf_ctx_range(struct bpf_sock, src_port):
8716                 switch (attach_type) {
8717                 case BPF_CGROUP_INET4_POST_BIND:
8718                 case BPF_CGROUP_INET6_POST_BIND:
8719                         goto read_only;
8720                 default:
8721                         return false;
8722                 }
8723         }
8724 read_only:
8725         return access_type == BPF_READ;
8726 full_access:
8727         return true;
8728 }
8729
8730 bool bpf_sock_common_is_valid_access(int off, int size,
8731                                      enum bpf_access_type type,
8732                                      struct bpf_insn_access_aux *info)
8733 {
8734         switch (off) {
8735         case bpf_ctx_range_till(struct bpf_sock, type, priority):
8736                 return false;
8737         default:
8738                 return bpf_sock_is_valid_access(off, size, type, info);
8739         }
8740 }
8741
8742 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
8743                               struct bpf_insn_access_aux *info)
8744 {
8745         const int size_default = sizeof(__u32);
8746         int field_size;
8747
8748         if (off < 0 || off >= sizeof(struct bpf_sock))
8749                 return false;
8750         if (off % size != 0)
8751                 return false;
8752
8753         switch (off) {
8754         case offsetof(struct bpf_sock, state):
8755         case offsetof(struct bpf_sock, family):
8756         case offsetof(struct bpf_sock, type):
8757         case offsetof(struct bpf_sock, protocol):
8758         case offsetof(struct bpf_sock, src_port):
8759         case offsetof(struct bpf_sock, rx_queue_mapping):
8760         case bpf_ctx_range(struct bpf_sock, src_ip4):
8761         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
8762         case bpf_ctx_range(struct bpf_sock, dst_ip4):
8763         case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
8764                 bpf_ctx_record_field_size(info, size_default);
8765                 return bpf_ctx_narrow_access_ok(off, size, size_default);
8766         case bpf_ctx_range(struct bpf_sock, dst_port):
8767                 field_size = size == size_default ?
8768                         size_default : sizeof_field(struct bpf_sock, dst_port);
8769                 bpf_ctx_record_field_size(info, field_size);
8770                 return bpf_ctx_narrow_access_ok(off, size, field_size);
8771         case offsetofend(struct bpf_sock, dst_port) ...
8772              offsetof(struct bpf_sock, dst_ip4) - 1:
8773                 return false;
8774         }
8775
8776         return size == size_default;
8777 }
8778
8779 static bool sock_filter_is_valid_access(int off, int size,
8780                                         enum bpf_access_type type,
8781                                         const struct bpf_prog *prog,
8782                                         struct bpf_insn_access_aux *info)
8783 {
8784         if (!bpf_sock_is_valid_access(off, size, type, info))
8785                 return false;
8786         return __sock_filter_check_attach_type(off, type,
8787                                                prog->expected_attach_type);
8788 }
8789
8790 static int bpf_noop_prologue(struct bpf_insn *insn_buf, bool direct_write,
8791                              const struct bpf_prog *prog)
8792 {
8793         /* Neither direct read nor direct write requires any preliminary
8794          * action.
8795          */
8796         return 0;
8797 }
8798
8799 static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
8800                                 const struct bpf_prog *prog, int drop_verdict)
8801 {
8802         struct bpf_insn *insn = insn_buf;
8803
8804         if (!direct_write)
8805                 return 0;
8806
8807         /* if (!skb->cloned)
8808          *       goto start;
8809          *
8810          * (Fast-path, otherwise approximation that we might be
8811          *  a clone, do the rest in helper.)
8812          */
8813         *insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET);
8814         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
8815         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
8816
8817         /* ret = bpf_skb_pull_data(skb, 0); */
8818         *insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
8819         *insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
8820         *insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
8821                                BPF_FUNC_skb_pull_data);
8822         /* if (!ret)
8823          *      goto restore;
8824          * return TC_ACT_SHOT;
8825          */
8826         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
8827         *insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
8828         *insn++ = BPF_EXIT_INSN();
8829
8830         /* restore: */
8831         *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
8832         /* start: */
8833         *insn++ = prog->insnsi[0];
8834
8835         return insn - insn_buf;
8836 }
8837
8838 static int bpf_gen_ld_abs(const struct bpf_insn *orig,
8839                           struct bpf_insn *insn_buf)
8840 {
8841         bool indirect = BPF_MODE(orig->code) == BPF_IND;
8842         struct bpf_insn *insn = insn_buf;
8843
8844         if (!indirect) {
8845                 *insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
8846         } else {
8847                 *insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
8848                 if (orig->imm)
8849                         *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
8850         }
8851         /* We're guaranteed here that CTX is in R6. */
8852         *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
8853
8854         switch (BPF_SIZE(orig->code)) {
8855         case BPF_B:
8856                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
8857                 break;
8858         case BPF_H:
8859                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
8860                 break;
8861         case BPF_W:
8862                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
8863                 break;
8864         }
8865
8866         *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
8867         *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
8868         *insn++ = BPF_EXIT_INSN();
8869
8870         return insn - insn_buf;
8871 }
8872
8873 static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
8874                                const struct bpf_prog *prog)
8875 {
8876         return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
8877 }
8878
8879 static bool tc_cls_act_is_valid_access(int off, int size,
8880                                        enum bpf_access_type type,
8881                                        const struct bpf_prog *prog,
8882                                        struct bpf_insn_access_aux *info)
8883 {
8884         if (type == BPF_WRITE) {
8885                 switch (off) {
8886                 case bpf_ctx_range(struct __sk_buff, mark):
8887                 case bpf_ctx_range(struct __sk_buff, tc_index):
8888                 case bpf_ctx_range(struct __sk_buff, priority):
8889                 case bpf_ctx_range(struct __sk_buff, tc_classid):
8890                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8891                 case bpf_ctx_range(struct __sk_buff, tstamp):
8892                 case bpf_ctx_range(struct __sk_buff, queue_mapping):
8893                         break;
8894                 default:
8895                         return false;
8896                 }
8897         }
8898
8899         switch (off) {
8900         case bpf_ctx_range(struct __sk_buff, data):
8901                 info->reg_type = PTR_TO_PACKET;
8902                 break;
8903         case bpf_ctx_range(struct __sk_buff, data_meta):
8904                 info->reg_type = PTR_TO_PACKET_META;
8905                 break;
8906         case bpf_ctx_range(struct __sk_buff, data_end):
8907                 info->reg_type = PTR_TO_PACKET_END;
8908                 break;
8909         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
8910                 return false;
8911         case offsetof(struct __sk_buff, tstamp_type):
8912                 /* The convert_ctx_access() on reading and writing
8913                  * __sk_buff->tstamp depends on whether the bpf prog
8914                  * has used __sk_buff->tstamp_type or not.
8915                  * Thus, we need to set prog->tstamp_type_access
8916                  * earlier during is_valid_access() here.
8917                  */
8918                 ((struct bpf_prog *)prog)->tstamp_type_access = 1;
8919                 return size == sizeof(__u8);
8920         }
8921
8922         return bpf_skb_is_valid_access(off, size, type, prog, info);
8923 }
8924
8925 DEFINE_MUTEX(nf_conn_btf_access_lock);
8926 EXPORT_SYMBOL_GPL(nf_conn_btf_access_lock);
8927
8928 int (*nfct_btf_struct_access)(struct bpf_verifier_log *log,
8929                               const struct bpf_reg_state *reg,
8930                               int off, int size);
8931 EXPORT_SYMBOL_GPL(nfct_btf_struct_access);
8932
8933 static int tc_cls_act_btf_struct_access(struct bpf_verifier_log *log,
8934                                         const struct bpf_reg_state *reg,
8935                                         int off, int size)
8936 {
8937         int ret = -EACCES;
8938
8939         mutex_lock(&nf_conn_btf_access_lock);
8940         if (nfct_btf_struct_access)
8941                 ret = nfct_btf_struct_access(log, reg, off, size);
8942         mutex_unlock(&nf_conn_btf_access_lock);
8943
8944         return ret;
8945 }
8946
8947 static bool __is_valid_xdp_access(int off, int size)
8948 {
8949         if (off < 0 || off >= sizeof(struct xdp_md))
8950                 return false;
8951         if (off % size != 0)
8952                 return false;
8953         if (size != sizeof(__u32))
8954                 return false;
8955
8956         return true;
8957 }
8958
8959 static bool xdp_is_valid_access(int off, int size,
8960                                 enum bpf_access_type type,
8961                                 const struct bpf_prog *prog,
8962                                 struct bpf_insn_access_aux *info)
8963 {
8964         if (prog->expected_attach_type != BPF_XDP_DEVMAP) {
8965                 switch (off) {
8966                 case offsetof(struct xdp_md, egress_ifindex):
8967                         return false;
8968                 }
8969         }
8970
8971         if (type == BPF_WRITE) {
8972                 if (bpf_prog_is_offloaded(prog->aux)) {
8973                         switch (off) {
8974                         case offsetof(struct xdp_md, rx_queue_index):
8975                                 return __is_valid_xdp_access(off, size);
8976                         }
8977                 }
8978                 return false;
8979         }
8980
8981         switch (off) {
8982         case offsetof(struct xdp_md, data):
8983                 info->reg_type = PTR_TO_PACKET;
8984                 break;
8985         case offsetof(struct xdp_md, data_meta):
8986                 info->reg_type = PTR_TO_PACKET_META;
8987                 break;
8988         case offsetof(struct xdp_md, data_end):
8989                 info->reg_type = PTR_TO_PACKET_END;
8990                 break;
8991         }
8992
8993         return __is_valid_xdp_access(off, size);
8994 }
8995
8996 void bpf_warn_invalid_xdp_action(struct net_device *dev, struct bpf_prog *prog, u32 act)
8997 {
8998         const u32 act_max = XDP_REDIRECT;
8999
9000         pr_warn_once("%s XDP return value %u on prog %s (id %d) dev %s, expect packet loss!\n",
9001                      act > act_max ? "Illegal" : "Driver unsupported",
9002                      act, prog->aux->name, prog->aux->id, dev ? dev->name : "N/A");
9003 }
9004 EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
9005
9006 static int xdp_btf_struct_access(struct bpf_verifier_log *log,
9007                                  const struct bpf_reg_state *reg,
9008                                  int off, int size)
9009 {
9010         int ret = -EACCES;
9011
9012         mutex_lock(&nf_conn_btf_access_lock);
9013         if (nfct_btf_struct_access)
9014                 ret = nfct_btf_struct_access(log, reg, off, size);
9015         mutex_unlock(&nf_conn_btf_access_lock);
9016
9017         return ret;
9018 }
9019
9020 static bool sock_addr_is_valid_access(int off, int size,
9021                                       enum bpf_access_type type,
9022                                       const struct bpf_prog *prog,
9023                                       struct bpf_insn_access_aux *info)
9024 {
9025         const int size_default = sizeof(__u32);
9026
9027         if (off < 0 || off >= sizeof(struct bpf_sock_addr))
9028                 return false;
9029         if (off % size != 0)
9030                 return false;
9031
9032         /* Disallow access to fields not belonging to the attach type's address
9033          * family.
9034          */
9035         switch (off) {
9036         case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
9037                 switch (prog->expected_attach_type) {
9038                 case BPF_CGROUP_INET4_BIND:
9039                 case BPF_CGROUP_INET4_CONNECT:
9040                 case BPF_CGROUP_INET4_GETPEERNAME:
9041                 case BPF_CGROUP_INET4_GETSOCKNAME:
9042                 case BPF_CGROUP_UDP4_SENDMSG:
9043                 case BPF_CGROUP_UDP4_RECVMSG:
9044                         break;
9045                 default:
9046                         return false;
9047                 }
9048                 break;
9049         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
9050                 switch (prog->expected_attach_type) {
9051                 case BPF_CGROUP_INET6_BIND:
9052                 case BPF_CGROUP_INET6_CONNECT:
9053                 case BPF_CGROUP_INET6_GETPEERNAME:
9054                 case BPF_CGROUP_INET6_GETSOCKNAME:
9055                 case BPF_CGROUP_UDP6_SENDMSG:
9056                 case BPF_CGROUP_UDP6_RECVMSG:
9057                         break;
9058                 default:
9059                         return false;
9060                 }
9061                 break;
9062         case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
9063                 switch (prog->expected_attach_type) {
9064                 case BPF_CGROUP_UDP4_SENDMSG:
9065                         break;
9066                 default:
9067                         return false;
9068                 }
9069                 break;
9070         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
9071                                 msg_src_ip6[3]):
9072                 switch (prog->expected_attach_type) {
9073                 case BPF_CGROUP_UDP6_SENDMSG:
9074                         break;
9075                 default:
9076                         return false;
9077                 }
9078                 break;
9079         }
9080
9081         switch (off) {
9082         case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
9083         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
9084         case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
9085         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
9086                                 msg_src_ip6[3]):
9087         case bpf_ctx_range(struct bpf_sock_addr, user_port):
9088                 if (type == BPF_READ) {
9089                         bpf_ctx_record_field_size(info, size_default);
9090
9091                         if (bpf_ctx_wide_access_ok(off, size,
9092                                                    struct bpf_sock_addr,
9093                                                    user_ip6))
9094                                 return true;
9095
9096                         if (bpf_ctx_wide_access_ok(off, size,
9097                                                    struct bpf_sock_addr,
9098                                                    msg_src_ip6))
9099                                 return true;
9100
9101                         if (!bpf_ctx_narrow_access_ok(off, size, size_default))
9102                                 return false;
9103                 } else {
9104                         if (bpf_ctx_wide_access_ok(off, size,
9105                                                    struct bpf_sock_addr,
9106                                                    user_ip6))
9107                                 return true;
9108
9109                         if (bpf_ctx_wide_access_ok(off, size,
9110                                                    struct bpf_sock_addr,
9111                                                    msg_src_ip6))
9112                                 return true;
9113
9114                         if (size != size_default)
9115                                 return false;
9116                 }
9117                 break;
9118         case offsetof(struct bpf_sock_addr, sk):
9119                 if (type != BPF_READ)
9120                         return false;
9121                 if (size != sizeof(__u64))
9122                         return false;
9123                 info->reg_type = PTR_TO_SOCKET;
9124                 break;
9125         default:
9126                 if (type == BPF_READ) {
9127                         if (size != size_default)
9128                                 return false;
9129                 } else {
9130                         return false;
9131                 }
9132         }
9133
9134         return true;
9135 }
9136
9137 static bool sock_ops_is_valid_access(int off, int size,
9138                                      enum bpf_access_type type,
9139                                      const struct bpf_prog *prog,
9140                                      struct bpf_insn_access_aux *info)
9141 {
9142         const int size_default = sizeof(__u32);
9143
9144         if (off < 0 || off >= sizeof(struct bpf_sock_ops))
9145                 return false;
9146
9147         /* The verifier guarantees that size > 0. */
9148         if (off % size != 0)
9149                 return false;
9150
9151         if (type == BPF_WRITE) {
9152                 switch (off) {
9153                 case offsetof(struct bpf_sock_ops, reply):
9154                 case offsetof(struct bpf_sock_ops, sk_txhash):
9155                         if (size != size_default)
9156                                 return false;
9157                         break;
9158                 default:
9159                         return false;
9160                 }
9161         } else {
9162                 switch (off) {
9163                 case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received,
9164                                         bytes_acked):
9165                         if (size != sizeof(__u64))
9166                                 return false;
9167                         break;
9168                 case offsetof(struct bpf_sock_ops, sk):
9169                         if (size != sizeof(__u64))
9170                                 return false;
9171                         info->reg_type = PTR_TO_SOCKET_OR_NULL;
9172                         break;
9173                 case offsetof(struct bpf_sock_ops, skb_data):
9174                         if (size != sizeof(__u64))
9175                                 return false;
9176                         info->reg_type = PTR_TO_PACKET;
9177                         break;
9178                 case offsetof(struct bpf_sock_ops, skb_data_end):
9179                         if (size != sizeof(__u64))
9180                                 return false;
9181                         info->reg_type = PTR_TO_PACKET_END;
9182                         break;
9183                 case offsetof(struct bpf_sock_ops, skb_tcp_flags):
9184                         bpf_ctx_record_field_size(info, size_default);
9185                         return bpf_ctx_narrow_access_ok(off, size,
9186                                                         size_default);
9187                 case offsetof(struct bpf_sock_ops, skb_hwtstamp):
9188                         if (size != sizeof(__u64))
9189                                 return false;
9190                         break;
9191                 default:
9192                         if (size != size_default)
9193                                 return false;
9194                         break;
9195                 }
9196         }
9197
9198         return true;
9199 }
9200
9201 static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
9202                            const struct bpf_prog *prog)
9203 {
9204         return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
9205 }
9206
9207 static bool sk_skb_is_valid_access(int off, int size,
9208                                    enum bpf_access_type type,
9209                                    const struct bpf_prog *prog,
9210                                    struct bpf_insn_access_aux *info)
9211 {
9212         switch (off) {
9213         case bpf_ctx_range(struct __sk_buff, tc_classid):
9214         case bpf_ctx_range(struct __sk_buff, data_meta):
9215         case bpf_ctx_range(struct __sk_buff, tstamp):
9216         case bpf_ctx_range(struct __sk_buff, wire_len):
9217         case bpf_ctx_range(struct __sk_buff, hwtstamp):
9218                 return false;
9219         }
9220
9221         if (type == BPF_WRITE) {
9222                 switch (off) {
9223                 case bpf_ctx_range(struct __sk_buff, tc_index):
9224                 case bpf_ctx_range(struct __sk_buff, priority):
9225                         break;
9226                 default:
9227                         return false;
9228                 }
9229         }
9230
9231         switch (off) {
9232         case bpf_ctx_range(struct __sk_buff, mark):
9233                 return false;
9234         case bpf_ctx_range(struct __sk_buff, data):
9235                 info->reg_type = PTR_TO_PACKET;
9236                 break;
9237         case bpf_ctx_range(struct __sk_buff, data_end):
9238                 info->reg_type = PTR_TO_PACKET_END;
9239                 break;
9240         }
9241
9242         return bpf_skb_is_valid_access(off, size, type, prog, info);
9243 }
9244
9245 static bool sk_msg_is_valid_access(int off, int size,
9246                                    enum bpf_access_type type,
9247                                    const struct bpf_prog *prog,
9248                                    struct bpf_insn_access_aux *info)
9249 {
9250         if (type == BPF_WRITE)
9251                 return false;
9252
9253         if (off % size != 0)
9254                 return false;
9255
9256         switch (off) {
9257         case offsetof(struct sk_msg_md, data):
9258                 info->reg_type = PTR_TO_PACKET;
9259                 if (size != sizeof(__u64))
9260                         return false;
9261                 break;
9262         case offsetof(struct sk_msg_md, data_end):
9263                 info->reg_type = PTR_TO_PACKET_END;
9264                 if (size != sizeof(__u64))
9265                         return false;
9266                 break;
9267         case offsetof(struct sk_msg_md, sk):
9268                 if (size != sizeof(__u64))
9269                         return false;
9270                 info->reg_type = PTR_TO_SOCKET;
9271                 break;
9272         case bpf_ctx_range(struct sk_msg_md, family):
9273         case bpf_ctx_range(struct sk_msg_md, remote_ip4):
9274         case bpf_ctx_range(struct sk_msg_md, local_ip4):
9275         case bpf_ctx_range_till(struct sk_msg_md, remote_ip6[0], remote_ip6[3]):
9276         case bpf_ctx_range_till(struct sk_msg_md, local_ip6[0], local_ip6[3]):
9277         case bpf_ctx_range(struct sk_msg_md, remote_port):
9278         case bpf_ctx_range(struct sk_msg_md, local_port):
9279         case bpf_ctx_range(struct sk_msg_md, size):
9280                 if (size != sizeof(__u32))
9281                         return false;
9282                 break;
9283         default:
9284                 return false;
9285         }
9286         return true;
9287 }
9288
9289 static bool flow_dissector_is_valid_access(int off, int size,
9290                                            enum bpf_access_type type,
9291                                            const struct bpf_prog *prog,
9292                                            struct bpf_insn_access_aux *info)
9293 {
9294         const int size_default = sizeof(__u32);
9295
9296         if (off < 0 || off >= sizeof(struct __sk_buff))
9297                 return false;
9298
9299         if (type == BPF_WRITE)
9300                 return false;
9301
9302         switch (off) {
9303         case bpf_ctx_range(struct __sk_buff, data):
9304                 if (size != size_default)
9305                         return false;
9306                 info->reg_type = PTR_TO_PACKET;
9307                 return true;
9308         case bpf_ctx_range(struct __sk_buff, data_end):
9309                 if (size != size_default)
9310                         return false;
9311                 info->reg_type = PTR_TO_PACKET_END;
9312                 return true;
9313         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
9314                 if (size != sizeof(__u64))
9315                         return false;
9316                 info->reg_type = PTR_TO_FLOW_KEYS;
9317                 return true;
9318         default:
9319                 return false;
9320         }
9321 }
9322
9323 static u32 flow_dissector_convert_ctx_access(enum bpf_access_type type,
9324                                              const struct bpf_insn *si,
9325                                              struct bpf_insn *insn_buf,
9326                                              struct bpf_prog *prog,
9327                                              u32 *target_size)
9328
9329 {
9330         struct bpf_insn *insn = insn_buf;
9331
9332         switch (si->off) {
9333         case offsetof(struct __sk_buff, data):
9334                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data),
9335                                       si->dst_reg, si->src_reg,
9336                                       offsetof(struct bpf_flow_dissector, data));
9337                 break;
9338
9339         case offsetof(struct __sk_buff, data_end):
9340                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data_end),
9341                                       si->dst_reg, si->src_reg,
9342                                       offsetof(struct bpf_flow_dissector, data_end));
9343                 break;
9344
9345         case offsetof(struct __sk_buff, flow_keys):
9346                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, flow_keys),
9347                                       si->dst_reg, si->src_reg,
9348                                       offsetof(struct bpf_flow_dissector, flow_keys));
9349                 break;
9350         }
9351
9352         return insn - insn_buf;
9353 }
9354
9355 static struct bpf_insn *bpf_convert_tstamp_type_read(const struct bpf_insn *si,
9356                                                      struct bpf_insn *insn)
9357 {
9358         __u8 value_reg = si->dst_reg;
9359         __u8 skb_reg = si->src_reg;
9360         /* AX is needed because src_reg and dst_reg could be the same */
9361         __u8 tmp_reg = BPF_REG_AX;
9362
9363         *insn++ = BPF_LDX_MEM(BPF_B, tmp_reg, skb_reg,
9364                               SKB_BF_MONO_TC_OFFSET);
9365         *insn++ = BPF_JMP32_IMM(BPF_JSET, tmp_reg,
9366                                 SKB_MONO_DELIVERY_TIME_MASK, 2);
9367         *insn++ = BPF_MOV32_IMM(value_reg, BPF_SKB_TSTAMP_UNSPEC);
9368         *insn++ = BPF_JMP_A(1);
9369         *insn++ = BPF_MOV32_IMM(value_reg, BPF_SKB_TSTAMP_DELIVERY_MONO);
9370
9371         return insn;
9372 }
9373
9374 static struct bpf_insn *bpf_convert_shinfo_access(__u8 dst_reg, __u8 skb_reg,
9375                                                   struct bpf_insn *insn)
9376 {
9377         /* si->dst_reg = skb_shinfo(SKB); */
9378 #ifdef NET_SKBUFF_DATA_USES_OFFSET
9379         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
9380                               BPF_REG_AX, skb_reg,
9381                               offsetof(struct sk_buff, end));
9382         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, head),
9383                               dst_reg, skb_reg,
9384                               offsetof(struct sk_buff, head));
9385         *insn++ = BPF_ALU64_REG(BPF_ADD, dst_reg, BPF_REG_AX);
9386 #else
9387         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
9388                               dst_reg, skb_reg,
9389                               offsetof(struct sk_buff, end));
9390 #endif
9391
9392         return insn;
9393 }
9394
9395 static struct bpf_insn *bpf_convert_tstamp_read(const struct bpf_prog *prog,
9396                                                 const struct bpf_insn *si,
9397                                                 struct bpf_insn *insn)
9398 {
9399         __u8 value_reg = si->dst_reg;
9400         __u8 skb_reg = si->src_reg;
9401
9402 #ifdef CONFIG_NET_XGRESS
9403         /* If the tstamp_type is read,
9404          * the bpf prog is aware the tstamp could have delivery time.
9405          * Thus, read skb->tstamp as is if tstamp_type_access is true.
9406          */
9407         if (!prog->tstamp_type_access) {
9408                 /* AX is needed because src_reg and dst_reg could be the same */
9409                 __u8 tmp_reg = BPF_REG_AX;
9410
9411                 *insn++ = BPF_LDX_MEM(BPF_B, tmp_reg, skb_reg, SKB_BF_MONO_TC_OFFSET);
9412                 *insn++ = BPF_ALU32_IMM(BPF_AND, tmp_reg,
9413                                         TC_AT_INGRESS_MASK | SKB_MONO_DELIVERY_TIME_MASK);
9414                 *insn++ = BPF_JMP32_IMM(BPF_JNE, tmp_reg,
9415                                         TC_AT_INGRESS_MASK | SKB_MONO_DELIVERY_TIME_MASK, 2);
9416                 /* skb->tc_at_ingress && skb->mono_delivery_time,
9417                  * read 0 as the (rcv) timestamp.
9418                  */
9419                 *insn++ = BPF_MOV64_IMM(value_reg, 0);
9420                 *insn++ = BPF_JMP_A(1);
9421         }
9422 #endif
9423
9424         *insn++ = BPF_LDX_MEM(BPF_DW, value_reg, skb_reg,
9425                               offsetof(struct sk_buff, tstamp));
9426         return insn;
9427 }
9428
9429 static struct bpf_insn *bpf_convert_tstamp_write(const struct bpf_prog *prog,
9430                                                  const struct bpf_insn *si,
9431                                                  struct bpf_insn *insn)
9432 {
9433         __u8 value_reg = si->src_reg;
9434         __u8 skb_reg = si->dst_reg;
9435
9436 #ifdef CONFIG_NET_XGRESS
9437         /* If the tstamp_type is read,
9438          * the bpf prog is aware the tstamp could have delivery time.
9439          * Thus, write skb->tstamp as is if tstamp_type_access is true.
9440          * Otherwise, writing at ingress will have to clear the
9441          * mono_delivery_time bit also.
9442          */
9443         if (!prog->tstamp_type_access) {
9444                 __u8 tmp_reg = BPF_REG_AX;
9445
9446                 *insn++ = BPF_LDX_MEM(BPF_B, tmp_reg, skb_reg, SKB_BF_MONO_TC_OFFSET);
9447                 /* Writing __sk_buff->tstamp as ingress, goto <clear> */
9448                 *insn++ = BPF_JMP32_IMM(BPF_JSET, tmp_reg, TC_AT_INGRESS_MASK, 1);
9449                 /* goto <store> */
9450                 *insn++ = BPF_JMP_A(2);
9451                 /* <clear>: mono_delivery_time */
9452                 *insn++ = BPF_ALU32_IMM(BPF_AND, tmp_reg, ~SKB_MONO_DELIVERY_TIME_MASK);
9453                 *insn++ = BPF_STX_MEM(BPF_B, skb_reg, tmp_reg, SKB_BF_MONO_TC_OFFSET);
9454         }
9455 #endif
9456
9457         /* <store>: skb->tstamp = tstamp */
9458         *insn++ = BPF_RAW_INSN(BPF_CLASS(si->code) | BPF_DW | BPF_MEM,
9459                                skb_reg, value_reg, offsetof(struct sk_buff, tstamp), si->imm);
9460         return insn;
9461 }
9462
9463 #define BPF_EMIT_STORE(size, si, off)                                   \
9464         BPF_RAW_INSN(BPF_CLASS((si)->code) | (size) | BPF_MEM,          \
9465                      (si)->dst_reg, (si)->src_reg, (off), (si)->imm)
9466
9467 static u32 bpf_convert_ctx_access(enum bpf_access_type type,
9468                                   const struct bpf_insn *si,
9469                                   struct bpf_insn *insn_buf,
9470                                   struct bpf_prog *prog, u32 *target_size)
9471 {
9472         struct bpf_insn *insn = insn_buf;
9473         int off;
9474
9475         switch (si->off) {
9476         case offsetof(struct __sk_buff, len):
9477                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9478                                       bpf_target_off(struct sk_buff, len, 4,
9479                                                      target_size));
9480                 break;
9481
9482         case offsetof(struct __sk_buff, protocol):
9483                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
9484                                       bpf_target_off(struct sk_buff, protocol, 2,
9485                                                      target_size));
9486                 break;
9487
9488         case offsetof(struct __sk_buff, vlan_proto):
9489                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
9490                                       bpf_target_off(struct sk_buff, vlan_proto, 2,
9491                                                      target_size));
9492                 break;
9493
9494         case offsetof(struct __sk_buff, priority):
9495                 if (type == BPF_WRITE)
9496                         *insn++ = BPF_EMIT_STORE(BPF_W, si,
9497                                                  bpf_target_off(struct sk_buff, priority, 4,
9498                                                                 target_size));
9499                 else
9500                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9501                                               bpf_target_off(struct sk_buff, priority, 4,
9502                                                              target_size));
9503                 break;
9504
9505         case offsetof(struct __sk_buff, ingress_ifindex):
9506                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9507                                       bpf_target_off(struct sk_buff, skb_iif, 4,
9508                                                      target_size));
9509                 break;
9510
9511         case offsetof(struct __sk_buff, ifindex):
9512                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
9513                                       si->dst_reg, si->src_reg,
9514                                       offsetof(struct sk_buff, dev));
9515                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
9516                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
9517                                       bpf_target_off(struct net_device, ifindex, 4,
9518                                                      target_size));
9519                 break;
9520
9521         case offsetof(struct __sk_buff, hash):
9522                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9523                                       bpf_target_off(struct sk_buff, hash, 4,
9524                                                      target_size));
9525                 break;
9526
9527         case offsetof(struct __sk_buff, mark):
9528                 if (type == BPF_WRITE)
9529                         *insn++ = BPF_EMIT_STORE(BPF_W, si,
9530                                                  bpf_target_off(struct sk_buff, mark, 4,
9531                                                                 target_size));
9532                 else
9533                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9534                                               bpf_target_off(struct sk_buff, mark, 4,
9535                                                              target_size));
9536                 break;
9537
9538         case offsetof(struct __sk_buff, pkt_type):
9539                 *target_size = 1;
9540                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
9541                                       PKT_TYPE_OFFSET);
9542                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
9543 #ifdef __BIG_ENDIAN_BITFIELD
9544                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
9545 #endif
9546                 break;
9547
9548         case offsetof(struct __sk_buff, queue_mapping):
9549                 if (type == BPF_WRITE) {
9550                         u32 off = bpf_target_off(struct sk_buff, queue_mapping, 2, target_size);
9551
9552                         if (BPF_CLASS(si->code) == BPF_ST && si->imm >= NO_QUEUE_MAPPING) {
9553                                 *insn++ = BPF_JMP_A(0); /* noop */
9554                                 break;
9555                         }
9556
9557                         if (BPF_CLASS(si->code) == BPF_STX)
9558                                 *insn++ = BPF_JMP_IMM(BPF_JGE, si->src_reg, NO_QUEUE_MAPPING, 1);
9559                         *insn++ = BPF_EMIT_STORE(BPF_H, si, off);
9560                 } else {
9561                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
9562                                               bpf_target_off(struct sk_buff,
9563                                                              queue_mapping,
9564                                                              2, target_size));
9565                 }
9566                 break;
9567
9568         case offsetof(struct __sk_buff, vlan_present):
9569                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9570                                       bpf_target_off(struct sk_buff,
9571                                                      vlan_all, 4, target_size));
9572                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
9573                 *insn++ = BPF_ALU32_IMM(BPF_MOV, si->dst_reg, 1);
9574                 break;
9575
9576         case offsetof(struct __sk_buff, vlan_tci):
9577                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
9578                                       bpf_target_off(struct sk_buff, vlan_tci, 2,
9579                                                      target_size));
9580                 break;
9581
9582         case offsetof(struct __sk_buff, cb[0]) ...
9583              offsetofend(struct __sk_buff, cb[4]) - 1:
9584                 BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, data) < 20);
9585                 BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
9586                               offsetof(struct qdisc_skb_cb, data)) %
9587                              sizeof(__u64));
9588
9589                 prog->cb_access = 1;
9590                 off  = si->off;
9591                 off -= offsetof(struct __sk_buff, cb[0]);
9592                 off += offsetof(struct sk_buff, cb);
9593                 off += offsetof(struct qdisc_skb_cb, data);
9594                 if (type == BPF_WRITE)
9595                         *insn++ = BPF_EMIT_STORE(BPF_SIZE(si->code), si, off);
9596                 else
9597                         *insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
9598                                               si->src_reg, off);
9599                 break;
9600
9601         case offsetof(struct __sk_buff, tc_classid):
9602                 BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, tc_classid) != 2);
9603
9604                 off  = si->off;
9605                 off -= offsetof(struct __sk_buff, tc_classid);
9606                 off += offsetof(struct sk_buff, cb);
9607                 off += offsetof(struct qdisc_skb_cb, tc_classid);
9608                 *target_size = 2;
9609                 if (type == BPF_WRITE)
9610                         *insn++ = BPF_EMIT_STORE(BPF_H, si, off);
9611                 else
9612                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
9613                                               si->src_reg, off);
9614                 break;
9615
9616         case offsetof(struct __sk_buff, data):
9617                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
9618                                       si->dst_reg, si->src_reg,
9619                                       offsetof(struct sk_buff, data));
9620                 break;
9621
9622         case offsetof(struct __sk_buff, data_meta):
9623                 off  = si->off;
9624                 off -= offsetof(struct __sk_buff, data_meta);
9625                 off += offsetof(struct sk_buff, cb);
9626                 off += offsetof(struct bpf_skb_data_end, data_meta);
9627                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
9628                                       si->src_reg, off);
9629                 break;
9630
9631         case offsetof(struct __sk_buff, data_end):
9632                 off  = si->off;
9633                 off -= offsetof(struct __sk_buff, data_end);
9634                 off += offsetof(struct sk_buff, cb);
9635                 off += offsetof(struct bpf_skb_data_end, data_end);
9636                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
9637                                       si->src_reg, off);
9638                 break;
9639
9640         case offsetof(struct __sk_buff, tc_index):
9641 #ifdef CONFIG_NET_SCHED
9642                 if (type == BPF_WRITE)
9643                         *insn++ = BPF_EMIT_STORE(BPF_H, si,
9644                                                  bpf_target_off(struct sk_buff, tc_index, 2,
9645                                                                 target_size));
9646                 else
9647                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
9648                                               bpf_target_off(struct sk_buff, tc_index, 2,
9649                                                              target_size));
9650 #else
9651                 *target_size = 2;
9652                 if (type == BPF_WRITE)
9653                         *insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
9654                 else
9655                         *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
9656 #endif
9657                 break;
9658
9659         case offsetof(struct __sk_buff, napi_id):
9660 #if defined(CONFIG_NET_RX_BUSY_POLL)
9661                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9662                                       bpf_target_off(struct sk_buff, napi_id, 4,
9663                                                      target_size));
9664                 *insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
9665                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
9666 #else
9667                 *target_size = 4;
9668                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
9669 #endif
9670                 break;
9671         case offsetof(struct __sk_buff, family):
9672                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
9673
9674                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9675                                       si->dst_reg, si->src_reg,
9676                                       offsetof(struct sk_buff, sk));
9677                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
9678                                       bpf_target_off(struct sock_common,
9679                                                      skc_family,
9680                                                      2, target_size));
9681                 break;
9682         case offsetof(struct __sk_buff, remote_ip4):
9683                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
9684
9685                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9686                                       si->dst_reg, si->src_reg,
9687                                       offsetof(struct sk_buff, sk));
9688                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
9689                                       bpf_target_off(struct sock_common,
9690                                                      skc_daddr,
9691                                                      4, target_size));
9692                 break;
9693         case offsetof(struct __sk_buff, local_ip4):
9694                 BUILD_BUG_ON(sizeof_field(struct sock_common,
9695                                           skc_rcv_saddr) != 4);
9696
9697                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9698                                       si->dst_reg, si->src_reg,
9699                                       offsetof(struct sk_buff, sk));
9700                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
9701                                       bpf_target_off(struct sock_common,
9702                                                      skc_rcv_saddr,
9703                                                      4, target_size));
9704                 break;
9705         case offsetof(struct __sk_buff, remote_ip6[0]) ...
9706              offsetof(struct __sk_buff, remote_ip6[3]):
9707 #if IS_ENABLED(CONFIG_IPV6)
9708                 BUILD_BUG_ON(sizeof_field(struct sock_common,
9709                                           skc_v6_daddr.s6_addr32[0]) != 4);
9710
9711                 off = si->off;
9712                 off -= offsetof(struct __sk_buff, remote_ip6[0]);
9713
9714                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9715                                       si->dst_reg, si->src_reg,
9716                                       offsetof(struct sk_buff, sk));
9717                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
9718                                       offsetof(struct sock_common,
9719                                                skc_v6_daddr.s6_addr32[0]) +
9720                                       off);
9721 #else
9722                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
9723 #endif
9724                 break;
9725         case offsetof(struct __sk_buff, local_ip6[0]) ...
9726              offsetof(struct __sk_buff, local_ip6[3]):
9727 #if IS_ENABLED(CONFIG_IPV6)
9728                 BUILD_BUG_ON(sizeof_field(struct sock_common,
9729                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
9730
9731                 off = si->off;
9732                 off -= offsetof(struct __sk_buff, local_ip6[0]);
9733
9734                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9735                                       si->dst_reg, si->src_reg,
9736                                       offsetof(struct sk_buff, sk));
9737                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
9738                                       offsetof(struct sock_common,
9739                                                skc_v6_rcv_saddr.s6_addr32[0]) +
9740                                       off);
9741 #else
9742                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
9743 #endif
9744                 break;
9745
9746         case offsetof(struct __sk_buff, remote_port):
9747                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
9748
9749                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9750                                       si->dst_reg, si->src_reg,
9751                                       offsetof(struct sk_buff, sk));
9752                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
9753                                       bpf_target_off(struct sock_common,
9754                                                      skc_dport,
9755                                                      2, target_size));
9756 #ifndef __BIG_ENDIAN_BITFIELD
9757                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
9758 #endif
9759                 break;
9760
9761         case offsetof(struct __sk_buff, local_port):
9762                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
9763
9764                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9765                                       si->dst_reg, si->src_reg,
9766                                       offsetof(struct sk_buff, sk));
9767                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
9768                                       bpf_target_off(struct sock_common,
9769                                                      skc_num, 2, target_size));
9770                 break;
9771
9772         case offsetof(struct __sk_buff, tstamp):
9773                 BUILD_BUG_ON(sizeof_field(struct sk_buff, tstamp) != 8);
9774
9775                 if (type == BPF_WRITE)
9776                         insn = bpf_convert_tstamp_write(prog, si, insn);
9777                 else
9778                         insn = bpf_convert_tstamp_read(prog, si, insn);
9779                 break;
9780
9781         case offsetof(struct __sk_buff, tstamp_type):
9782                 insn = bpf_convert_tstamp_type_read(si, insn);
9783                 break;
9784
9785         case offsetof(struct __sk_buff, gso_segs):
9786                 insn = bpf_convert_shinfo_access(si->dst_reg, si->src_reg, insn);
9787                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_segs),
9788                                       si->dst_reg, si->dst_reg,
9789                                       bpf_target_off(struct skb_shared_info,
9790                                                      gso_segs, 2,
9791                                                      target_size));
9792                 break;
9793         case offsetof(struct __sk_buff, gso_size):
9794                 insn = bpf_convert_shinfo_access(si->dst_reg, si->src_reg, insn);
9795                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_size),
9796                                       si->dst_reg, si->dst_reg,
9797                                       bpf_target_off(struct skb_shared_info,
9798                                                      gso_size, 2,
9799                                                      target_size));
9800                 break;
9801         case offsetof(struct __sk_buff, wire_len):
9802                 BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, pkt_len) != 4);
9803
9804                 off = si->off;
9805                 off -= offsetof(struct __sk_buff, wire_len);
9806                 off += offsetof(struct sk_buff, cb);
9807                 off += offsetof(struct qdisc_skb_cb, pkt_len);
9808                 *target_size = 4;
9809                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, off);
9810                 break;
9811
9812         case offsetof(struct __sk_buff, sk):
9813                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9814                                       si->dst_reg, si->src_reg,
9815                                       offsetof(struct sk_buff, sk));
9816                 break;
9817         case offsetof(struct __sk_buff, hwtstamp):
9818                 BUILD_BUG_ON(sizeof_field(struct skb_shared_hwtstamps, hwtstamp) != 8);
9819                 BUILD_BUG_ON(offsetof(struct skb_shared_hwtstamps, hwtstamp) != 0);
9820
9821                 insn = bpf_convert_shinfo_access(si->dst_reg, si->src_reg, insn);
9822                 *insn++ = BPF_LDX_MEM(BPF_DW,
9823                                       si->dst_reg, si->dst_reg,
9824                                       bpf_target_off(struct skb_shared_info,
9825                                                      hwtstamps, 8,
9826                                                      target_size));
9827                 break;
9828         }
9829
9830         return insn - insn_buf;
9831 }
9832
9833 u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
9834                                 const struct bpf_insn *si,
9835                                 struct bpf_insn *insn_buf,
9836                                 struct bpf_prog *prog, u32 *target_size)
9837 {
9838         struct bpf_insn *insn = insn_buf;
9839         int off;
9840
9841         switch (si->off) {
9842         case offsetof(struct bpf_sock, bound_dev_if):
9843                 BUILD_BUG_ON(sizeof_field(struct sock, sk_bound_dev_if) != 4);
9844
9845                 if (type == BPF_WRITE)
9846                         *insn++ = BPF_EMIT_STORE(BPF_W, si,
9847                                                  offsetof(struct sock, sk_bound_dev_if));
9848                 else
9849                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9850                                       offsetof(struct sock, sk_bound_dev_if));
9851                 break;
9852
9853         case offsetof(struct bpf_sock, mark):
9854                 BUILD_BUG_ON(sizeof_field(struct sock, sk_mark) != 4);
9855
9856                 if (type == BPF_WRITE)
9857                         *insn++ = BPF_EMIT_STORE(BPF_W, si,
9858                                                  offsetof(struct sock, sk_mark));
9859                 else
9860                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9861                                       offsetof(struct sock, sk_mark));
9862                 break;
9863
9864         case offsetof(struct bpf_sock, priority):
9865                 BUILD_BUG_ON(sizeof_field(struct sock, sk_priority) != 4);
9866
9867                 if (type == BPF_WRITE)
9868                         *insn++ = BPF_EMIT_STORE(BPF_W, si,
9869                                                  offsetof(struct sock, sk_priority));
9870                 else
9871                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9872                                       offsetof(struct sock, sk_priority));
9873                 break;
9874
9875         case offsetof(struct bpf_sock, family):
9876                 *insn++ = BPF_LDX_MEM(
9877                         BPF_FIELD_SIZEOF(struct sock_common, skc_family),
9878                         si->dst_reg, si->src_reg,
9879                         bpf_target_off(struct sock_common,
9880                                        skc_family,
9881                                        sizeof_field(struct sock_common,
9882                                                     skc_family),
9883                                        target_size));
9884                 break;
9885
9886         case offsetof(struct bpf_sock, type):
9887                 *insn++ = BPF_LDX_MEM(
9888                         BPF_FIELD_SIZEOF(struct sock, sk_type),
9889                         si->dst_reg, si->src_reg,
9890                         bpf_target_off(struct sock, sk_type,
9891                                        sizeof_field(struct sock, sk_type),
9892                                        target_size));
9893                 break;
9894
9895         case offsetof(struct bpf_sock, protocol):
9896                 *insn++ = BPF_LDX_MEM(
9897                         BPF_FIELD_SIZEOF(struct sock, sk_protocol),
9898                         si->dst_reg, si->src_reg,
9899                         bpf_target_off(struct sock, sk_protocol,
9900                                        sizeof_field(struct sock, sk_protocol),
9901                                        target_size));
9902                 break;
9903
9904         case offsetof(struct bpf_sock, src_ip4):
9905                 *insn++ = BPF_LDX_MEM(
9906                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
9907                         bpf_target_off(struct sock_common, skc_rcv_saddr,
9908                                        sizeof_field(struct sock_common,
9909                                                     skc_rcv_saddr),
9910                                        target_size));
9911                 break;
9912
9913         case offsetof(struct bpf_sock, dst_ip4):
9914                 *insn++ = BPF_LDX_MEM(
9915                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
9916                         bpf_target_off(struct sock_common, skc_daddr,
9917                                        sizeof_field(struct sock_common,
9918                                                     skc_daddr),
9919                                        target_size));
9920                 break;
9921
9922         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
9923 #if IS_ENABLED(CONFIG_IPV6)
9924                 off = si->off;
9925                 off -= offsetof(struct bpf_sock, src_ip6[0]);
9926                 *insn++ = BPF_LDX_MEM(
9927                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
9928                         bpf_target_off(
9929                                 struct sock_common,
9930                                 skc_v6_rcv_saddr.s6_addr32[0],
9931                                 sizeof_field(struct sock_common,
9932                                              skc_v6_rcv_saddr.s6_addr32[0]),
9933                                 target_size) + off);
9934 #else
9935                 (void)off;
9936                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
9937 #endif
9938                 break;
9939
9940         case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
9941 #if IS_ENABLED(CONFIG_IPV6)
9942                 off = si->off;
9943                 off -= offsetof(struct bpf_sock, dst_ip6[0]);
9944                 *insn++ = BPF_LDX_MEM(
9945                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
9946                         bpf_target_off(struct sock_common,
9947                                        skc_v6_daddr.s6_addr32[0],
9948                                        sizeof_field(struct sock_common,
9949                                                     skc_v6_daddr.s6_addr32[0]),
9950                                        target_size) + off);
9951 #else
9952                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
9953                 *target_size = 4;
9954 #endif
9955                 break;
9956
9957         case offsetof(struct bpf_sock, src_port):
9958                 *insn++ = BPF_LDX_MEM(
9959                         BPF_FIELD_SIZEOF(struct sock_common, skc_num),
9960                         si->dst_reg, si->src_reg,
9961                         bpf_target_off(struct sock_common, skc_num,
9962                                        sizeof_field(struct sock_common,
9963                                                     skc_num),
9964                                        target_size));
9965                 break;
9966
9967         case offsetof(struct bpf_sock, dst_port):
9968                 *insn++ = BPF_LDX_MEM(
9969                         BPF_FIELD_SIZEOF(struct sock_common, skc_dport),
9970                         si->dst_reg, si->src_reg,
9971                         bpf_target_off(struct sock_common, skc_dport,
9972                                        sizeof_field(struct sock_common,
9973                                                     skc_dport),
9974                                        target_size));
9975                 break;
9976
9977         case offsetof(struct bpf_sock, state):
9978                 *insn++ = BPF_LDX_MEM(
9979                         BPF_FIELD_SIZEOF(struct sock_common, skc_state),
9980                         si->dst_reg, si->src_reg,
9981                         bpf_target_off(struct sock_common, skc_state,
9982                                        sizeof_field(struct sock_common,
9983                                                     skc_state),
9984                                        target_size));
9985                 break;
9986         case offsetof(struct bpf_sock, rx_queue_mapping):
9987 #ifdef CONFIG_SOCK_RX_QUEUE_MAPPING
9988                 *insn++ = BPF_LDX_MEM(
9989                         BPF_FIELD_SIZEOF(struct sock, sk_rx_queue_mapping),
9990                         si->dst_reg, si->src_reg,
9991                         bpf_target_off(struct sock, sk_rx_queue_mapping,
9992                                        sizeof_field(struct sock,
9993                                                     sk_rx_queue_mapping),
9994                                        target_size));
9995                 *insn++ = BPF_JMP_IMM(BPF_JNE, si->dst_reg, NO_QUEUE_MAPPING,
9996                                       1);
9997                 *insn++ = BPF_MOV64_IMM(si->dst_reg, -1);
9998 #else
9999                 *insn++ = BPF_MOV64_IMM(si->dst_reg, -1);
10000                 *target_size = 2;
10001 #endif
10002                 break;
10003         }
10004
10005         return insn - insn_buf;
10006 }
10007
10008 static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
10009                                          const struct bpf_insn *si,
10010                                          struct bpf_insn *insn_buf,
10011                                          struct bpf_prog *prog, u32 *target_size)
10012 {
10013         struct bpf_insn *insn = insn_buf;
10014
10015         switch (si->off) {
10016         case offsetof(struct __sk_buff, ifindex):
10017                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
10018                                       si->dst_reg, si->src_reg,
10019                                       offsetof(struct sk_buff, dev));
10020                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10021                                       bpf_target_off(struct net_device, ifindex, 4,
10022                                                      target_size));
10023                 break;
10024         default:
10025                 return bpf_convert_ctx_access(type, si, insn_buf, prog,
10026                                               target_size);
10027         }
10028
10029         return insn - insn_buf;
10030 }
10031
10032 static u32 xdp_convert_ctx_access(enum bpf_access_type type,
10033                                   const struct bpf_insn *si,
10034                                   struct bpf_insn *insn_buf,
10035                                   struct bpf_prog *prog, u32 *target_size)
10036 {
10037         struct bpf_insn *insn = insn_buf;
10038
10039         switch (si->off) {
10040         case offsetof(struct xdp_md, data):
10041                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
10042                                       si->dst_reg, si->src_reg,
10043                                       offsetof(struct xdp_buff, data));
10044                 break;
10045         case offsetof(struct xdp_md, data_meta):
10046                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta),
10047                                       si->dst_reg, si->src_reg,
10048                                       offsetof(struct xdp_buff, data_meta));
10049                 break;
10050         case offsetof(struct xdp_md, data_end):
10051                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
10052                                       si->dst_reg, si->src_reg,
10053                                       offsetof(struct xdp_buff, data_end));
10054                 break;
10055         case offsetof(struct xdp_md, ingress_ifindex):
10056                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
10057                                       si->dst_reg, si->src_reg,
10058                                       offsetof(struct xdp_buff, rxq));
10059                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev),
10060                                       si->dst_reg, si->dst_reg,
10061                                       offsetof(struct xdp_rxq_info, dev));
10062                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10063                                       offsetof(struct net_device, ifindex));
10064                 break;
10065         case offsetof(struct xdp_md, rx_queue_index):
10066                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
10067                                       si->dst_reg, si->src_reg,
10068                                       offsetof(struct xdp_buff, rxq));
10069                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10070                                       offsetof(struct xdp_rxq_info,
10071                                                queue_index));
10072                 break;
10073         case offsetof(struct xdp_md, egress_ifindex):
10074                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, txq),
10075                                       si->dst_reg, si->src_reg,
10076                                       offsetof(struct xdp_buff, txq));
10077                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_txq_info, dev),
10078                                       si->dst_reg, si->dst_reg,
10079                                       offsetof(struct xdp_txq_info, dev));
10080                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10081                                       offsetof(struct net_device, ifindex));
10082                 break;
10083         }
10084
10085         return insn - insn_buf;
10086 }
10087
10088 /* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of
10089  * context Structure, F is Field in context structure that contains a pointer
10090  * to Nested Structure of type NS that has the field NF.
10091  *
10092  * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make
10093  * sure that SIZE is not greater than actual size of S.F.NF.
10094  *
10095  * If offset OFF is provided, the load happens from that offset relative to
10096  * offset of NF.
10097  */
10098 #define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF)          \
10099         do {                                                                   \
10100                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg,     \
10101                                       si->src_reg, offsetof(S, F));            \
10102                 *insn++ = BPF_LDX_MEM(                                         \
10103                         SIZE, si->dst_reg, si->dst_reg,                        \
10104                         bpf_target_off(NS, NF, sizeof_field(NS, NF),           \
10105                                        target_size)                            \
10106                                 + OFF);                                        \
10107         } while (0)
10108
10109 #define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF)                              \
10110         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF,                     \
10111                                              BPF_FIELD_SIZEOF(NS, NF), 0)
10112
10113 /* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to
10114  * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation.
10115  *
10116  * In addition it uses Temporary Field TF (member of struct S) as the 3rd
10117  * "register" since two registers available in convert_ctx_access are not
10118  * enough: we can't override neither SRC, since it contains value to store, nor
10119  * DST since it contains pointer to context that may be used by later
10120  * instructions. But we need a temporary place to save pointer to nested
10121  * structure whose field we want to store to.
10122  */
10123 #define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE, OFF, TF)          \
10124         do {                                                                   \
10125                 int tmp_reg = BPF_REG_9;                                       \
10126                 if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
10127                         --tmp_reg;                                             \
10128                 if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
10129                         --tmp_reg;                                             \
10130                 *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg,            \
10131                                       offsetof(S, TF));                        \
10132                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg,         \
10133                                       si->dst_reg, offsetof(S, F));            \
10134                 *insn++ = BPF_RAW_INSN(SIZE | BPF_MEM | BPF_CLASS(si->code),   \
10135                                        tmp_reg, si->src_reg,                   \
10136                         bpf_target_off(NS, NF, sizeof_field(NS, NF),           \
10137                                        target_size)                            \
10138                                        + OFF,                                  \
10139                                        si->imm);                               \
10140                 *insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg,            \
10141                                       offsetof(S, TF));                        \
10142         } while (0)
10143
10144 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \
10145                                                       TF)                      \
10146         do {                                                                   \
10147                 if (type == BPF_WRITE) {                                       \
10148                         SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE,   \
10149                                                          OFF, TF);             \
10150                 } else {                                                       \
10151                         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(                  \
10152                                 S, NS, F, NF, SIZE, OFF);  \
10153                 }                                                              \
10154         } while (0)
10155
10156 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(S, NS, F, NF, TF)                 \
10157         SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(                         \
10158                 S, NS, F, NF, BPF_FIELD_SIZEOF(NS, NF), 0, TF)
10159
10160 static u32 sock_addr_convert_ctx_access(enum bpf_access_type type,
10161                                         const struct bpf_insn *si,
10162                                         struct bpf_insn *insn_buf,
10163                                         struct bpf_prog *prog, u32 *target_size)
10164 {
10165         int off, port_size = sizeof_field(struct sockaddr_in6, sin6_port);
10166         struct bpf_insn *insn = insn_buf;
10167
10168         switch (si->off) {
10169         case offsetof(struct bpf_sock_addr, user_family):
10170                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10171                                             struct sockaddr, uaddr, sa_family);
10172                 break;
10173
10174         case offsetof(struct bpf_sock_addr, user_ip4):
10175                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10176                         struct bpf_sock_addr_kern, struct sockaddr_in, uaddr,
10177                         sin_addr, BPF_SIZE(si->code), 0, tmp_reg);
10178                 break;
10179
10180         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
10181                 off = si->off;
10182                 off -= offsetof(struct bpf_sock_addr, user_ip6[0]);
10183                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10184                         struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
10185                         sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off,
10186                         tmp_reg);
10187                 break;
10188
10189         case offsetof(struct bpf_sock_addr, user_port):
10190                 /* To get port we need to know sa_family first and then treat
10191                  * sockaddr as either sockaddr_in or sockaddr_in6.
10192                  * Though we can simplify since port field has same offset and
10193                  * size in both structures.
10194                  * Here we check this invariant and use just one of the
10195                  * structures if it's true.
10196                  */
10197                 BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) !=
10198                              offsetof(struct sockaddr_in6, sin6_port));
10199                 BUILD_BUG_ON(sizeof_field(struct sockaddr_in, sin_port) !=
10200                              sizeof_field(struct sockaddr_in6, sin6_port));
10201                 /* Account for sin6_port being smaller than user_port. */
10202                 port_size = min(port_size, BPF_LDST_BYTES(si));
10203                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10204                         struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
10205                         sin6_port, bytes_to_bpf_size(port_size), 0, tmp_reg);
10206                 break;
10207
10208         case offsetof(struct bpf_sock_addr, family):
10209                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10210                                             struct sock, sk, sk_family);
10211                 break;
10212
10213         case offsetof(struct bpf_sock_addr, type):
10214                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10215                                             struct sock, sk, sk_type);
10216                 break;
10217
10218         case offsetof(struct bpf_sock_addr, protocol):
10219                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10220                                             struct sock, sk, sk_protocol);
10221                 break;
10222
10223         case offsetof(struct bpf_sock_addr, msg_src_ip4):
10224                 /* Treat t_ctx as struct in_addr for msg_src_ip4. */
10225                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10226                         struct bpf_sock_addr_kern, struct in_addr, t_ctx,
10227                         s_addr, BPF_SIZE(si->code), 0, tmp_reg);
10228                 break;
10229
10230         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
10231                                 msg_src_ip6[3]):
10232                 off = si->off;
10233                 off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]);
10234                 /* Treat t_ctx as struct in6_addr for msg_src_ip6. */
10235                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10236                         struct bpf_sock_addr_kern, struct in6_addr, t_ctx,
10237                         s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg);
10238                 break;
10239         case offsetof(struct bpf_sock_addr, sk):
10240                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_addr_kern, sk),
10241                                       si->dst_reg, si->src_reg,
10242                                       offsetof(struct bpf_sock_addr_kern, sk));
10243                 break;
10244         }
10245
10246         return insn - insn_buf;
10247 }
10248
10249 static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
10250                                        const struct bpf_insn *si,
10251                                        struct bpf_insn *insn_buf,
10252                                        struct bpf_prog *prog,
10253                                        u32 *target_size)
10254 {
10255         struct bpf_insn *insn = insn_buf;
10256         int off;
10257
10258 /* Helper macro for adding read access to tcp_sock or sock fields. */
10259 #define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
10260         do {                                                                  \
10261                 int fullsock_reg = si->dst_reg, reg = BPF_REG_9, jmp = 2;     \
10262                 BUILD_BUG_ON(sizeof_field(OBJ, OBJ_FIELD) >                   \
10263                              sizeof_field(struct bpf_sock_ops, BPF_FIELD));   \
10264                 if (si->dst_reg == reg || si->src_reg == reg)                 \
10265                         reg--;                                                \
10266                 if (si->dst_reg == reg || si->src_reg == reg)                 \
10267                         reg--;                                                \
10268                 if (si->dst_reg == si->src_reg) {                             \
10269                         *insn++ = BPF_STX_MEM(BPF_DW, si->src_reg, reg,       \
10270                                           offsetof(struct bpf_sock_ops_kern,  \
10271                                           temp));                             \
10272                         fullsock_reg = reg;                                   \
10273                         jmp += 2;                                             \
10274                 }                                                             \
10275                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
10276                                                 struct bpf_sock_ops_kern,     \
10277                                                 is_fullsock),                 \
10278                                       fullsock_reg, si->src_reg,              \
10279                                       offsetof(struct bpf_sock_ops_kern,      \
10280                                                is_fullsock));                 \
10281                 *insn++ = BPF_JMP_IMM(BPF_JEQ, fullsock_reg, 0, jmp);         \
10282                 if (si->dst_reg == si->src_reg)                               \
10283                         *insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,       \
10284                                       offsetof(struct bpf_sock_ops_kern,      \
10285                                       temp));                                 \
10286                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
10287                                                 struct bpf_sock_ops_kern, sk),\
10288                                       si->dst_reg, si->src_reg,               \
10289                                       offsetof(struct bpf_sock_ops_kern, sk));\
10290                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ,                   \
10291                                                        OBJ_FIELD),            \
10292                                       si->dst_reg, si->dst_reg,               \
10293                                       offsetof(OBJ, OBJ_FIELD));              \
10294                 if (si->dst_reg == si->src_reg) {                             \
10295                         *insn++ = BPF_JMP_A(1);                               \
10296                         *insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,       \
10297                                       offsetof(struct bpf_sock_ops_kern,      \
10298                                       temp));                                 \
10299                 }                                                             \
10300         } while (0)
10301
10302 #define SOCK_OPS_GET_SK()                                                             \
10303         do {                                                                  \
10304                 int fullsock_reg = si->dst_reg, reg = BPF_REG_9, jmp = 1;     \
10305                 if (si->dst_reg == reg || si->src_reg == reg)                 \
10306                         reg--;                                                \
10307                 if (si->dst_reg == reg || si->src_reg == reg)                 \
10308                         reg--;                                                \
10309                 if (si->dst_reg == si->src_reg) {                             \
10310                         *insn++ = BPF_STX_MEM(BPF_DW, si->src_reg, reg,       \
10311                                           offsetof(struct bpf_sock_ops_kern,  \
10312                                           temp));                             \
10313                         fullsock_reg = reg;                                   \
10314                         jmp += 2;                                             \
10315                 }                                                             \
10316                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
10317                                                 struct bpf_sock_ops_kern,     \
10318                                                 is_fullsock),                 \
10319                                       fullsock_reg, si->src_reg,              \
10320                                       offsetof(struct bpf_sock_ops_kern,      \
10321                                                is_fullsock));                 \
10322                 *insn++ = BPF_JMP_IMM(BPF_JEQ, fullsock_reg, 0, jmp);         \
10323                 if (si->dst_reg == si->src_reg)                               \
10324                         *insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,       \
10325                                       offsetof(struct bpf_sock_ops_kern,      \
10326                                       temp));                                 \
10327                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
10328                                                 struct bpf_sock_ops_kern, sk),\
10329                                       si->dst_reg, si->src_reg,               \
10330                                       offsetof(struct bpf_sock_ops_kern, sk));\
10331                 if (si->dst_reg == si->src_reg) {                             \
10332                         *insn++ = BPF_JMP_A(1);                               \
10333                         *insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,       \
10334                                       offsetof(struct bpf_sock_ops_kern,      \
10335                                       temp));                                 \
10336                 }                                                             \
10337         } while (0)
10338
10339 #define SOCK_OPS_GET_TCP_SOCK_FIELD(FIELD) \
10340                 SOCK_OPS_GET_FIELD(FIELD, FIELD, struct tcp_sock)
10341
10342 /* Helper macro for adding write access to tcp_sock or sock fields.
10343  * The macro is called with two registers, dst_reg which contains a pointer
10344  * to ctx (context) and src_reg which contains the value that should be
10345  * stored. However, we need an additional register since we cannot overwrite
10346  * dst_reg because it may be used later in the program.
10347  * Instead we "borrow" one of the other register. We first save its value
10348  * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore
10349  * it at the end of the macro.
10350  */
10351 #define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
10352         do {                                                                  \
10353                 int reg = BPF_REG_9;                                          \
10354                 BUILD_BUG_ON(sizeof_field(OBJ, OBJ_FIELD) >                   \
10355                              sizeof_field(struct bpf_sock_ops, BPF_FIELD));   \
10356                 if (si->dst_reg == reg || si->src_reg == reg)                 \
10357                         reg--;                                                \
10358                 if (si->dst_reg == reg || si->src_reg == reg)                 \
10359                         reg--;                                                \
10360                 *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg,               \
10361                                       offsetof(struct bpf_sock_ops_kern,      \
10362                                                temp));                        \
10363                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
10364                                                 struct bpf_sock_ops_kern,     \
10365                                                 is_fullsock),                 \
10366                                       reg, si->dst_reg,                       \
10367                                       offsetof(struct bpf_sock_ops_kern,      \
10368                                                is_fullsock));                 \
10369                 *insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);                    \
10370                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
10371                                                 struct bpf_sock_ops_kern, sk),\
10372                                       reg, si->dst_reg,                       \
10373                                       offsetof(struct bpf_sock_ops_kern, sk));\
10374                 *insn++ = BPF_RAW_INSN(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD) |     \
10375                                        BPF_MEM | BPF_CLASS(si->code),         \
10376                                        reg, si->src_reg,                      \
10377                                        offsetof(OBJ, OBJ_FIELD),              \
10378                                        si->imm);                              \
10379                 *insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg,               \
10380                                       offsetof(struct bpf_sock_ops_kern,      \
10381                                                temp));                        \
10382         } while (0)
10383
10384 #define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE)            \
10385         do {                                                                  \
10386                 if (TYPE == BPF_WRITE)                                        \
10387                         SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
10388                 else                                                          \
10389                         SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
10390         } while (0)
10391
10392         switch (si->off) {
10393         case offsetof(struct bpf_sock_ops, op):
10394                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10395                                                        op),
10396                                       si->dst_reg, si->src_reg,
10397                                       offsetof(struct bpf_sock_ops_kern, op));
10398                 break;
10399
10400         case offsetof(struct bpf_sock_ops, replylong[0]) ...
10401              offsetof(struct bpf_sock_ops, replylong[3]):
10402                 BUILD_BUG_ON(sizeof_field(struct bpf_sock_ops, reply) !=
10403                              sizeof_field(struct bpf_sock_ops_kern, reply));
10404                 BUILD_BUG_ON(sizeof_field(struct bpf_sock_ops, replylong) !=
10405                              sizeof_field(struct bpf_sock_ops_kern, replylong));
10406                 off = si->off;
10407                 off -= offsetof(struct bpf_sock_ops, replylong[0]);
10408                 off += offsetof(struct bpf_sock_ops_kern, replylong[0]);
10409                 if (type == BPF_WRITE)
10410                         *insn++ = BPF_EMIT_STORE(BPF_W, si, off);
10411                 else
10412                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10413                                               off);
10414                 break;
10415
10416         case offsetof(struct bpf_sock_ops, family):
10417                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
10418
10419                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10420                                               struct bpf_sock_ops_kern, sk),
10421                                       si->dst_reg, si->src_reg,
10422                                       offsetof(struct bpf_sock_ops_kern, sk));
10423                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10424                                       offsetof(struct sock_common, skc_family));
10425                 break;
10426
10427         case offsetof(struct bpf_sock_ops, remote_ip4):
10428                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
10429
10430                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10431                                                 struct bpf_sock_ops_kern, sk),
10432                                       si->dst_reg, si->src_reg,
10433                                       offsetof(struct bpf_sock_ops_kern, sk));
10434                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10435                                       offsetof(struct sock_common, skc_daddr));
10436                 break;
10437
10438         case offsetof(struct bpf_sock_ops, local_ip4):
10439                 BUILD_BUG_ON(sizeof_field(struct sock_common,
10440                                           skc_rcv_saddr) != 4);
10441
10442                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10443                                               struct bpf_sock_ops_kern, sk),
10444                                       si->dst_reg, si->src_reg,
10445                                       offsetof(struct bpf_sock_ops_kern, sk));
10446                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10447                                       offsetof(struct sock_common,
10448                                                skc_rcv_saddr));
10449                 break;
10450
10451         case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
10452              offsetof(struct bpf_sock_ops, remote_ip6[3]):
10453 #if IS_ENABLED(CONFIG_IPV6)
10454                 BUILD_BUG_ON(sizeof_field(struct sock_common,
10455                                           skc_v6_daddr.s6_addr32[0]) != 4);
10456
10457                 off = si->off;
10458                 off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
10459                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10460                                                 struct bpf_sock_ops_kern, sk),
10461                                       si->dst_reg, si->src_reg,
10462                                       offsetof(struct bpf_sock_ops_kern, sk));
10463                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10464                                       offsetof(struct sock_common,
10465                                                skc_v6_daddr.s6_addr32[0]) +
10466                                       off);
10467 #else
10468                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10469 #endif
10470                 break;
10471
10472         case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
10473              offsetof(struct bpf_sock_ops, local_ip6[3]):
10474 #if IS_ENABLED(CONFIG_IPV6)
10475                 BUILD_BUG_ON(sizeof_field(struct sock_common,
10476                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
10477
10478                 off = si->off;
10479                 off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
10480                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10481                                                 struct bpf_sock_ops_kern, sk),
10482                                       si->dst_reg, si->src_reg,
10483                                       offsetof(struct bpf_sock_ops_kern, sk));
10484                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10485                                       offsetof(struct sock_common,
10486                                                skc_v6_rcv_saddr.s6_addr32[0]) +
10487                                       off);
10488 #else
10489                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10490 #endif
10491                 break;
10492
10493         case offsetof(struct bpf_sock_ops, remote_port):
10494                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
10495
10496                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10497                                                 struct bpf_sock_ops_kern, sk),
10498                                       si->dst_reg, si->src_reg,
10499                                       offsetof(struct bpf_sock_ops_kern, sk));
10500                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10501                                       offsetof(struct sock_common, skc_dport));
10502 #ifndef __BIG_ENDIAN_BITFIELD
10503                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
10504 #endif
10505                 break;
10506
10507         case offsetof(struct bpf_sock_ops, local_port):
10508                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
10509
10510                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10511                                                 struct bpf_sock_ops_kern, sk),
10512                                       si->dst_reg, si->src_reg,
10513                                       offsetof(struct bpf_sock_ops_kern, sk));
10514                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10515                                       offsetof(struct sock_common, skc_num));
10516                 break;
10517
10518         case offsetof(struct bpf_sock_ops, is_fullsock):
10519                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10520                                                 struct bpf_sock_ops_kern,
10521                                                 is_fullsock),
10522                                       si->dst_reg, si->src_reg,
10523                                       offsetof(struct bpf_sock_ops_kern,
10524                                                is_fullsock));
10525                 break;
10526
10527         case offsetof(struct bpf_sock_ops, state):
10528                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_state) != 1);
10529
10530                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10531                                                 struct bpf_sock_ops_kern, sk),
10532                                       si->dst_reg, si->src_reg,
10533                                       offsetof(struct bpf_sock_ops_kern, sk));
10534                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg,
10535                                       offsetof(struct sock_common, skc_state));
10536                 break;
10537
10538         case offsetof(struct bpf_sock_ops, rtt_min):
10539                 BUILD_BUG_ON(sizeof_field(struct tcp_sock, rtt_min) !=
10540                              sizeof(struct minmax));
10541                 BUILD_BUG_ON(sizeof(struct minmax) <
10542                              sizeof(struct minmax_sample));
10543
10544                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10545                                                 struct bpf_sock_ops_kern, sk),
10546                                       si->dst_reg, si->src_reg,
10547                                       offsetof(struct bpf_sock_ops_kern, sk));
10548                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10549                                       offsetof(struct tcp_sock, rtt_min) +
10550                                       sizeof_field(struct minmax_sample, t));
10551                 break;
10552
10553         case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags):
10554                 SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags,
10555                                    struct tcp_sock);
10556                 break;
10557
10558         case offsetof(struct bpf_sock_ops, sk_txhash):
10559                 SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash,
10560                                           struct sock, type);
10561                 break;
10562         case offsetof(struct bpf_sock_ops, snd_cwnd):
10563                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_cwnd);
10564                 break;
10565         case offsetof(struct bpf_sock_ops, srtt_us):
10566                 SOCK_OPS_GET_TCP_SOCK_FIELD(srtt_us);
10567                 break;
10568         case offsetof(struct bpf_sock_ops, snd_ssthresh):
10569                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_ssthresh);
10570                 break;
10571         case offsetof(struct bpf_sock_ops, rcv_nxt):
10572                 SOCK_OPS_GET_TCP_SOCK_FIELD(rcv_nxt);
10573                 break;
10574         case offsetof(struct bpf_sock_ops, snd_nxt):
10575                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_nxt);
10576                 break;
10577         case offsetof(struct bpf_sock_ops, snd_una):
10578                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_una);
10579                 break;
10580         case offsetof(struct bpf_sock_ops, mss_cache):
10581                 SOCK_OPS_GET_TCP_SOCK_FIELD(mss_cache);
10582                 break;
10583         case offsetof(struct bpf_sock_ops, ecn_flags):
10584                 SOCK_OPS_GET_TCP_SOCK_FIELD(ecn_flags);
10585                 break;
10586         case offsetof(struct bpf_sock_ops, rate_delivered):
10587                 SOCK_OPS_GET_TCP_SOCK_FIELD(rate_delivered);
10588                 break;
10589         case offsetof(struct bpf_sock_ops, rate_interval_us):
10590                 SOCK_OPS_GET_TCP_SOCK_FIELD(rate_interval_us);
10591                 break;
10592         case offsetof(struct bpf_sock_ops, packets_out):
10593                 SOCK_OPS_GET_TCP_SOCK_FIELD(packets_out);
10594                 break;
10595         case offsetof(struct bpf_sock_ops, retrans_out):
10596                 SOCK_OPS_GET_TCP_SOCK_FIELD(retrans_out);
10597                 break;
10598         case offsetof(struct bpf_sock_ops, total_retrans):
10599                 SOCK_OPS_GET_TCP_SOCK_FIELD(total_retrans);
10600                 break;
10601         case offsetof(struct bpf_sock_ops, segs_in):
10602                 SOCK_OPS_GET_TCP_SOCK_FIELD(segs_in);
10603                 break;
10604         case offsetof(struct bpf_sock_ops, data_segs_in):
10605                 SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_in);
10606                 break;
10607         case offsetof(struct bpf_sock_ops, segs_out):
10608                 SOCK_OPS_GET_TCP_SOCK_FIELD(segs_out);
10609                 break;
10610         case offsetof(struct bpf_sock_ops, data_segs_out):
10611                 SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_out);
10612                 break;
10613         case offsetof(struct bpf_sock_ops, lost_out):
10614                 SOCK_OPS_GET_TCP_SOCK_FIELD(lost_out);
10615                 break;
10616         case offsetof(struct bpf_sock_ops, sacked_out):
10617                 SOCK_OPS_GET_TCP_SOCK_FIELD(sacked_out);
10618                 break;
10619         case offsetof(struct bpf_sock_ops, bytes_received):
10620                 SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_received);
10621                 break;
10622         case offsetof(struct bpf_sock_ops, bytes_acked):
10623                 SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_acked);
10624                 break;
10625         case offsetof(struct bpf_sock_ops, sk):
10626                 SOCK_OPS_GET_SK();
10627                 break;
10628         case offsetof(struct bpf_sock_ops, skb_data_end):
10629                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10630                                                        skb_data_end),
10631                                       si->dst_reg, si->src_reg,
10632                                       offsetof(struct bpf_sock_ops_kern,
10633                                                skb_data_end));
10634                 break;
10635         case offsetof(struct bpf_sock_ops, skb_data):
10636                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10637                                                        skb),
10638                                       si->dst_reg, si->src_reg,
10639                                       offsetof(struct bpf_sock_ops_kern,
10640                                                skb));
10641                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
10642                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
10643                                       si->dst_reg, si->dst_reg,
10644                                       offsetof(struct sk_buff, data));
10645                 break;
10646         case offsetof(struct bpf_sock_ops, skb_len):
10647                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10648                                                        skb),
10649                                       si->dst_reg, si->src_reg,
10650                                       offsetof(struct bpf_sock_ops_kern,
10651                                                skb));
10652                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
10653                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, len),
10654                                       si->dst_reg, si->dst_reg,
10655                                       offsetof(struct sk_buff, len));
10656                 break;
10657         case offsetof(struct bpf_sock_ops, skb_tcp_flags):
10658                 off = offsetof(struct sk_buff, cb);
10659                 off += offsetof(struct tcp_skb_cb, tcp_flags);
10660                 *target_size = sizeof_field(struct tcp_skb_cb, tcp_flags);
10661                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10662                                                        skb),
10663                                       si->dst_reg, si->src_reg,
10664                                       offsetof(struct bpf_sock_ops_kern,
10665                                                skb));
10666                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
10667                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_skb_cb,
10668                                                        tcp_flags),
10669                                       si->dst_reg, si->dst_reg, off);
10670                 break;
10671         case offsetof(struct bpf_sock_ops, skb_hwtstamp): {
10672                 struct bpf_insn *jmp_on_null_skb;
10673
10674                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10675                                                        skb),
10676                                       si->dst_reg, si->src_reg,
10677                                       offsetof(struct bpf_sock_ops_kern,
10678                                                skb));
10679                 /* Reserve one insn to test skb == NULL */
10680                 jmp_on_null_skb = insn++;
10681                 insn = bpf_convert_shinfo_access(si->dst_reg, si->dst_reg, insn);
10682                 *insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
10683                                       bpf_target_off(struct skb_shared_info,
10684                                                      hwtstamps, 8,
10685                                                      target_size));
10686                 *jmp_on_null_skb = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0,
10687                                                insn - jmp_on_null_skb - 1);
10688                 break;
10689         }
10690         }
10691         return insn - insn_buf;
10692 }
10693
10694 /* data_end = skb->data + skb_headlen() */
10695 static struct bpf_insn *bpf_convert_data_end_access(const struct bpf_insn *si,
10696                                                     struct bpf_insn *insn)
10697 {
10698         int reg;
10699         int temp_reg_off = offsetof(struct sk_buff, cb) +
10700                            offsetof(struct sk_skb_cb, temp_reg);
10701
10702         if (si->src_reg == si->dst_reg) {
10703                 /* We need an extra register, choose and save a register. */
10704                 reg = BPF_REG_9;
10705                 if (si->src_reg == reg || si->dst_reg == reg)
10706                         reg--;
10707                 if (si->src_reg == reg || si->dst_reg == reg)
10708                         reg--;
10709                 *insn++ = BPF_STX_MEM(BPF_DW, si->src_reg, reg, temp_reg_off);
10710         } else {
10711                 reg = si->dst_reg;
10712         }
10713
10714         /* reg = skb->data */
10715         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
10716                               reg, si->src_reg,
10717                               offsetof(struct sk_buff, data));
10718         /* AX = skb->len */
10719         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, len),
10720                               BPF_REG_AX, si->src_reg,
10721                               offsetof(struct sk_buff, len));
10722         /* reg = skb->data + skb->len */
10723         *insn++ = BPF_ALU64_REG(BPF_ADD, reg, BPF_REG_AX);
10724         /* AX = skb->data_len */
10725         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data_len),
10726                               BPF_REG_AX, si->src_reg,
10727                               offsetof(struct sk_buff, data_len));
10728
10729         /* reg = skb->data + skb->len - skb->data_len */
10730         *insn++ = BPF_ALU64_REG(BPF_SUB, reg, BPF_REG_AX);
10731
10732         if (si->src_reg == si->dst_reg) {
10733                 /* Restore the saved register */
10734                 *insn++ = BPF_MOV64_REG(BPF_REG_AX, si->src_reg);
10735                 *insn++ = BPF_MOV64_REG(si->dst_reg, reg);
10736                 *insn++ = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_AX, temp_reg_off);
10737         }
10738
10739         return insn;
10740 }
10741
10742 static u32 sk_skb_convert_ctx_access(enum bpf_access_type type,
10743                                      const struct bpf_insn *si,
10744                                      struct bpf_insn *insn_buf,
10745                                      struct bpf_prog *prog, u32 *target_size)
10746 {
10747         struct bpf_insn *insn = insn_buf;
10748         int off;
10749
10750         switch (si->off) {
10751         case offsetof(struct __sk_buff, data_end):
10752                 insn = bpf_convert_data_end_access(si, insn);
10753                 break;
10754         case offsetof(struct __sk_buff, cb[0]) ...
10755              offsetofend(struct __sk_buff, cb[4]) - 1:
10756                 BUILD_BUG_ON(sizeof_field(struct sk_skb_cb, data) < 20);
10757                 BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
10758                               offsetof(struct sk_skb_cb, data)) %
10759                              sizeof(__u64));
10760
10761                 prog->cb_access = 1;
10762                 off  = si->off;
10763                 off -= offsetof(struct __sk_buff, cb[0]);
10764                 off += offsetof(struct sk_buff, cb);
10765                 off += offsetof(struct sk_skb_cb, data);
10766                 if (type == BPF_WRITE)
10767                         *insn++ = BPF_EMIT_STORE(BPF_SIZE(si->code), si, off);
10768                 else
10769                         *insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
10770                                               si->src_reg, off);
10771                 break;
10772
10773
10774         default:
10775                 return bpf_convert_ctx_access(type, si, insn_buf, prog,
10776                                               target_size);
10777         }
10778
10779         return insn - insn_buf;
10780 }
10781
10782 static u32 sk_msg_convert_ctx_access(enum bpf_access_type type,
10783                                      const struct bpf_insn *si,
10784                                      struct bpf_insn *insn_buf,
10785                                      struct bpf_prog *prog, u32 *target_size)
10786 {
10787         struct bpf_insn *insn = insn_buf;
10788 #if IS_ENABLED(CONFIG_IPV6)
10789         int off;
10790 #endif
10791
10792         /* convert ctx uses the fact sg element is first in struct */
10793         BUILD_BUG_ON(offsetof(struct sk_msg, sg) != 0);
10794
10795         switch (si->off) {
10796         case offsetof(struct sk_msg_md, data):
10797                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data),
10798                                       si->dst_reg, si->src_reg,
10799                                       offsetof(struct sk_msg, data));
10800                 break;
10801         case offsetof(struct sk_msg_md, data_end):
10802                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data_end),
10803                                       si->dst_reg, si->src_reg,
10804                                       offsetof(struct sk_msg, data_end));
10805                 break;
10806         case offsetof(struct sk_msg_md, family):
10807                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
10808
10809                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10810                                               struct sk_msg, sk),
10811                                       si->dst_reg, si->src_reg,
10812                                       offsetof(struct sk_msg, sk));
10813                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10814                                       offsetof(struct sock_common, skc_family));
10815                 break;
10816
10817         case offsetof(struct sk_msg_md, remote_ip4):
10818                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
10819
10820                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10821                                                 struct sk_msg, sk),
10822                                       si->dst_reg, si->src_reg,
10823                                       offsetof(struct sk_msg, sk));
10824                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10825                                       offsetof(struct sock_common, skc_daddr));
10826                 break;
10827
10828         case offsetof(struct sk_msg_md, local_ip4):
10829                 BUILD_BUG_ON(sizeof_field(struct sock_common,
10830                                           skc_rcv_saddr) != 4);
10831
10832                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10833                                               struct sk_msg, sk),
10834                                       si->dst_reg, si->src_reg,
10835                                       offsetof(struct sk_msg, sk));
10836                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10837                                       offsetof(struct sock_common,
10838                                                skc_rcv_saddr));
10839                 break;
10840
10841         case offsetof(struct sk_msg_md, remote_ip6[0]) ...
10842              offsetof(struct sk_msg_md, remote_ip6[3]):
10843 #if IS_ENABLED(CONFIG_IPV6)
10844                 BUILD_BUG_ON(sizeof_field(struct sock_common,
10845                                           skc_v6_daddr.s6_addr32[0]) != 4);
10846
10847                 off = si->off;
10848                 off -= offsetof(struct sk_msg_md, remote_ip6[0]);
10849                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10850                                                 struct sk_msg, sk),
10851                                       si->dst_reg, si->src_reg,
10852                                       offsetof(struct sk_msg, sk));
10853                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10854                                       offsetof(struct sock_common,
10855                                                skc_v6_daddr.s6_addr32[0]) +
10856                                       off);
10857 #else
10858                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10859 #endif
10860                 break;
10861
10862         case offsetof(struct sk_msg_md, local_ip6[0]) ...
10863              offsetof(struct sk_msg_md, local_ip6[3]):
10864 #if IS_ENABLED(CONFIG_IPV6)
10865                 BUILD_BUG_ON(sizeof_field(struct sock_common,
10866                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
10867
10868                 off = si->off;
10869                 off -= offsetof(struct sk_msg_md, local_ip6[0]);
10870                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10871                                                 struct sk_msg, sk),
10872                                       si->dst_reg, si->src_reg,
10873                                       offsetof(struct sk_msg, sk));
10874                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10875                                       offsetof(struct sock_common,
10876                                                skc_v6_rcv_saddr.s6_addr32[0]) +
10877                                       off);
10878 #else
10879                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10880 #endif
10881                 break;
10882
10883         case offsetof(struct sk_msg_md, remote_port):
10884                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
10885
10886                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10887                                                 struct sk_msg, sk),
10888                                       si->dst_reg, si->src_reg,
10889                                       offsetof(struct sk_msg, sk));
10890                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10891                                       offsetof(struct sock_common, skc_dport));
10892 #ifndef __BIG_ENDIAN_BITFIELD
10893                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
10894 #endif
10895                 break;
10896
10897         case offsetof(struct sk_msg_md, local_port):
10898                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
10899
10900                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10901                                                 struct sk_msg, sk),
10902                                       si->dst_reg, si->src_reg,
10903                                       offsetof(struct sk_msg, sk));
10904                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10905                                       offsetof(struct sock_common, skc_num));
10906                 break;
10907
10908         case offsetof(struct sk_msg_md, size):
10909                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_sg, size),
10910                                       si->dst_reg, si->src_reg,
10911                                       offsetof(struct sk_msg_sg, size));
10912                 break;
10913
10914         case offsetof(struct sk_msg_md, sk):
10915                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, sk),
10916                                       si->dst_reg, si->src_reg,
10917                                       offsetof(struct sk_msg, sk));
10918                 break;
10919         }
10920
10921         return insn - insn_buf;
10922 }
10923
10924 const struct bpf_verifier_ops sk_filter_verifier_ops = {
10925         .get_func_proto         = sk_filter_func_proto,
10926         .is_valid_access        = sk_filter_is_valid_access,
10927         .convert_ctx_access     = bpf_convert_ctx_access,
10928         .gen_ld_abs             = bpf_gen_ld_abs,
10929 };
10930
10931 const struct bpf_prog_ops sk_filter_prog_ops = {
10932         .test_run               = bpf_prog_test_run_skb,
10933 };
10934
10935 const struct bpf_verifier_ops tc_cls_act_verifier_ops = {
10936         .get_func_proto         = tc_cls_act_func_proto,
10937         .is_valid_access        = tc_cls_act_is_valid_access,
10938         .convert_ctx_access     = tc_cls_act_convert_ctx_access,
10939         .gen_prologue           = tc_cls_act_prologue,
10940         .gen_ld_abs             = bpf_gen_ld_abs,
10941         .btf_struct_access      = tc_cls_act_btf_struct_access,
10942 };
10943
10944 const struct bpf_prog_ops tc_cls_act_prog_ops = {
10945         .test_run               = bpf_prog_test_run_skb,
10946 };
10947
10948 const struct bpf_verifier_ops xdp_verifier_ops = {
10949         .get_func_proto         = xdp_func_proto,
10950         .is_valid_access        = xdp_is_valid_access,
10951         .convert_ctx_access     = xdp_convert_ctx_access,
10952         .gen_prologue           = bpf_noop_prologue,
10953         .btf_struct_access      = xdp_btf_struct_access,
10954 };
10955
10956 const struct bpf_prog_ops xdp_prog_ops = {
10957         .test_run               = bpf_prog_test_run_xdp,
10958 };
10959
10960 const struct bpf_verifier_ops cg_skb_verifier_ops = {
10961         .get_func_proto         = cg_skb_func_proto,
10962         .is_valid_access        = cg_skb_is_valid_access,
10963         .convert_ctx_access     = bpf_convert_ctx_access,
10964 };
10965
10966 const struct bpf_prog_ops cg_skb_prog_ops = {
10967         .test_run               = bpf_prog_test_run_skb,
10968 };
10969
10970 const struct bpf_verifier_ops lwt_in_verifier_ops = {
10971         .get_func_proto         = lwt_in_func_proto,
10972         .is_valid_access        = lwt_is_valid_access,
10973         .convert_ctx_access     = bpf_convert_ctx_access,
10974 };
10975
10976 const struct bpf_prog_ops lwt_in_prog_ops = {
10977         .test_run               = bpf_prog_test_run_skb,
10978 };
10979
10980 const struct bpf_verifier_ops lwt_out_verifier_ops = {
10981         .get_func_proto         = lwt_out_func_proto,
10982         .is_valid_access        = lwt_is_valid_access,
10983         .convert_ctx_access     = bpf_convert_ctx_access,
10984 };
10985
10986 const struct bpf_prog_ops lwt_out_prog_ops = {
10987         .test_run               = bpf_prog_test_run_skb,
10988 };
10989
10990 const struct bpf_verifier_ops lwt_xmit_verifier_ops = {
10991         .get_func_proto         = lwt_xmit_func_proto,
10992         .is_valid_access        = lwt_is_valid_access,
10993         .convert_ctx_access     = bpf_convert_ctx_access,
10994         .gen_prologue           = tc_cls_act_prologue,
10995 };
10996
10997 const struct bpf_prog_ops lwt_xmit_prog_ops = {
10998         .test_run               = bpf_prog_test_run_skb,
10999 };
11000
11001 const struct bpf_verifier_ops lwt_seg6local_verifier_ops = {
11002         .get_func_proto         = lwt_seg6local_func_proto,
11003         .is_valid_access        = lwt_is_valid_access,
11004         .convert_ctx_access     = bpf_convert_ctx_access,
11005 };
11006
11007 const struct bpf_prog_ops lwt_seg6local_prog_ops = {
11008         .test_run               = bpf_prog_test_run_skb,
11009 };
11010
11011 const struct bpf_verifier_ops cg_sock_verifier_ops = {
11012         .get_func_proto         = sock_filter_func_proto,
11013         .is_valid_access        = sock_filter_is_valid_access,
11014         .convert_ctx_access     = bpf_sock_convert_ctx_access,
11015 };
11016
11017 const struct bpf_prog_ops cg_sock_prog_ops = {
11018 };
11019
11020 const struct bpf_verifier_ops cg_sock_addr_verifier_ops = {
11021         .get_func_proto         = sock_addr_func_proto,
11022         .is_valid_access        = sock_addr_is_valid_access,
11023         .convert_ctx_access     = sock_addr_convert_ctx_access,
11024 };
11025
11026 const struct bpf_prog_ops cg_sock_addr_prog_ops = {
11027 };
11028
11029 const struct bpf_verifier_ops sock_ops_verifier_ops = {
11030         .get_func_proto         = sock_ops_func_proto,
11031         .is_valid_access        = sock_ops_is_valid_access,
11032         .convert_ctx_access     = sock_ops_convert_ctx_access,
11033 };
11034
11035 const struct bpf_prog_ops sock_ops_prog_ops = {
11036 };
11037
11038 const struct bpf_verifier_ops sk_skb_verifier_ops = {
11039         .get_func_proto         = sk_skb_func_proto,
11040         .is_valid_access        = sk_skb_is_valid_access,
11041         .convert_ctx_access     = sk_skb_convert_ctx_access,
11042         .gen_prologue           = sk_skb_prologue,
11043 };
11044
11045 const struct bpf_prog_ops sk_skb_prog_ops = {
11046 };
11047
11048 const struct bpf_verifier_ops sk_msg_verifier_ops = {
11049         .get_func_proto         = sk_msg_func_proto,
11050         .is_valid_access        = sk_msg_is_valid_access,
11051         .convert_ctx_access     = sk_msg_convert_ctx_access,
11052         .gen_prologue           = bpf_noop_prologue,
11053 };
11054
11055 const struct bpf_prog_ops sk_msg_prog_ops = {
11056 };
11057
11058 const struct bpf_verifier_ops flow_dissector_verifier_ops = {
11059         .get_func_proto         = flow_dissector_func_proto,
11060         .is_valid_access        = flow_dissector_is_valid_access,
11061         .convert_ctx_access     = flow_dissector_convert_ctx_access,
11062 };
11063
11064 const struct bpf_prog_ops flow_dissector_prog_ops = {
11065         .test_run               = bpf_prog_test_run_flow_dissector,
11066 };
11067
11068 int sk_detach_filter(struct sock *sk)
11069 {
11070         int ret = -ENOENT;
11071         struct sk_filter *filter;
11072
11073         if (sock_flag(sk, SOCK_FILTER_LOCKED))
11074                 return -EPERM;
11075
11076         filter = rcu_dereference_protected(sk->sk_filter,
11077                                            lockdep_sock_is_held(sk));
11078         if (filter) {
11079                 RCU_INIT_POINTER(sk->sk_filter, NULL);
11080                 sk_filter_uncharge(sk, filter);
11081                 ret = 0;
11082         }
11083
11084         return ret;
11085 }
11086 EXPORT_SYMBOL_GPL(sk_detach_filter);
11087
11088 int sk_get_filter(struct sock *sk, sockptr_t optval, unsigned int len)
11089 {
11090         struct sock_fprog_kern *fprog;
11091         struct sk_filter *filter;
11092         int ret = 0;
11093
11094         sockopt_lock_sock(sk);
11095         filter = rcu_dereference_protected(sk->sk_filter,
11096                                            lockdep_sock_is_held(sk));
11097         if (!filter)
11098                 goto out;
11099
11100         /* We're copying the filter that has been originally attached,
11101          * so no conversion/decode needed anymore. eBPF programs that
11102          * have no original program cannot be dumped through this.
11103          */
11104         ret = -EACCES;
11105         fprog = filter->prog->orig_prog;
11106         if (!fprog)
11107                 goto out;
11108
11109         ret = fprog->len;
11110         if (!len)
11111                 /* User space only enquires number of filter blocks. */
11112                 goto out;
11113
11114         ret = -EINVAL;
11115         if (len < fprog->len)
11116                 goto out;
11117
11118         ret = -EFAULT;
11119         if (copy_to_sockptr(optval, fprog->filter, bpf_classic_proglen(fprog)))
11120                 goto out;
11121
11122         /* Instead of bytes, the API requests to return the number
11123          * of filter blocks.
11124          */
11125         ret = fprog->len;
11126 out:
11127         sockopt_release_sock(sk);
11128         return ret;
11129 }
11130
11131 #ifdef CONFIG_INET
11132 static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,
11133                                     struct sock_reuseport *reuse,
11134                                     struct sock *sk, struct sk_buff *skb,
11135                                     struct sock *migrating_sk,
11136                                     u32 hash)
11137 {
11138         reuse_kern->skb = skb;
11139         reuse_kern->sk = sk;
11140         reuse_kern->selected_sk = NULL;
11141         reuse_kern->migrating_sk = migrating_sk;
11142         reuse_kern->data_end = skb->data + skb_headlen(skb);
11143         reuse_kern->hash = hash;
11144         reuse_kern->reuseport_id = reuse->reuseport_id;
11145         reuse_kern->bind_inany = reuse->bind_inany;
11146 }
11147
11148 struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,
11149                                   struct bpf_prog *prog, struct sk_buff *skb,
11150                                   struct sock *migrating_sk,
11151                                   u32 hash)
11152 {
11153         struct sk_reuseport_kern reuse_kern;
11154         enum sk_action action;
11155
11156         bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, migrating_sk, hash);
11157         action = bpf_prog_run(prog, &reuse_kern);
11158
11159         if (action == SK_PASS)
11160                 return reuse_kern.selected_sk;
11161         else
11162                 return ERR_PTR(-ECONNREFUSED);
11163 }
11164
11165 BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern,
11166            struct bpf_map *, map, void *, key, u32, flags)
11167 {
11168         bool is_sockarray = map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY;
11169         struct sock_reuseport *reuse;
11170         struct sock *selected_sk;
11171
11172         selected_sk = map->ops->map_lookup_elem(map, key);
11173         if (!selected_sk)
11174                 return -ENOENT;
11175
11176         reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
11177         if (!reuse) {
11178                 /* Lookup in sock_map can return TCP ESTABLISHED sockets. */
11179                 if (sk_is_refcounted(selected_sk))
11180                         sock_put(selected_sk);
11181
11182                 /* reuseport_array has only sk with non NULL sk_reuseport_cb.
11183                  * The only (!reuse) case here is - the sk has already been
11184                  * unhashed (e.g. by close()), so treat it as -ENOENT.
11185                  *
11186                  * Other maps (e.g. sock_map) do not provide this guarantee and
11187                  * the sk may never be in the reuseport group to begin with.
11188                  */
11189                 return is_sockarray ? -ENOENT : -EINVAL;
11190         }
11191
11192         if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
11193                 struct sock *sk = reuse_kern->sk;
11194
11195                 if (sk->sk_protocol != selected_sk->sk_protocol)
11196                         return -EPROTOTYPE;
11197                 else if (sk->sk_family != selected_sk->sk_family)
11198                         return -EAFNOSUPPORT;
11199
11200                 /* Catch all. Likely bound to a different sockaddr. */
11201                 return -EBADFD;
11202         }
11203
11204         reuse_kern->selected_sk = selected_sk;
11205
11206         return 0;
11207 }
11208
11209 static const struct bpf_func_proto sk_select_reuseport_proto = {
11210         .func           = sk_select_reuseport,
11211         .gpl_only       = false,
11212         .ret_type       = RET_INTEGER,
11213         .arg1_type      = ARG_PTR_TO_CTX,
11214         .arg2_type      = ARG_CONST_MAP_PTR,
11215         .arg3_type      = ARG_PTR_TO_MAP_KEY,
11216         .arg4_type      = ARG_ANYTHING,
11217 };
11218
11219 BPF_CALL_4(sk_reuseport_load_bytes,
11220            const struct sk_reuseport_kern *, reuse_kern, u32, offset,
11221            void *, to, u32, len)
11222 {
11223         return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
11224 }
11225
11226 static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
11227         .func           = sk_reuseport_load_bytes,
11228         .gpl_only       = false,
11229         .ret_type       = RET_INTEGER,
11230         .arg1_type      = ARG_PTR_TO_CTX,
11231         .arg2_type      = ARG_ANYTHING,
11232         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
11233         .arg4_type      = ARG_CONST_SIZE,
11234 };
11235
11236 BPF_CALL_5(sk_reuseport_load_bytes_relative,
11237            const struct sk_reuseport_kern *, reuse_kern, u32, offset,
11238            void *, to, u32, len, u32, start_header)
11239 {
11240         return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
11241                                                len, start_header);
11242 }
11243
11244 static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
11245         .func           = sk_reuseport_load_bytes_relative,
11246         .gpl_only       = false,
11247         .ret_type       = RET_INTEGER,
11248         .arg1_type      = ARG_PTR_TO_CTX,
11249         .arg2_type      = ARG_ANYTHING,
11250         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
11251         .arg4_type      = ARG_CONST_SIZE,
11252         .arg5_type      = ARG_ANYTHING,
11253 };
11254
11255 static const struct bpf_func_proto *
11256 sk_reuseport_func_proto(enum bpf_func_id func_id,
11257                         const struct bpf_prog *prog)
11258 {
11259         switch (func_id) {
11260         case BPF_FUNC_sk_select_reuseport:
11261                 return &sk_select_reuseport_proto;
11262         case BPF_FUNC_skb_load_bytes:
11263                 return &sk_reuseport_load_bytes_proto;
11264         case BPF_FUNC_skb_load_bytes_relative:
11265                 return &sk_reuseport_load_bytes_relative_proto;
11266         case BPF_FUNC_get_socket_cookie:
11267                 return &bpf_get_socket_ptr_cookie_proto;
11268         case BPF_FUNC_ktime_get_coarse_ns:
11269                 return &bpf_ktime_get_coarse_ns_proto;
11270         default:
11271                 return bpf_base_func_proto(func_id);
11272         }
11273 }
11274
11275 static bool
11276 sk_reuseport_is_valid_access(int off, int size,
11277                              enum bpf_access_type type,
11278                              const struct bpf_prog *prog,
11279                              struct bpf_insn_access_aux *info)
11280 {
11281         const u32 size_default = sizeof(__u32);
11282
11283         if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
11284             off % size || type != BPF_READ)
11285                 return false;
11286
11287         switch (off) {
11288         case offsetof(struct sk_reuseport_md, data):
11289                 info->reg_type = PTR_TO_PACKET;
11290                 return size == sizeof(__u64);
11291
11292         case offsetof(struct sk_reuseport_md, data_end):
11293                 info->reg_type = PTR_TO_PACKET_END;
11294                 return size == sizeof(__u64);
11295
11296         case offsetof(struct sk_reuseport_md, hash):
11297                 return size == size_default;
11298
11299         case offsetof(struct sk_reuseport_md, sk):
11300                 info->reg_type = PTR_TO_SOCKET;
11301                 return size == sizeof(__u64);
11302
11303         case offsetof(struct sk_reuseport_md, migrating_sk):
11304                 info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
11305                 return size == sizeof(__u64);
11306
11307         /* Fields that allow narrowing */
11308         case bpf_ctx_range(struct sk_reuseport_md, eth_protocol):
11309                 if (size < sizeof_field(struct sk_buff, protocol))
11310                         return false;
11311                 fallthrough;
11312         case bpf_ctx_range(struct sk_reuseport_md, ip_protocol):
11313         case bpf_ctx_range(struct sk_reuseport_md, bind_inany):
11314         case bpf_ctx_range(struct sk_reuseport_md, len):
11315                 bpf_ctx_record_field_size(info, size_default);
11316                 return bpf_ctx_narrow_access_ok(off, size, size_default);
11317
11318         default:
11319                 return false;
11320         }
11321 }
11322
11323 #define SK_REUSEPORT_LOAD_FIELD(F) ({                                   \
11324         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
11325                               si->dst_reg, si->src_reg,                 \
11326                               bpf_target_off(struct sk_reuseport_kern, F, \
11327                                              sizeof_field(struct sk_reuseport_kern, F), \
11328                                              target_size));             \
11329         })
11330
11331 #define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)                          \
11332         SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,           \
11333                                     struct sk_buff,                     \
11334                                     skb,                                \
11335                                     SKB_FIELD)
11336
11337 #define SK_REUSEPORT_LOAD_SK_FIELD(SK_FIELD)                            \
11338         SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,           \
11339                                     struct sock,                        \
11340                                     sk,                                 \
11341                                     SK_FIELD)
11342
11343 static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
11344                                            const struct bpf_insn *si,
11345                                            struct bpf_insn *insn_buf,
11346                                            struct bpf_prog *prog,
11347                                            u32 *target_size)
11348 {
11349         struct bpf_insn *insn = insn_buf;
11350
11351         switch (si->off) {
11352         case offsetof(struct sk_reuseport_md, data):
11353                 SK_REUSEPORT_LOAD_SKB_FIELD(data);
11354                 break;
11355
11356         case offsetof(struct sk_reuseport_md, len):
11357                 SK_REUSEPORT_LOAD_SKB_FIELD(len);
11358                 break;
11359
11360         case offsetof(struct sk_reuseport_md, eth_protocol):
11361                 SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
11362                 break;
11363
11364         case offsetof(struct sk_reuseport_md, ip_protocol):
11365                 SK_REUSEPORT_LOAD_SK_FIELD(sk_protocol);
11366                 break;
11367
11368         case offsetof(struct sk_reuseport_md, data_end):
11369                 SK_REUSEPORT_LOAD_FIELD(data_end);
11370                 break;
11371
11372         case offsetof(struct sk_reuseport_md, hash):
11373                 SK_REUSEPORT_LOAD_FIELD(hash);
11374                 break;
11375
11376         case offsetof(struct sk_reuseport_md, bind_inany):
11377                 SK_REUSEPORT_LOAD_FIELD(bind_inany);
11378                 break;
11379
11380         case offsetof(struct sk_reuseport_md, sk):
11381                 SK_REUSEPORT_LOAD_FIELD(sk);
11382                 break;
11383
11384         case offsetof(struct sk_reuseport_md, migrating_sk):
11385                 SK_REUSEPORT_LOAD_FIELD(migrating_sk);
11386                 break;
11387         }
11388
11389         return insn - insn_buf;
11390 }
11391
11392 const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
11393         .get_func_proto         = sk_reuseport_func_proto,
11394         .is_valid_access        = sk_reuseport_is_valid_access,
11395         .convert_ctx_access     = sk_reuseport_convert_ctx_access,
11396 };
11397
11398 const struct bpf_prog_ops sk_reuseport_prog_ops = {
11399 };
11400
11401 DEFINE_STATIC_KEY_FALSE(bpf_sk_lookup_enabled);
11402 EXPORT_SYMBOL(bpf_sk_lookup_enabled);
11403
11404 BPF_CALL_3(bpf_sk_lookup_assign, struct bpf_sk_lookup_kern *, ctx,
11405            struct sock *, sk, u64, flags)
11406 {
11407         if (unlikely(flags & ~(BPF_SK_LOOKUP_F_REPLACE |
11408                                BPF_SK_LOOKUP_F_NO_REUSEPORT)))
11409                 return -EINVAL;
11410         if (unlikely(sk && sk_is_refcounted(sk)))
11411                 return -ESOCKTNOSUPPORT; /* reject non-RCU freed sockets */
11412         if (unlikely(sk && sk_is_tcp(sk) && sk->sk_state != TCP_LISTEN))
11413                 return -ESOCKTNOSUPPORT; /* only accept TCP socket in LISTEN */
11414         if (unlikely(sk && sk_is_udp(sk) && sk->sk_state != TCP_CLOSE))
11415                 return -ESOCKTNOSUPPORT; /* only accept UDP socket in CLOSE */
11416
11417         /* Check if socket is suitable for packet L3/L4 protocol */
11418         if (sk && sk->sk_protocol != ctx->protocol)
11419                 return -EPROTOTYPE;
11420         if (sk && sk->sk_family != ctx->family &&
11421             (sk->sk_family == AF_INET || ipv6_only_sock(sk)))
11422                 return -EAFNOSUPPORT;
11423
11424         if (ctx->selected_sk && !(flags & BPF_SK_LOOKUP_F_REPLACE))
11425                 return -EEXIST;
11426
11427         /* Select socket as lookup result */
11428         ctx->selected_sk = sk;
11429         ctx->no_reuseport = flags & BPF_SK_LOOKUP_F_NO_REUSEPORT;
11430         return 0;
11431 }
11432
11433 static const struct bpf_func_proto bpf_sk_lookup_assign_proto = {
11434         .func           = bpf_sk_lookup_assign,
11435         .gpl_only       = false,
11436         .ret_type       = RET_INTEGER,
11437         .arg1_type      = ARG_PTR_TO_CTX,
11438         .arg2_type      = ARG_PTR_TO_SOCKET_OR_NULL,
11439         .arg3_type      = ARG_ANYTHING,
11440 };
11441
11442 static const struct bpf_func_proto *
11443 sk_lookup_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
11444 {
11445         switch (func_id) {
11446         case BPF_FUNC_perf_event_output:
11447                 return &bpf_event_output_data_proto;
11448         case BPF_FUNC_sk_assign:
11449                 return &bpf_sk_lookup_assign_proto;
11450         case BPF_FUNC_sk_release:
11451                 return &bpf_sk_release_proto;
11452         default:
11453                 return bpf_sk_base_func_proto(func_id);
11454         }
11455 }
11456
11457 static bool sk_lookup_is_valid_access(int off, int size,
11458                                       enum bpf_access_type type,
11459                                       const struct bpf_prog *prog,
11460                                       struct bpf_insn_access_aux *info)
11461 {
11462         if (off < 0 || off >= sizeof(struct bpf_sk_lookup))
11463                 return false;
11464         if (off % size != 0)
11465                 return false;
11466         if (type != BPF_READ)
11467                 return false;
11468
11469         switch (off) {
11470         case offsetof(struct bpf_sk_lookup, sk):
11471                 info->reg_type = PTR_TO_SOCKET_OR_NULL;
11472                 return size == sizeof(__u64);
11473
11474         case bpf_ctx_range(struct bpf_sk_lookup, family):
11475         case bpf_ctx_range(struct bpf_sk_lookup, protocol):
11476         case bpf_ctx_range(struct bpf_sk_lookup, remote_ip4):
11477         case bpf_ctx_range(struct bpf_sk_lookup, local_ip4):
11478         case bpf_ctx_range_till(struct bpf_sk_lookup, remote_ip6[0], remote_ip6[3]):
11479         case bpf_ctx_range_till(struct bpf_sk_lookup, local_ip6[0], local_ip6[3]):
11480         case bpf_ctx_range(struct bpf_sk_lookup, local_port):
11481         case bpf_ctx_range(struct bpf_sk_lookup, ingress_ifindex):
11482                 bpf_ctx_record_field_size(info, sizeof(__u32));
11483                 return bpf_ctx_narrow_access_ok(off, size, sizeof(__u32));
11484
11485         case bpf_ctx_range(struct bpf_sk_lookup, remote_port):
11486                 /* Allow 4-byte access to 2-byte field for backward compatibility */
11487                 if (size == sizeof(__u32))
11488                         return true;
11489                 bpf_ctx_record_field_size(info, sizeof(__be16));
11490                 return bpf_ctx_narrow_access_ok(off, size, sizeof(__be16));
11491
11492         case offsetofend(struct bpf_sk_lookup, remote_port) ...
11493              offsetof(struct bpf_sk_lookup, local_ip4) - 1:
11494                 /* Allow access to zero padding for backward compatibility */
11495                 bpf_ctx_record_field_size(info, sizeof(__u16));
11496                 return bpf_ctx_narrow_access_ok(off, size, sizeof(__u16));
11497
11498         default:
11499                 return false;
11500         }
11501 }
11502
11503 static u32 sk_lookup_convert_ctx_access(enum bpf_access_type type,
11504                                         const struct bpf_insn *si,
11505                                         struct bpf_insn *insn_buf,
11506                                         struct bpf_prog *prog,
11507                                         u32 *target_size)
11508 {
11509         struct bpf_insn *insn = insn_buf;
11510
11511         switch (si->off) {
11512         case offsetof(struct bpf_sk_lookup, sk):
11513                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
11514                                       offsetof(struct bpf_sk_lookup_kern, selected_sk));
11515                 break;
11516
11517         case offsetof(struct bpf_sk_lookup, family):
11518                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11519                                       bpf_target_off(struct bpf_sk_lookup_kern,
11520                                                      family, 2, target_size));
11521                 break;
11522
11523         case offsetof(struct bpf_sk_lookup, protocol):
11524                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11525                                       bpf_target_off(struct bpf_sk_lookup_kern,
11526                                                      protocol, 2, target_size));
11527                 break;
11528
11529         case offsetof(struct bpf_sk_lookup, remote_ip4):
11530                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
11531                                       bpf_target_off(struct bpf_sk_lookup_kern,
11532                                                      v4.saddr, 4, target_size));
11533                 break;
11534
11535         case offsetof(struct bpf_sk_lookup, local_ip4):
11536                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
11537                                       bpf_target_off(struct bpf_sk_lookup_kern,
11538                                                      v4.daddr, 4, target_size));
11539                 break;
11540
11541         case bpf_ctx_range_till(struct bpf_sk_lookup,
11542                                 remote_ip6[0], remote_ip6[3]): {
11543 #if IS_ENABLED(CONFIG_IPV6)
11544                 int off = si->off;
11545
11546                 off -= offsetof(struct bpf_sk_lookup, remote_ip6[0]);
11547                 off += bpf_target_off(struct in6_addr, s6_addr32[0], 4, target_size);
11548                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
11549                                       offsetof(struct bpf_sk_lookup_kern, v6.saddr));
11550                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
11551                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, off);
11552 #else
11553                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11554 #endif
11555                 break;
11556         }
11557         case bpf_ctx_range_till(struct bpf_sk_lookup,
11558                                 local_ip6[0], local_ip6[3]): {
11559 #if IS_ENABLED(CONFIG_IPV6)
11560                 int off = si->off;
11561
11562                 off -= offsetof(struct bpf_sk_lookup, local_ip6[0]);
11563                 off += bpf_target_off(struct in6_addr, s6_addr32[0], 4, target_size);
11564                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
11565                                       offsetof(struct bpf_sk_lookup_kern, v6.daddr));
11566                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
11567                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, off);
11568 #else
11569                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11570 #endif
11571                 break;
11572         }
11573         case offsetof(struct bpf_sk_lookup, remote_port):
11574                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11575                                       bpf_target_off(struct bpf_sk_lookup_kern,
11576                                                      sport, 2, target_size));
11577                 break;
11578
11579         case offsetofend(struct bpf_sk_lookup, remote_port):
11580                 *target_size = 2;
11581                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11582                 break;
11583
11584         case offsetof(struct bpf_sk_lookup, local_port):
11585                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11586                                       bpf_target_off(struct bpf_sk_lookup_kern,
11587                                                      dport, 2, target_size));
11588                 break;
11589
11590         case offsetof(struct bpf_sk_lookup, ingress_ifindex):
11591                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
11592                                       bpf_target_off(struct bpf_sk_lookup_kern,
11593                                                      ingress_ifindex, 4, target_size));
11594                 break;
11595         }
11596
11597         return insn - insn_buf;
11598 }
11599
11600 const struct bpf_prog_ops sk_lookup_prog_ops = {
11601         .test_run = bpf_prog_test_run_sk_lookup,
11602 };
11603
11604 const struct bpf_verifier_ops sk_lookup_verifier_ops = {
11605         .get_func_proto         = sk_lookup_func_proto,
11606         .is_valid_access        = sk_lookup_is_valid_access,
11607         .convert_ctx_access     = sk_lookup_convert_ctx_access,
11608 };
11609
11610 #endif /* CONFIG_INET */
11611
11612 DEFINE_BPF_DISPATCHER(xdp)
11613
11614 void bpf_prog_change_xdp(struct bpf_prog *prev_prog, struct bpf_prog *prog)
11615 {
11616         bpf_dispatcher_change_prog(BPF_DISPATCHER_PTR(xdp), prev_prog, prog);
11617 }
11618
11619 BTF_ID_LIST_GLOBAL(btf_sock_ids, MAX_BTF_SOCK_TYPE)
11620 #define BTF_SOCK_TYPE(name, type) BTF_ID(struct, type)
11621 BTF_SOCK_TYPE_xxx
11622 #undef BTF_SOCK_TYPE
11623
11624 BPF_CALL_1(bpf_skc_to_tcp6_sock, struct sock *, sk)
11625 {
11626         /* tcp6_sock type is not generated in dwarf and hence btf,
11627          * trigger an explicit type generation here.
11628          */
11629         BTF_TYPE_EMIT(struct tcp6_sock);
11630         if (sk && sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP &&
11631             sk->sk_family == AF_INET6)
11632                 return (unsigned long)sk;
11633
11634         return (unsigned long)NULL;
11635 }
11636
11637 const struct bpf_func_proto bpf_skc_to_tcp6_sock_proto = {
11638         .func                   = bpf_skc_to_tcp6_sock,
11639         .gpl_only               = false,
11640         .ret_type               = RET_PTR_TO_BTF_ID_OR_NULL,
11641         .arg1_type              = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11642         .ret_btf_id             = &btf_sock_ids[BTF_SOCK_TYPE_TCP6],
11643 };
11644
11645 BPF_CALL_1(bpf_skc_to_tcp_sock, struct sock *, sk)
11646 {
11647         if (sk && sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP)
11648                 return (unsigned long)sk;
11649
11650         return (unsigned long)NULL;
11651 }
11652
11653 const struct bpf_func_proto bpf_skc_to_tcp_sock_proto = {
11654         .func                   = bpf_skc_to_tcp_sock,
11655         .gpl_only               = false,
11656         .ret_type               = RET_PTR_TO_BTF_ID_OR_NULL,
11657         .arg1_type              = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11658         .ret_btf_id             = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
11659 };
11660
11661 BPF_CALL_1(bpf_skc_to_tcp_timewait_sock, struct sock *, sk)
11662 {
11663         /* BTF types for tcp_timewait_sock and inet_timewait_sock are not
11664          * generated if CONFIG_INET=n. Trigger an explicit generation here.
11665          */
11666         BTF_TYPE_EMIT(struct inet_timewait_sock);
11667         BTF_TYPE_EMIT(struct tcp_timewait_sock);
11668
11669 #ifdef CONFIG_INET
11670         if (sk && sk->sk_prot == &tcp_prot && sk->sk_state == TCP_TIME_WAIT)
11671                 return (unsigned long)sk;
11672 #endif
11673
11674 #if IS_BUILTIN(CONFIG_IPV6)
11675         if (sk && sk->sk_prot == &tcpv6_prot && sk->sk_state == TCP_TIME_WAIT)
11676                 return (unsigned long)sk;
11677 #endif
11678
11679         return (unsigned long)NULL;
11680 }
11681
11682 const struct bpf_func_proto bpf_skc_to_tcp_timewait_sock_proto = {
11683         .func                   = bpf_skc_to_tcp_timewait_sock,
11684         .gpl_only               = false,
11685         .ret_type               = RET_PTR_TO_BTF_ID_OR_NULL,
11686         .arg1_type              = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11687         .ret_btf_id             = &btf_sock_ids[BTF_SOCK_TYPE_TCP_TW],
11688 };
11689
11690 BPF_CALL_1(bpf_skc_to_tcp_request_sock, struct sock *, sk)
11691 {
11692 #ifdef CONFIG_INET
11693         if (sk && sk->sk_prot == &tcp_prot && sk->sk_state == TCP_NEW_SYN_RECV)
11694                 return (unsigned long)sk;
11695 #endif
11696
11697 #if IS_BUILTIN(CONFIG_IPV6)
11698         if (sk && sk->sk_prot == &tcpv6_prot && sk->sk_state == TCP_NEW_SYN_RECV)
11699                 return (unsigned long)sk;
11700 #endif
11701
11702         return (unsigned long)NULL;
11703 }
11704
11705 const struct bpf_func_proto bpf_skc_to_tcp_request_sock_proto = {
11706         .func                   = bpf_skc_to_tcp_request_sock,
11707         .gpl_only               = false,
11708         .ret_type               = RET_PTR_TO_BTF_ID_OR_NULL,
11709         .arg1_type              = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11710         .ret_btf_id             = &btf_sock_ids[BTF_SOCK_TYPE_TCP_REQ],
11711 };
11712
11713 BPF_CALL_1(bpf_skc_to_udp6_sock, struct sock *, sk)
11714 {
11715         /* udp6_sock type is not generated in dwarf and hence btf,
11716          * trigger an explicit type generation here.
11717          */
11718         BTF_TYPE_EMIT(struct udp6_sock);
11719         if (sk && sk_fullsock(sk) && sk->sk_protocol == IPPROTO_UDP &&
11720             sk->sk_type == SOCK_DGRAM && sk->sk_family == AF_INET6)
11721                 return (unsigned long)sk;
11722
11723         return (unsigned long)NULL;
11724 }
11725
11726 const struct bpf_func_proto bpf_skc_to_udp6_sock_proto = {
11727         .func                   = bpf_skc_to_udp6_sock,
11728         .gpl_only               = false,
11729         .ret_type               = RET_PTR_TO_BTF_ID_OR_NULL,
11730         .arg1_type              = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11731         .ret_btf_id             = &btf_sock_ids[BTF_SOCK_TYPE_UDP6],
11732 };
11733
11734 BPF_CALL_1(bpf_skc_to_unix_sock, struct sock *, sk)
11735 {
11736         /* unix_sock type is not generated in dwarf and hence btf,
11737          * trigger an explicit type generation here.
11738          */
11739         BTF_TYPE_EMIT(struct unix_sock);
11740         if (sk && sk_fullsock(sk) && sk->sk_family == AF_UNIX)
11741                 return (unsigned long)sk;
11742
11743         return (unsigned long)NULL;
11744 }
11745
11746 const struct bpf_func_proto bpf_skc_to_unix_sock_proto = {
11747         .func                   = bpf_skc_to_unix_sock,
11748         .gpl_only               = false,
11749         .ret_type               = RET_PTR_TO_BTF_ID_OR_NULL,
11750         .arg1_type              = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11751         .ret_btf_id             = &btf_sock_ids[BTF_SOCK_TYPE_UNIX],
11752 };
11753
11754 BPF_CALL_1(bpf_skc_to_mptcp_sock, struct sock *, sk)
11755 {
11756         BTF_TYPE_EMIT(struct mptcp_sock);
11757         return (unsigned long)bpf_mptcp_sock_from_subflow(sk);
11758 }
11759
11760 const struct bpf_func_proto bpf_skc_to_mptcp_sock_proto = {
11761         .func           = bpf_skc_to_mptcp_sock,
11762         .gpl_only       = false,
11763         .ret_type       = RET_PTR_TO_BTF_ID_OR_NULL,
11764         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
11765         .ret_btf_id     = &btf_sock_ids[BTF_SOCK_TYPE_MPTCP],
11766 };
11767
11768 BPF_CALL_1(bpf_sock_from_file, struct file *, file)
11769 {
11770         return (unsigned long)sock_from_file(file);
11771 }
11772
11773 BTF_ID_LIST(bpf_sock_from_file_btf_ids)
11774 BTF_ID(struct, socket)
11775 BTF_ID(struct, file)
11776
11777 const struct bpf_func_proto bpf_sock_from_file_proto = {
11778         .func           = bpf_sock_from_file,
11779         .gpl_only       = false,
11780         .ret_type       = RET_PTR_TO_BTF_ID_OR_NULL,
11781         .ret_btf_id     = &bpf_sock_from_file_btf_ids[0],
11782         .arg1_type      = ARG_PTR_TO_BTF_ID,
11783         .arg1_btf_id    = &bpf_sock_from_file_btf_ids[1],
11784 };
11785
11786 static const struct bpf_func_proto *
11787 bpf_sk_base_func_proto(enum bpf_func_id func_id)
11788 {
11789         const struct bpf_func_proto *func;
11790
11791         switch (func_id) {
11792         case BPF_FUNC_skc_to_tcp6_sock:
11793                 func = &bpf_skc_to_tcp6_sock_proto;
11794                 break;
11795         case BPF_FUNC_skc_to_tcp_sock:
11796                 func = &bpf_skc_to_tcp_sock_proto;
11797                 break;
11798         case BPF_FUNC_skc_to_tcp_timewait_sock:
11799                 func = &bpf_skc_to_tcp_timewait_sock_proto;
11800                 break;
11801         case BPF_FUNC_skc_to_tcp_request_sock:
11802                 func = &bpf_skc_to_tcp_request_sock_proto;
11803                 break;
11804         case BPF_FUNC_skc_to_udp6_sock:
11805                 func = &bpf_skc_to_udp6_sock_proto;
11806                 break;
11807         case BPF_FUNC_skc_to_unix_sock:
11808                 func = &bpf_skc_to_unix_sock_proto;
11809                 break;
11810         case BPF_FUNC_skc_to_mptcp_sock:
11811                 func = &bpf_skc_to_mptcp_sock_proto;
11812                 break;
11813         case BPF_FUNC_ktime_get_coarse_ns:
11814                 return &bpf_ktime_get_coarse_ns_proto;
11815         default:
11816                 return bpf_base_func_proto(func_id);
11817         }
11818
11819         if (!perfmon_capable())
11820                 return NULL;
11821
11822         return func;
11823 }
11824
11825 __bpf_kfunc_start_defs();
11826 __bpf_kfunc int bpf_dynptr_from_skb(struct sk_buff *skb, u64 flags,
11827                                     struct bpf_dynptr_kern *ptr__uninit)
11828 {
11829         if (flags) {
11830                 bpf_dynptr_set_null(ptr__uninit);
11831                 return -EINVAL;
11832         }
11833
11834         bpf_dynptr_init(ptr__uninit, skb, BPF_DYNPTR_TYPE_SKB, 0, skb->len);
11835
11836         return 0;
11837 }
11838
11839 __bpf_kfunc int bpf_dynptr_from_xdp(struct xdp_buff *xdp, u64 flags,
11840                                     struct bpf_dynptr_kern *ptr__uninit)
11841 {
11842         if (flags) {
11843                 bpf_dynptr_set_null(ptr__uninit);
11844                 return -EINVAL;
11845         }
11846
11847         bpf_dynptr_init(ptr__uninit, xdp, BPF_DYNPTR_TYPE_XDP, 0, xdp_get_buff_len(xdp));
11848
11849         return 0;
11850 }
11851
11852 __bpf_kfunc int bpf_sock_addr_set_sun_path(struct bpf_sock_addr_kern *sa_kern,
11853                                            const u8 *sun_path, u32 sun_path__sz)
11854 {
11855         struct sockaddr_un *un;
11856
11857         if (sa_kern->sk->sk_family != AF_UNIX)
11858                 return -EINVAL;
11859
11860         /* We do not allow changing the address to unnamed or larger than the
11861          * maximum allowed address size for a unix sockaddr.
11862          */
11863         if (sun_path__sz == 0 || sun_path__sz > UNIX_PATH_MAX)
11864                 return -EINVAL;
11865
11866         un = (struct sockaddr_un *)sa_kern->uaddr;
11867         memcpy(un->sun_path, sun_path, sun_path__sz);
11868         sa_kern->uaddrlen = offsetof(struct sockaddr_un, sun_path) + sun_path__sz;
11869
11870         return 0;
11871 }
11872 __bpf_kfunc_end_defs();
11873
11874 int bpf_dynptr_from_skb_rdonly(struct sk_buff *skb, u64 flags,
11875                                struct bpf_dynptr_kern *ptr__uninit)
11876 {
11877         int err;
11878
11879         err = bpf_dynptr_from_skb(skb, flags, ptr__uninit);
11880         if (err)
11881                 return err;
11882
11883         bpf_dynptr_set_rdonly(ptr__uninit);
11884
11885         return 0;
11886 }
11887
11888 BTF_SET8_START(bpf_kfunc_check_set_skb)
11889 BTF_ID_FLAGS(func, bpf_dynptr_from_skb)
11890 BTF_SET8_END(bpf_kfunc_check_set_skb)
11891
11892 BTF_SET8_START(bpf_kfunc_check_set_xdp)
11893 BTF_ID_FLAGS(func, bpf_dynptr_from_xdp)
11894 BTF_SET8_END(bpf_kfunc_check_set_xdp)
11895
11896 BTF_SET8_START(bpf_kfunc_check_set_sock_addr)
11897 BTF_ID_FLAGS(func, bpf_sock_addr_set_sun_path)
11898 BTF_SET8_END(bpf_kfunc_check_set_sock_addr)
11899
11900 static const struct btf_kfunc_id_set bpf_kfunc_set_skb = {
11901         .owner = THIS_MODULE,
11902         .set = &bpf_kfunc_check_set_skb,
11903 };
11904
11905 static const struct btf_kfunc_id_set bpf_kfunc_set_xdp = {
11906         .owner = THIS_MODULE,
11907         .set = &bpf_kfunc_check_set_xdp,
11908 };
11909
11910 static const struct btf_kfunc_id_set bpf_kfunc_set_sock_addr = {
11911         .owner = THIS_MODULE,
11912         .set = &bpf_kfunc_check_set_sock_addr,
11913 };
11914
11915 static int __init bpf_kfunc_init(void)
11916 {
11917         int ret;
11918
11919         ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &bpf_kfunc_set_skb);
11920         ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_ACT, &bpf_kfunc_set_skb);
11921         ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SK_SKB, &bpf_kfunc_set_skb);
11922         ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SOCKET_FILTER, &bpf_kfunc_set_skb);
11923         ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SKB, &bpf_kfunc_set_skb);
11924         ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_OUT, &bpf_kfunc_set_skb);
11925         ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_IN, &bpf_kfunc_set_skb);
11926         ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_XMIT, &bpf_kfunc_set_skb);
11927         ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_SEG6LOCAL, &bpf_kfunc_set_skb);
11928         ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_NETFILTER, &bpf_kfunc_set_skb);
11929         ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &bpf_kfunc_set_xdp);
11930         return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
11931                                                 &bpf_kfunc_set_sock_addr);
11932 }
11933 late_initcall(bpf_kfunc_init);
11934
11935 __bpf_kfunc_start_defs();
11936
11937 /* bpf_sock_destroy: Destroy the given socket with ECONNABORTED error code.
11938  *
11939  * The function expects a non-NULL pointer to a socket, and invokes the
11940  * protocol specific socket destroy handlers.
11941  *
11942  * The helper can only be called from BPF contexts that have acquired the socket
11943  * locks.
11944  *
11945  * Parameters:
11946  * @sock: Pointer to socket to be destroyed
11947  *
11948  * Return:
11949  * On error, may return EPROTONOSUPPORT, EINVAL.
11950  * EPROTONOSUPPORT if protocol specific destroy handler is not supported.
11951  * 0 otherwise
11952  */
11953 __bpf_kfunc int bpf_sock_destroy(struct sock_common *sock)
11954 {
11955         struct sock *sk = (struct sock *)sock;
11956
11957         /* The locking semantics that allow for synchronous execution of the
11958          * destroy handlers are only supported for TCP and UDP.
11959          * Supporting protocols will need to acquire sock lock in the BPF context
11960          * prior to invoking this kfunc.
11961          */
11962         if (!sk->sk_prot->diag_destroy || (sk->sk_protocol != IPPROTO_TCP &&
11963                                            sk->sk_protocol != IPPROTO_UDP))
11964                 return -EOPNOTSUPP;
11965
11966         return sk->sk_prot->diag_destroy(sk, ECONNABORTED);
11967 }
11968
11969 __bpf_kfunc_end_defs();
11970
11971 BTF_SET8_START(bpf_sk_iter_kfunc_ids)
11972 BTF_ID_FLAGS(func, bpf_sock_destroy, KF_TRUSTED_ARGS)
11973 BTF_SET8_END(bpf_sk_iter_kfunc_ids)
11974
11975 static int tracing_iter_filter(const struct bpf_prog *prog, u32 kfunc_id)
11976 {
11977         if (btf_id_set8_contains(&bpf_sk_iter_kfunc_ids, kfunc_id) &&
11978             prog->expected_attach_type != BPF_TRACE_ITER)
11979                 return -EACCES;
11980         return 0;
11981 }
11982
11983 static const struct btf_kfunc_id_set bpf_sk_iter_kfunc_set = {
11984         .owner = THIS_MODULE,
11985         .set   = &bpf_sk_iter_kfunc_ids,
11986         .filter = tracing_iter_filter,
11987 };
11988
11989 static int init_subsystem(void)
11990 {
11991         return register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_sk_iter_kfunc_set);
11992 }
11993 late_initcall(init_subsystem);