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