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