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