Merge tag 'powerpc-5.8-1' of git://git.kernel.org/pub/scm/linux/kernel/git/powerpc...
[platform/kernel/linux-starfive.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/module.h>
21 #include <linux/types.h>
22 #include <linux/mm.h>
23 #include <linux/fcntl.h>
24 #include <linux/socket.h>
25 #include <linux/sock_diag.h>
26 #include <linux/in.h>
27 #include <linux/inet.h>
28 #include <linux/netdevice.h>
29 #include <linux/if_packet.h>
30 #include <linux/if_arp.h>
31 #include <linux/gfp.h>
32 #include <net/inet_common.h>
33 #include <net/ip.h>
34 #include <net/protocol.h>
35 #include <net/netlink.h>
36 #include <linux/skbuff.h>
37 #include <linux/skmsg.h>
38 #include <net/sock.h>
39 #include <net/flow_dissector.h>
40 #include <linux/errno.h>
41 #include <linux/timer.h>
42 #include <linux/uaccess.h>
43 #include <asm/unaligned.h>
44 #include <asm/cmpxchg.h>
45 #include <linux/filter.h>
46 #include <linux/ratelimit.h>
47 #include <linux/seccomp.h>
48 #include <linux/if_vlan.h>
49 #include <linux/bpf.h>
50 #include <net/sch_generic.h>
51 #include <net/cls_cgroup.h>
52 #include <net/dst_metadata.h>
53 #include <net/dst.h>
54 #include <net/sock_reuseport.h>
55 #include <net/busy_poll.h>
56 #include <net/tcp.h>
57 #include <net/xfrm.h>
58 #include <net/udp.h>
59 #include <linux/bpf_trace.h>
60 #include <net/xdp_sock.h>
61 #include <linux/inetdevice.h>
62 #include <net/inet_hashtables.h>
63 #include <net/inet6_hashtables.h>
64 #include <net/ip_fib.h>
65 #include <net/nexthop.h>
66 #include <net/flow.h>
67 #include <net/arp.h>
68 #include <net/ipv6.h>
69 #include <net/net_namespace.h>
70 #include <linux/seg6_local.h>
71 #include <net/seg6.h>
72 #include <net/seg6_local.h>
73 #include <net/lwtunnel.h>
74 #include <net/ipv6_stubs.h>
75 #include <net/bpf_sk_storage.h>
76
77 /**
78  *      sk_filter_trim_cap - run a packet through a socket filter
79  *      @sk: sock associated with &sk_buff
80  *      @skb: buffer to filter
81  *      @cap: limit on how short the eBPF program may trim the packet
82  *
83  * Run the eBPF program and then cut skb->data to correct size returned by
84  * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
85  * than pkt_len we keep whole skb->data. This is the socket level
86  * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
87  * be accepted or -EPERM if the packet should be tossed.
88  *
89  */
90 int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
91 {
92         int err;
93         struct sk_filter *filter;
94
95         /*
96          * If the skb was allocated from pfmemalloc reserves, only
97          * allow SOCK_MEMALLOC sockets to use it as this socket is
98          * helping free memory
99          */
100         if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
101                 NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
102                 return -ENOMEM;
103         }
104         err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
105         if (err)
106                 return err;
107
108         err = security_sock_rcv_skb(sk, skb);
109         if (err)
110                 return err;
111
112         rcu_read_lock();
113         filter = rcu_dereference(sk->sk_filter);
114         if (filter) {
115                 struct sock *save_sk = skb->sk;
116                 unsigned int pkt_len;
117
118                 skb->sk = sk;
119                 pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
120                 skb->sk = save_sk;
121                 err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
122         }
123         rcu_read_unlock();
124
125         return err;
126 }
127 EXPORT_SYMBOL(sk_filter_trim_cap);
128
129 BPF_CALL_1(bpf_skb_get_pay_offset, struct sk_buff *, skb)
130 {
131         return skb_get_poff(skb);
132 }
133
134 BPF_CALL_3(bpf_skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
135 {
136         struct nlattr *nla;
137
138         if (skb_is_nonlinear(skb))
139                 return 0;
140
141         if (skb->len < sizeof(struct nlattr))
142                 return 0;
143
144         if (a > skb->len - sizeof(struct nlattr))
145                 return 0;
146
147         nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
148         if (nla)
149                 return (void *) nla - (void *) skb->data;
150
151         return 0;
152 }
153
154 BPF_CALL_3(bpf_skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
155 {
156         struct nlattr *nla;
157
158         if (skb_is_nonlinear(skb))
159                 return 0;
160
161         if (skb->len < sizeof(struct nlattr))
162                 return 0;
163
164         if (a > skb->len - sizeof(struct nlattr))
165                 return 0;
166
167         nla = (struct nlattr *) &skb->data[a];
168         if (nla->nla_len > skb->len - a)
169                 return 0;
170
171         nla = nla_find_nested(nla, x);
172         if (nla)
173                 return (void *) nla - (void *) skb->data;
174
175         return 0;
176 }
177
178 BPF_CALL_4(bpf_skb_load_helper_8, const struct sk_buff *, skb, const void *,
179            data, int, headlen, int, offset)
180 {
181         u8 tmp, *ptr;
182         const int len = sizeof(tmp);
183
184         if (offset >= 0) {
185                 if (headlen - offset >= len)
186                         return *(u8 *)(data + offset);
187                 if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
188                         return tmp;
189         } else {
190                 ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
191                 if (likely(ptr))
192                         return *(u8 *)ptr;
193         }
194
195         return -EFAULT;
196 }
197
198 BPF_CALL_2(bpf_skb_load_helper_8_no_cache, const struct sk_buff *, skb,
199            int, offset)
200 {
201         return ____bpf_skb_load_helper_8(skb, skb->data, skb->len - skb->data_len,
202                                          offset);
203 }
204
205 BPF_CALL_4(bpf_skb_load_helper_16, const struct sk_buff *, skb, const void *,
206            data, int, headlen, int, offset)
207 {
208         u16 tmp, *ptr;
209         const int len = sizeof(tmp);
210
211         if (offset >= 0) {
212                 if (headlen - offset >= len)
213                         return get_unaligned_be16(data + offset);
214                 if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
215                         return be16_to_cpu(tmp);
216         } else {
217                 ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
218                 if (likely(ptr))
219                         return get_unaligned_be16(ptr);
220         }
221
222         return -EFAULT;
223 }
224
225 BPF_CALL_2(bpf_skb_load_helper_16_no_cache, const struct sk_buff *, skb,
226            int, offset)
227 {
228         return ____bpf_skb_load_helper_16(skb, skb->data, skb->len - skb->data_len,
229                                           offset);
230 }
231
232 BPF_CALL_4(bpf_skb_load_helper_32, const struct sk_buff *, skb, const void *,
233            data, int, headlen, int, offset)
234 {
235         u32 tmp, *ptr;
236         const int len = sizeof(tmp);
237
238         if (likely(offset >= 0)) {
239                 if (headlen - offset >= len)
240                         return get_unaligned_be32(data + offset);
241                 if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
242                         return be32_to_cpu(tmp);
243         } else {
244                 ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
245                 if (likely(ptr))
246                         return get_unaligned_be32(ptr);
247         }
248
249         return -EFAULT;
250 }
251
252 BPF_CALL_2(bpf_skb_load_helper_32_no_cache, const struct sk_buff *, skb,
253            int, offset)
254 {
255         return ____bpf_skb_load_helper_32(skb, skb->data, skb->len - skb->data_len,
256                                           offset);
257 }
258
259 static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
260                               struct bpf_insn *insn_buf)
261 {
262         struct bpf_insn *insn = insn_buf;
263
264         switch (skb_field) {
265         case SKF_AD_MARK:
266                 BUILD_BUG_ON(sizeof_field(struct sk_buff, mark) != 4);
267
268                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
269                                       offsetof(struct sk_buff, mark));
270                 break;
271
272         case SKF_AD_PKTTYPE:
273                 *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET());
274                 *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
275 #ifdef __BIG_ENDIAN_BITFIELD
276                 *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
277 #endif
278                 break;
279
280         case SKF_AD_QUEUE:
281                 BUILD_BUG_ON(sizeof_field(struct sk_buff, queue_mapping) != 2);
282
283                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
284                                       offsetof(struct sk_buff, queue_mapping));
285                 break;
286
287         case SKF_AD_VLAN_TAG:
288                 BUILD_BUG_ON(sizeof_field(struct sk_buff, vlan_tci) != 2);
289
290                 /* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
291                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
292                                       offsetof(struct sk_buff, vlan_tci));
293                 break;
294         case SKF_AD_VLAN_TAG_PRESENT:
295                 *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_VLAN_PRESENT_OFFSET());
296                 if (PKT_VLAN_PRESENT_BIT)
297                         *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, PKT_VLAN_PRESENT_BIT);
298                 if (PKT_VLAN_PRESENT_BIT < 7)
299                         *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1);
300                 break;
301         }
302
303         return insn - insn_buf;
304 }
305
306 static bool convert_bpf_extensions(struct sock_filter *fp,
307                                    struct bpf_insn **insnp)
308 {
309         struct bpf_insn *insn = *insnp;
310         u32 cnt;
311
312         switch (fp->k) {
313         case SKF_AD_OFF + SKF_AD_PROTOCOL:
314                 BUILD_BUG_ON(sizeof_field(struct sk_buff, protocol) != 2);
315
316                 /* A = *(u16 *) (CTX + offsetof(protocol)) */
317                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
318                                       offsetof(struct sk_buff, protocol));
319                 /* A = ntohs(A) [emitting a nop or swap16] */
320                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
321                 break;
322
323         case SKF_AD_OFF + SKF_AD_PKTTYPE:
324                 cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
325                 insn += cnt - 1;
326                 break;
327
328         case SKF_AD_OFF + SKF_AD_IFINDEX:
329         case SKF_AD_OFF + SKF_AD_HATYPE:
330                 BUILD_BUG_ON(sizeof_field(struct net_device, ifindex) != 4);
331                 BUILD_BUG_ON(sizeof_field(struct net_device, type) != 2);
332
333                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
334                                       BPF_REG_TMP, BPF_REG_CTX,
335                                       offsetof(struct sk_buff, dev));
336                 /* if (tmp != 0) goto pc + 1 */
337                 *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
338                 *insn++ = BPF_EXIT_INSN();
339                 if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
340                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
341                                             offsetof(struct net_device, ifindex));
342                 else
343                         *insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
344                                             offsetof(struct net_device, type));
345                 break;
346
347         case SKF_AD_OFF + SKF_AD_MARK:
348                 cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
349                 insn += cnt - 1;
350                 break;
351
352         case SKF_AD_OFF + SKF_AD_RXHASH:
353                 BUILD_BUG_ON(sizeof_field(struct sk_buff, hash) != 4);
354
355                 *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
356                                     offsetof(struct sk_buff, hash));
357                 break;
358
359         case SKF_AD_OFF + SKF_AD_QUEUE:
360                 cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
361                 insn += cnt - 1;
362                 break;
363
364         case SKF_AD_OFF + SKF_AD_VLAN_TAG:
365                 cnt = convert_skb_access(SKF_AD_VLAN_TAG,
366                                          BPF_REG_A, BPF_REG_CTX, insn);
367                 insn += cnt - 1;
368                 break;
369
370         case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
371                 cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
372                                          BPF_REG_A, BPF_REG_CTX, insn);
373                 insn += cnt - 1;
374                 break;
375
376         case SKF_AD_OFF + SKF_AD_VLAN_TPID:
377                 BUILD_BUG_ON(sizeof_field(struct sk_buff, vlan_proto) != 2);
378
379                 /* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
380                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
381                                       offsetof(struct sk_buff, vlan_proto));
382                 /* A = ntohs(A) [emitting a nop or swap16] */
383                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
384                 break;
385
386         case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
387         case SKF_AD_OFF + SKF_AD_NLATTR:
388         case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
389         case SKF_AD_OFF + SKF_AD_CPU:
390         case SKF_AD_OFF + SKF_AD_RANDOM:
391                 /* arg1 = CTX */
392                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
393                 /* arg2 = A */
394                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
395                 /* arg3 = X */
396                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
397                 /* Emit call(arg1=CTX, arg2=A, arg3=X) */
398                 switch (fp->k) {
399                 case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
400                         *insn = BPF_EMIT_CALL(bpf_skb_get_pay_offset);
401                         break;
402                 case SKF_AD_OFF + SKF_AD_NLATTR:
403                         *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr);
404                         break;
405                 case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
406                         *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr_nest);
407                         break;
408                 case SKF_AD_OFF + SKF_AD_CPU:
409                         *insn = BPF_EMIT_CALL(bpf_get_raw_cpu_id);
410                         break;
411                 case SKF_AD_OFF + SKF_AD_RANDOM:
412                         *insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
413                         bpf_user_rnd_init_once();
414                         break;
415                 }
416                 break;
417
418         case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
419                 /* A ^= X */
420                 *insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
421                 break;
422
423         default:
424                 /* This is just a dummy call to avoid letting the compiler
425                  * evict __bpf_call_base() as an optimization. Placed here
426                  * where no-one bothers.
427                  */
428                 BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
429                 return false;
430         }
431
432         *insnp = insn;
433         return true;
434 }
435
436 static bool convert_bpf_ld_abs(struct sock_filter *fp, struct bpf_insn **insnp)
437 {
438         const bool unaligned_ok = IS_BUILTIN(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS);
439         int size = bpf_size_to_bytes(BPF_SIZE(fp->code));
440         bool endian = BPF_SIZE(fp->code) == BPF_H ||
441                       BPF_SIZE(fp->code) == BPF_W;
442         bool indirect = BPF_MODE(fp->code) == BPF_IND;
443         const int ip_align = NET_IP_ALIGN;
444         struct bpf_insn *insn = *insnp;
445         int offset = fp->k;
446
447         if (!indirect &&
448             ((unaligned_ok && offset >= 0) ||
449              (!unaligned_ok && offset >= 0 &&
450               offset + ip_align >= 0 &&
451               offset + ip_align % size == 0))) {
452                 bool ldx_off_ok = offset <= S16_MAX;
453
454                 *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_H);
455                 if (offset)
456                         *insn++ = BPF_ALU64_IMM(BPF_SUB, BPF_REG_TMP, offset);
457                 *insn++ = BPF_JMP_IMM(BPF_JSLT, BPF_REG_TMP,
458                                       size, 2 + endian + (!ldx_off_ok * 2));
459                 if (ldx_off_ok) {
460                         *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
461                                               BPF_REG_D, offset);
462                 } else {
463                         *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_D);
464                         *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_TMP, offset);
465                         *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
466                                               BPF_REG_TMP, 0);
467                 }
468                 if (endian)
469                         *insn++ = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, size * 8);
470                 *insn++ = BPF_JMP_A(8);
471         }
472
473         *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
474         *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_D);
475         *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_H);
476         if (!indirect) {
477                 *insn++ = BPF_MOV64_IMM(BPF_REG_ARG4, offset);
478         } else {
479                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG4, BPF_REG_X);
480                 if (fp->k)
481                         *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_ARG4, offset);
482         }
483
484         switch (BPF_SIZE(fp->code)) {
485         case BPF_B:
486                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8);
487                 break;
488         case BPF_H:
489                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16);
490                 break;
491         case BPF_W:
492                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32);
493                 break;
494         default:
495                 return false;
496         }
497
498         *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_A, 0, 2);
499         *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
500         *insn   = BPF_EXIT_INSN();
501
502         *insnp = insn;
503         return true;
504 }
505
506 /**
507  *      bpf_convert_filter - convert filter program
508  *      @prog: the user passed filter program
509  *      @len: the length of the user passed filter program
510  *      @new_prog: allocated 'struct bpf_prog' or NULL
511  *      @new_len: pointer to store length of converted program
512  *      @seen_ld_abs: bool whether we've seen ld_abs/ind
513  *
514  * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
515  * style extended BPF (eBPF).
516  * Conversion workflow:
517  *
518  * 1) First pass for calculating the new program length:
519  *   bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs)
520  *
521  * 2) 2nd pass to remap in two passes: 1st pass finds new
522  *    jump offsets, 2nd pass remapping:
523  *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len, &seen_ld_abs)
524  */
525 static int bpf_convert_filter(struct sock_filter *prog, int len,
526                               struct bpf_prog *new_prog, int *new_len,
527                               bool *seen_ld_abs)
528 {
529         int new_flen = 0, pass = 0, target, i, stack_off;
530         struct bpf_insn *new_insn, *first_insn = NULL;
531         struct sock_filter *fp;
532         int *addrs = NULL;
533         u8 bpf_src;
534
535         BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
536         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
537
538         if (len <= 0 || len > BPF_MAXINSNS)
539                 return -EINVAL;
540
541         if (new_prog) {
542                 first_insn = new_prog->insnsi;
543                 addrs = kcalloc(len, sizeof(*addrs),
544                                 GFP_KERNEL | __GFP_NOWARN);
545                 if (!addrs)
546                         return -ENOMEM;
547         }
548
549 do_pass:
550         new_insn = first_insn;
551         fp = prog;
552
553         /* Classic BPF related prologue emission. */
554         if (new_prog) {
555                 /* Classic BPF expects A and X to be reset first. These need
556                  * to be guaranteed to be the first two instructions.
557                  */
558                 *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
559                 *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
560
561                 /* All programs must keep CTX in callee saved BPF_REG_CTX.
562                  * In eBPF case it's done by the compiler, here we need to
563                  * do this ourself. Initial CTX is present in BPF_REG_ARG1.
564                  */
565                 *new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
566                 if (*seen_ld_abs) {
567                         /* For packet access in classic BPF, cache skb->data
568                          * in callee-saved BPF R8 and skb->len - skb->data_len
569                          * (headlen) in BPF R9. Since classic BPF is read-only
570                          * on CTX, we only need to cache it once.
571                          */
572                         *new_insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
573                                                   BPF_REG_D, BPF_REG_CTX,
574                                                   offsetof(struct sk_buff, data));
575                         *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_H, BPF_REG_CTX,
576                                                   offsetof(struct sk_buff, len));
577                         *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_TMP, BPF_REG_CTX,
578                                                   offsetof(struct sk_buff, data_len));
579                         *new_insn++ = BPF_ALU32_REG(BPF_SUB, BPF_REG_H, BPF_REG_TMP);
580                 }
581         } else {
582                 new_insn += 3;
583         }
584
585         for (i = 0; i < len; fp++, i++) {
586                 struct bpf_insn tmp_insns[32] = { };
587                 struct bpf_insn *insn = tmp_insns;
588
589                 if (addrs)
590                         addrs[i] = new_insn - first_insn;
591
592                 switch (fp->code) {
593                 /* All arithmetic insns and skb loads map as-is. */
594                 case BPF_ALU | BPF_ADD | BPF_X:
595                 case BPF_ALU | BPF_ADD | BPF_K:
596                 case BPF_ALU | BPF_SUB | BPF_X:
597                 case BPF_ALU | BPF_SUB | BPF_K:
598                 case BPF_ALU | BPF_AND | BPF_X:
599                 case BPF_ALU | BPF_AND | BPF_K:
600                 case BPF_ALU | BPF_OR | BPF_X:
601                 case BPF_ALU | BPF_OR | BPF_K:
602                 case BPF_ALU | BPF_LSH | BPF_X:
603                 case BPF_ALU | BPF_LSH | BPF_K:
604                 case BPF_ALU | BPF_RSH | BPF_X:
605                 case BPF_ALU | BPF_RSH | BPF_K:
606                 case BPF_ALU | BPF_XOR | BPF_X:
607                 case BPF_ALU | BPF_XOR | BPF_K:
608                 case BPF_ALU | BPF_MUL | BPF_X:
609                 case BPF_ALU | BPF_MUL | BPF_K:
610                 case BPF_ALU | BPF_DIV | BPF_X:
611                 case BPF_ALU | BPF_DIV | BPF_K:
612                 case BPF_ALU | BPF_MOD | BPF_X:
613                 case BPF_ALU | BPF_MOD | BPF_K:
614                 case BPF_ALU | BPF_NEG:
615                 case BPF_LD | BPF_ABS | BPF_W:
616                 case BPF_LD | BPF_ABS | BPF_H:
617                 case BPF_LD | BPF_ABS | BPF_B:
618                 case BPF_LD | BPF_IND | BPF_W:
619                 case BPF_LD | BPF_IND | BPF_H:
620                 case BPF_LD | BPF_IND | BPF_B:
621                         /* Check for overloaded BPF extension and
622                          * directly convert it if found, otherwise
623                          * just move on with mapping.
624                          */
625                         if (BPF_CLASS(fp->code) == BPF_LD &&
626                             BPF_MODE(fp->code) == BPF_ABS &&
627                             convert_bpf_extensions(fp, &insn))
628                                 break;
629                         if (BPF_CLASS(fp->code) == BPF_LD &&
630                             convert_bpf_ld_abs(fp, &insn)) {
631                                 *seen_ld_abs = true;
632                                 break;
633                         }
634
635                         if (fp->code == (BPF_ALU | BPF_DIV | BPF_X) ||
636                             fp->code == (BPF_ALU | BPF_MOD | BPF_X)) {
637                                 *insn++ = BPF_MOV32_REG(BPF_REG_X, BPF_REG_X);
638                                 /* Error with exception code on div/mod by 0.
639                                  * For cBPF programs, this was always return 0.
640                                  */
641                                 *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_X, 0, 2);
642                                 *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
643                                 *insn++ = BPF_EXIT_INSN();
644                         }
645
646                         *insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
647                         break;
648
649                 /* Jump transformation cannot use BPF block macros
650                  * everywhere as offset calculation and target updates
651                  * require a bit more work than the rest, i.e. jump
652                  * opcodes map as-is, but offsets need adjustment.
653                  */
654
655 #define BPF_EMIT_JMP                                                    \
656         do {                                                            \
657                 const s32 off_min = S16_MIN, off_max = S16_MAX;         \
658                 s32 off;                                                \
659                                                                         \
660                 if (target >= len || target < 0)                        \
661                         goto err;                                       \
662                 off = addrs ? addrs[target] - addrs[i] - 1 : 0;         \
663                 /* Adjust pc relative offset for 2nd or 3rd insn. */    \
664                 off -= insn - tmp_insns;                                \
665                 /* Reject anything not fitting into insn->off. */       \
666                 if (off < off_min || off > off_max)                     \
667                         goto err;                                       \
668                 insn->off = off;                                        \
669         } while (0)
670
671                 case BPF_JMP | BPF_JA:
672                         target = i + fp->k + 1;
673                         insn->code = fp->code;
674                         BPF_EMIT_JMP;
675                         break;
676
677                 case BPF_JMP | BPF_JEQ | BPF_K:
678                 case BPF_JMP | BPF_JEQ | BPF_X:
679                 case BPF_JMP | BPF_JSET | BPF_K:
680                 case BPF_JMP | BPF_JSET | BPF_X:
681                 case BPF_JMP | BPF_JGT | BPF_K:
682                 case BPF_JMP | BPF_JGT | BPF_X:
683                 case BPF_JMP | BPF_JGE | BPF_K:
684                 case BPF_JMP | BPF_JGE | BPF_X:
685                         if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
686                                 /* BPF immediates are signed, zero extend
687                                  * immediate into tmp register and use it
688                                  * in compare insn.
689                                  */
690                                 *insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
691
692                                 insn->dst_reg = BPF_REG_A;
693                                 insn->src_reg = BPF_REG_TMP;
694                                 bpf_src = BPF_X;
695                         } else {
696                                 insn->dst_reg = BPF_REG_A;
697                                 insn->imm = fp->k;
698                                 bpf_src = BPF_SRC(fp->code);
699                                 insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
700                         }
701
702                         /* Common case where 'jump_false' is next insn. */
703                         if (fp->jf == 0) {
704                                 insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
705                                 target = i + fp->jt + 1;
706                                 BPF_EMIT_JMP;
707                                 break;
708                         }
709
710                         /* Convert some jumps when 'jump_true' is next insn. */
711                         if (fp->jt == 0) {
712                                 switch (BPF_OP(fp->code)) {
713                                 case BPF_JEQ:
714                                         insn->code = BPF_JMP | BPF_JNE | bpf_src;
715                                         break;
716                                 case BPF_JGT:
717                                         insn->code = BPF_JMP | BPF_JLE | bpf_src;
718                                         break;
719                                 case BPF_JGE:
720                                         insn->code = BPF_JMP | BPF_JLT | bpf_src;
721                                         break;
722                                 default:
723                                         goto jmp_rest;
724                                 }
725
726                                 target = i + fp->jf + 1;
727                                 BPF_EMIT_JMP;
728                                 break;
729                         }
730 jmp_rest:
731                         /* Other jumps are mapped into two insns: Jxx and JA. */
732                         target = i + fp->jt + 1;
733                         insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
734                         BPF_EMIT_JMP;
735                         insn++;
736
737                         insn->code = BPF_JMP | BPF_JA;
738                         target = i + fp->jf + 1;
739                         BPF_EMIT_JMP;
740                         break;
741
742                 /* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
743                 case BPF_LDX | BPF_MSH | BPF_B: {
744                         struct sock_filter tmp = {
745                                 .code   = BPF_LD | BPF_ABS | BPF_B,
746                                 .k      = fp->k,
747                         };
748
749                         *seen_ld_abs = true;
750
751                         /* X = A */
752                         *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
753                         /* A = BPF_R0 = *(u8 *) (skb->data + K) */
754                         convert_bpf_ld_abs(&tmp, &insn);
755                         insn++;
756                         /* A &= 0xf */
757                         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
758                         /* A <<= 2 */
759                         *insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
760                         /* tmp = X */
761                         *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_X);
762                         /* X = A */
763                         *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
764                         /* A = tmp */
765                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
766                         break;
767                 }
768                 /* RET_K is remaped into 2 insns. RET_A case doesn't need an
769                  * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
770                  */
771                 case BPF_RET | BPF_A:
772                 case BPF_RET | BPF_K:
773                         if (BPF_RVAL(fp->code) == BPF_K)
774                                 *insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
775                                                         0, fp->k);
776                         *insn = BPF_EXIT_INSN();
777                         break;
778
779                 /* Store to stack. */
780                 case BPF_ST:
781                 case BPF_STX:
782                         stack_off = fp->k * 4  + 4;
783                         *insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
784                                             BPF_ST ? BPF_REG_A : BPF_REG_X,
785                                             -stack_off);
786                         /* check_load_and_stores() verifies that classic BPF can
787                          * load from stack only after write, so tracking
788                          * stack_depth for ST|STX insns is enough
789                          */
790                         if (new_prog && new_prog->aux->stack_depth < stack_off)
791                                 new_prog->aux->stack_depth = stack_off;
792                         break;
793
794                 /* Load from stack. */
795                 case BPF_LD | BPF_MEM:
796                 case BPF_LDX | BPF_MEM:
797                         stack_off = fp->k * 4  + 4;
798                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
799                                             BPF_REG_A : BPF_REG_X, BPF_REG_FP,
800                                             -stack_off);
801                         break;
802
803                 /* A = K or X = K */
804                 case BPF_LD | BPF_IMM:
805                 case BPF_LDX | BPF_IMM:
806                         *insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
807                                               BPF_REG_A : BPF_REG_X, fp->k);
808                         break;
809
810                 /* X = A */
811                 case BPF_MISC | BPF_TAX:
812                         *insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
813                         break;
814
815                 /* A = X */
816                 case BPF_MISC | BPF_TXA:
817                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
818                         break;
819
820                 /* A = skb->len or X = skb->len */
821                 case BPF_LD | BPF_W | BPF_LEN:
822                 case BPF_LDX | BPF_W | BPF_LEN:
823                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
824                                             BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
825                                             offsetof(struct sk_buff, len));
826                         break;
827
828                 /* Access seccomp_data fields. */
829                 case BPF_LDX | BPF_ABS | BPF_W:
830                         /* A = *(u32 *) (ctx + K) */
831                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
832                         break;
833
834                 /* Unknown instruction. */
835                 default:
836                         goto err;
837                 }
838
839                 insn++;
840                 if (new_prog)
841                         memcpy(new_insn, tmp_insns,
842                                sizeof(*insn) * (insn - tmp_insns));
843                 new_insn += insn - tmp_insns;
844         }
845
846         if (!new_prog) {
847                 /* Only calculating new length. */
848                 *new_len = new_insn - first_insn;
849                 if (*seen_ld_abs)
850                         *new_len += 4; /* Prologue bits. */
851                 return 0;
852         }
853
854         pass++;
855         if (new_flen != new_insn - first_insn) {
856                 new_flen = new_insn - first_insn;
857                 if (pass > 2)
858                         goto err;
859                 goto do_pass;
860         }
861
862         kfree(addrs);
863         BUG_ON(*new_len != new_flen);
864         return 0;
865 err:
866         kfree(addrs);
867         return -EINVAL;
868 }
869
870 /* Security:
871  *
872  * As we dont want to clear mem[] array for each packet going through
873  * __bpf_prog_run(), we check that filter loaded by user never try to read
874  * a cell if not previously written, and we check all branches to be sure
875  * a malicious user doesn't try to abuse us.
876  */
877 static int check_load_and_stores(const struct sock_filter *filter, int flen)
878 {
879         u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
880         int pc, ret = 0;
881
882         BUILD_BUG_ON(BPF_MEMWORDS > 16);
883
884         masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
885         if (!masks)
886                 return -ENOMEM;
887
888         memset(masks, 0xff, flen * sizeof(*masks));
889
890         for (pc = 0; pc < flen; pc++) {
891                 memvalid &= masks[pc];
892
893                 switch (filter[pc].code) {
894                 case BPF_ST:
895                 case BPF_STX:
896                         memvalid |= (1 << filter[pc].k);
897                         break;
898                 case BPF_LD | BPF_MEM:
899                 case BPF_LDX | BPF_MEM:
900                         if (!(memvalid & (1 << filter[pc].k))) {
901                                 ret = -EINVAL;
902                                 goto error;
903                         }
904                         break;
905                 case BPF_JMP | BPF_JA:
906                         /* A jump must set masks on target */
907                         masks[pc + 1 + filter[pc].k] &= memvalid;
908                         memvalid = ~0;
909                         break;
910                 case BPF_JMP | BPF_JEQ | BPF_K:
911                 case BPF_JMP | BPF_JEQ | BPF_X:
912                 case BPF_JMP | BPF_JGE | BPF_K:
913                 case BPF_JMP | BPF_JGE | BPF_X:
914                 case BPF_JMP | BPF_JGT | BPF_K:
915                 case BPF_JMP | BPF_JGT | BPF_X:
916                 case BPF_JMP | BPF_JSET | BPF_K:
917                 case BPF_JMP | BPF_JSET | BPF_X:
918                         /* A jump must set masks on targets */
919                         masks[pc + 1 + filter[pc].jt] &= memvalid;
920                         masks[pc + 1 + filter[pc].jf] &= memvalid;
921                         memvalid = ~0;
922                         break;
923                 }
924         }
925 error:
926         kfree(masks);
927         return ret;
928 }
929
930 static bool chk_code_allowed(u16 code_to_probe)
931 {
932         static const bool codes[] = {
933                 /* 32 bit ALU operations */
934                 [BPF_ALU | BPF_ADD | BPF_K] = true,
935                 [BPF_ALU | BPF_ADD | BPF_X] = true,
936                 [BPF_ALU | BPF_SUB | BPF_K] = true,
937                 [BPF_ALU | BPF_SUB | BPF_X] = true,
938                 [BPF_ALU | BPF_MUL | BPF_K] = true,
939                 [BPF_ALU | BPF_MUL | BPF_X] = true,
940                 [BPF_ALU | BPF_DIV | BPF_K] = true,
941                 [BPF_ALU | BPF_DIV | BPF_X] = true,
942                 [BPF_ALU | BPF_MOD | BPF_K] = true,
943                 [BPF_ALU | BPF_MOD | BPF_X] = true,
944                 [BPF_ALU | BPF_AND | BPF_K] = true,
945                 [BPF_ALU | BPF_AND | BPF_X] = true,
946                 [BPF_ALU | BPF_OR | BPF_K] = true,
947                 [BPF_ALU | BPF_OR | BPF_X] = true,
948                 [BPF_ALU | BPF_XOR | BPF_K] = true,
949                 [BPF_ALU | BPF_XOR | BPF_X] = true,
950                 [BPF_ALU | BPF_LSH | BPF_K] = true,
951                 [BPF_ALU | BPF_LSH | BPF_X] = true,
952                 [BPF_ALU | BPF_RSH | BPF_K] = true,
953                 [BPF_ALU | BPF_RSH | BPF_X] = true,
954                 [BPF_ALU | BPF_NEG] = true,
955                 /* Load instructions */
956                 [BPF_LD | BPF_W | BPF_ABS] = true,
957                 [BPF_LD | BPF_H | BPF_ABS] = true,
958                 [BPF_LD | BPF_B | BPF_ABS] = true,
959                 [BPF_LD | BPF_W | BPF_LEN] = true,
960                 [BPF_LD | BPF_W | BPF_IND] = true,
961                 [BPF_LD | BPF_H | BPF_IND] = true,
962                 [BPF_LD | BPF_B | BPF_IND] = true,
963                 [BPF_LD | BPF_IMM] = true,
964                 [BPF_LD | BPF_MEM] = true,
965                 [BPF_LDX | BPF_W | BPF_LEN] = true,
966                 [BPF_LDX | BPF_B | BPF_MSH] = true,
967                 [BPF_LDX | BPF_IMM] = true,
968                 [BPF_LDX | BPF_MEM] = true,
969                 /* Store instructions */
970                 [BPF_ST] = true,
971                 [BPF_STX] = true,
972                 /* Misc instructions */
973                 [BPF_MISC | BPF_TAX] = true,
974                 [BPF_MISC | BPF_TXA] = true,
975                 /* Return instructions */
976                 [BPF_RET | BPF_K] = true,
977                 [BPF_RET | BPF_A] = true,
978                 /* Jump instructions */
979                 [BPF_JMP | BPF_JA] = true,
980                 [BPF_JMP | BPF_JEQ | BPF_K] = true,
981                 [BPF_JMP | BPF_JEQ | BPF_X] = true,
982                 [BPF_JMP | BPF_JGE | BPF_K] = true,
983                 [BPF_JMP | BPF_JGE | BPF_X] = true,
984                 [BPF_JMP | BPF_JGT | BPF_K] = true,
985                 [BPF_JMP | BPF_JGT | BPF_X] = true,
986                 [BPF_JMP | BPF_JSET | BPF_K] = true,
987                 [BPF_JMP | BPF_JSET | BPF_X] = true,
988         };
989
990         if (code_to_probe >= ARRAY_SIZE(codes))
991                 return false;
992
993         return codes[code_to_probe];
994 }
995
996 static bool bpf_check_basics_ok(const struct sock_filter *filter,
997                                 unsigned int flen)
998 {
999         if (filter == NULL)
1000                 return false;
1001         if (flen == 0 || flen > BPF_MAXINSNS)
1002                 return false;
1003
1004         return true;
1005 }
1006
1007 /**
1008  *      bpf_check_classic - verify socket filter code
1009  *      @filter: filter to verify
1010  *      @flen: length of filter
1011  *
1012  * Check the user's filter code. If we let some ugly
1013  * filter code slip through kaboom! The filter must contain
1014  * no references or jumps that are out of range, no illegal
1015  * instructions, and must end with a RET instruction.
1016  *
1017  * All jumps are forward as they are not signed.
1018  *
1019  * Returns 0 if the rule set is legal or -EINVAL if not.
1020  */
1021 static int bpf_check_classic(const struct sock_filter *filter,
1022                              unsigned int flen)
1023 {
1024         bool anc_found;
1025         int pc;
1026
1027         /* Check the filter code now */
1028         for (pc = 0; pc < flen; pc++) {
1029                 const struct sock_filter *ftest = &filter[pc];
1030
1031                 /* May we actually operate on this code? */
1032                 if (!chk_code_allowed(ftest->code))
1033                         return -EINVAL;
1034
1035                 /* Some instructions need special checks */
1036                 switch (ftest->code) {
1037                 case BPF_ALU | BPF_DIV | BPF_K:
1038                 case BPF_ALU | BPF_MOD | BPF_K:
1039                         /* Check for division by zero */
1040                         if (ftest->k == 0)
1041                                 return -EINVAL;
1042                         break;
1043                 case BPF_ALU | BPF_LSH | BPF_K:
1044                 case BPF_ALU | BPF_RSH | BPF_K:
1045                         if (ftest->k >= 32)
1046                                 return -EINVAL;
1047                         break;
1048                 case BPF_LD | BPF_MEM:
1049                 case BPF_LDX | BPF_MEM:
1050                 case BPF_ST:
1051                 case BPF_STX:
1052                         /* Check for invalid memory addresses */
1053                         if (ftest->k >= BPF_MEMWORDS)
1054                                 return -EINVAL;
1055                         break;
1056                 case BPF_JMP | BPF_JA:
1057                         /* Note, the large ftest->k might cause loops.
1058                          * Compare this with conditional jumps below,
1059                          * where offsets are limited. --ANK (981016)
1060                          */
1061                         if (ftest->k >= (unsigned int)(flen - pc - 1))
1062                                 return -EINVAL;
1063                         break;
1064                 case BPF_JMP | BPF_JEQ | BPF_K:
1065                 case BPF_JMP | BPF_JEQ | BPF_X:
1066                 case BPF_JMP | BPF_JGE | BPF_K:
1067                 case BPF_JMP | BPF_JGE | BPF_X:
1068                 case BPF_JMP | BPF_JGT | BPF_K:
1069                 case BPF_JMP | BPF_JGT | BPF_X:
1070                 case BPF_JMP | BPF_JSET | BPF_K:
1071                 case BPF_JMP | BPF_JSET | BPF_X:
1072                         /* Both conditionals must be safe */
1073                         if (pc + ftest->jt + 1 >= flen ||
1074                             pc + ftest->jf + 1 >= flen)
1075                                 return -EINVAL;
1076                         break;
1077                 case BPF_LD | BPF_W | BPF_ABS:
1078                 case BPF_LD | BPF_H | BPF_ABS:
1079                 case BPF_LD | BPF_B | BPF_ABS:
1080                         anc_found = false;
1081                         if (bpf_anc_helper(ftest) & BPF_ANC)
1082                                 anc_found = true;
1083                         /* Ancillary operation unknown or unsupported */
1084                         if (anc_found == false && ftest->k >= SKF_AD_OFF)
1085                                 return -EINVAL;
1086                 }
1087         }
1088
1089         /* Last instruction must be a RET code */
1090         switch (filter[flen - 1].code) {
1091         case BPF_RET | BPF_K:
1092         case BPF_RET | BPF_A:
1093                 return check_load_and_stores(filter, flen);
1094         }
1095
1096         return -EINVAL;
1097 }
1098
1099 static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
1100                                       const struct sock_fprog *fprog)
1101 {
1102         unsigned int fsize = bpf_classic_proglen(fprog);
1103         struct sock_fprog_kern *fkprog;
1104
1105         fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
1106         if (!fp->orig_prog)
1107                 return -ENOMEM;
1108
1109         fkprog = fp->orig_prog;
1110         fkprog->len = fprog->len;
1111
1112         fkprog->filter = kmemdup(fp->insns, fsize,
1113                                  GFP_KERNEL | __GFP_NOWARN);
1114         if (!fkprog->filter) {
1115                 kfree(fp->orig_prog);
1116                 return -ENOMEM;
1117         }
1118
1119         return 0;
1120 }
1121
1122 static void bpf_release_orig_filter(struct bpf_prog *fp)
1123 {
1124         struct sock_fprog_kern *fprog = fp->orig_prog;
1125
1126         if (fprog) {
1127                 kfree(fprog->filter);
1128                 kfree(fprog);
1129         }
1130 }
1131
1132 static void __bpf_prog_release(struct bpf_prog *prog)
1133 {
1134         if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
1135                 bpf_prog_put(prog);
1136         } else {
1137                 bpf_release_orig_filter(prog);
1138                 bpf_prog_free(prog);
1139         }
1140 }
1141
1142 static void __sk_filter_release(struct sk_filter *fp)
1143 {
1144         __bpf_prog_release(fp->prog);
1145         kfree(fp);
1146 }
1147
1148 /**
1149  *      sk_filter_release_rcu - Release a socket filter by rcu_head
1150  *      @rcu: rcu_head that contains the sk_filter to free
1151  */
1152 static void sk_filter_release_rcu(struct rcu_head *rcu)
1153 {
1154         struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
1155
1156         __sk_filter_release(fp);
1157 }
1158
1159 /**
1160  *      sk_filter_release - release a socket filter
1161  *      @fp: filter to remove
1162  *
1163  *      Remove a filter from a socket and release its resources.
1164  */
1165 static void sk_filter_release(struct sk_filter *fp)
1166 {
1167         if (refcount_dec_and_test(&fp->refcnt))
1168                 call_rcu(&fp->rcu, sk_filter_release_rcu);
1169 }
1170
1171 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
1172 {
1173         u32 filter_size = bpf_prog_size(fp->prog->len);
1174
1175         atomic_sub(filter_size, &sk->sk_omem_alloc);
1176         sk_filter_release(fp);
1177 }
1178
1179 /* try to charge the socket memory if there is space available
1180  * return true on success
1181  */
1182 static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1183 {
1184         u32 filter_size = bpf_prog_size(fp->prog->len);
1185
1186         /* same check as in sock_kmalloc() */
1187         if (filter_size <= sysctl_optmem_max &&
1188             atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
1189                 atomic_add(filter_size, &sk->sk_omem_alloc);
1190                 return true;
1191         }
1192         return false;
1193 }
1194
1195 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1196 {
1197         if (!refcount_inc_not_zero(&fp->refcnt))
1198                 return false;
1199
1200         if (!__sk_filter_charge(sk, fp)) {
1201                 sk_filter_release(fp);
1202                 return false;
1203         }
1204         return true;
1205 }
1206
1207 static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
1208 {
1209         struct sock_filter *old_prog;
1210         struct bpf_prog *old_fp;
1211         int err, new_len, old_len = fp->len;
1212         bool seen_ld_abs = false;
1213
1214         /* We are free to overwrite insns et al right here as it
1215          * won't be used at this point in time anymore internally
1216          * after the migration to the internal BPF instruction
1217          * representation.
1218          */
1219         BUILD_BUG_ON(sizeof(struct sock_filter) !=
1220                      sizeof(struct bpf_insn));
1221
1222         /* Conversion cannot happen on overlapping memory areas,
1223          * so we need to keep the user BPF around until the 2nd
1224          * pass. At this time, the user BPF is stored in fp->insns.
1225          */
1226         old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
1227                            GFP_KERNEL | __GFP_NOWARN);
1228         if (!old_prog) {
1229                 err = -ENOMEM;
1230                 goto out_err;
1231         }
1232
1233         /* 1st pass: calculate the new program length. */
1234         err = bpf_convert_filter(old_prog, old_len, NULL, &new_len,
1235                                  &seen_ld_abs);
1236         if (err)
1237                 goto out_err_free;
1238
1239         /* Expand fp for appending the new filter representation. */
1240         old_fp = fp;
1241         fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1242         if (!fp) {
1243                 /* The old_fp is still around in case we couldn't
1244                  * allocate new memory, so uncharge on that one.
1245                  */
1246                 fp = old_fp;
1247                 err = -ENOMEM;
1248                 goto out_err_free;
1249         }
1250
1251         fp->len = new_len;
1252
1253         /* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1254         err = bpf_convert_filter(old_prog, old_len, fp, &new_len,
1255                                  &seen_ld_abs);
1256         if (err)
1257                 /* 2nd bpf_convert_filter() can fail only if it fails
1258                  * to allocate memory, remapping must succeed. Note,
1259                  * that at this time old_fp has already been released
1260                  * by krealloc().
1261                  */
1262                 goto out_err_free;
1263
1264         fp = bpf_prog_select_runtime(fp, &err);
1265         if (err)
1266                 goto out_err_free;
1267
1268         kfree(old_prog);
1269         return fp;
1270
1271 out_err_free:
1272         kfree(old_prog);
1273 out_err:
1274         __bpf_prog_release(fp);
1275         return ERR_PTR(err);
1276 }
1277
1278 static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
1279                                            bpf_aux_classic_check_t trans)
1280 {
1281         int err;
1282
1283         fp->bpf_func = NULL;
1284         fp->jited = 0;
1285
1286         err = bpf_check_classic(fp->insns, fp->len);
1287         if (err) {
1288                 __bpf_prog_release(fp);
1289                 return ERR_PTR(err);
1290         }
1291
1292         /* There might be additional checks and transformations
1293          * needed on classic filters, f.e. in case of seccomp.
1294          */
1295         if (trans) {
1296                 err = trans(fp->insns, fp->len);
1297                 if (err) {
1298                         __bpf_prog_release(fp);
1299                         return ERR_PTR(err);
1300                 }
1301         }
1302
1303         /* Probe if we can JIT compile the filter and if so, do
1304          * the compilation of the filter.
1305          */
1306         bpf_jit_compile(fp);
1307
1308         /* JIT compiler couldn't process this filter, so do the
1309          * internal BPF translation for the optimized interpreter.
1310          */
1311         if (!fp->jited)
1312                 fp = bpf_migrate_filter(fp);
1313
1314         return fp;
1315 }
1316
1317 /**
1318  *      bpf_prog_create - create an unattached filter
1319  *      @pfp: the unattached filter that is created
1320  *      @fprog: the filter program
1321  *
1322  * Create a filter independent of any socket. We first run some
1323  * sanity checks on it to make sure it does not explode on us later.
1324  * If an error occurs or there is insufficient memory for the filter
1325  * a negative errno code is returned. On success the return is zero.
1326  */
1327 int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1328 {
1329         unsigned int fsize = bpf_classic_proglen(fprog);
1330         struct bpf_prog *fp;
1331
1332         /* Make sure new filter is there and in the right amounts. */
1333         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1334                 return -EINVAL;
1335
1336         fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1337         if (!fp)
1338                 return -ENOMEM;
1339
1340         memcpy(fp->insns, fprog->filter, fsize);
1341
1342         fp->len = fprog->len;
1343         /* Since unattached filters are not copied back to user
1344          * space through sk_get_filter(), we do not need to hold
1345          * a copy here, and can spare us the work.
1346          */
1347         fp->orig_prog = NULL;
1348
1349         /* bpf_prepare_filter() already takes care of freeing
1350          * memory in case something goes wrong.
1351          */
1352         fp = bpf_prepare_filter(fp, NULL);
1353         if (IS_ERR(fp))
1354                 return PTR_ERR(fp);
1355
1356         *pfp = fp;
1357         return 0;
1358 }
1359 EXPORT_SYMBOL_GPL(bpf_prog_create);
1360
1361 /**
1362  *      bpf_prog_create_from_user - create an unattached filter from user buffer
1363  *      @pfp: the unattached filter that is created
1364  *      @fprog: the filter program
1365  *      @trans: post-classic verifier transformation handler
1366  *      @save_orig: save classic BPF program
1367  *
1368  * This function effectively does the same as bpf_prog_create(), only
1369  * that it builds up its insns buffer from user space provided buffer.
1370  * It also allows for passing a bpf_aux_classic_check_t handler.
1371  */
1372 int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1373                               bpf_aux_classic_check_t trans, bool save_orig)
1374 {
1375         unsigned int fsize = bpf_classic_proglen(fprog);
1376         struct bpf_prog *fp;
1377         int err;
1378
1379         /* Make sure new filter is there and in the right amounts. */
1380         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1381                 return -EINVAL;
1382
1383         fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1384         if (!fp)
1385                 return -ENOMEM;
1386
1387         if (copy_from_user(fp->insns, fprog->filter, fsize)) {
1388                 __bpf_prog_free(fp);
1389                 return -EFAULT;
1390         }
1391
1392         fp->len = fprog->len;
1393         fp->orig_prog = NULL;
1394
1395         if (save_orig) {
1396                 err = bpf_prog_store_orig_filter(fp, fprog);
1397                 if (err) {
1398                         __bpf_prog_free(fp);
1399                         return -ENOMEM;
1400                 }
1401         }
1402
1403         /* bpf_prepare_filter() already takes care of freeing
1404          * memory in case something goes wrong.
1405          */
1406         fp = bpf_prepare_filter(fp, trans);
1407         if (IS_ERR(fp))
1408                 return PTR_ERR(fp);
1409
1410         *pfp = fp;
1411         return 0;
1412 }
1413 EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1414
1415 void bpf_prog_destroy(struct bpf_prog *fp)
1416 {
1417         __bpf_prog_release(fp);
1418 }
1419 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1420
1421 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1422 {
1423         struct sk_filter *fp, *old_fp;
1424
1425         fp = kmalloc(sizeof(*fp), GFP_KERNEL);
1426         if (!fp)
1427                 return -ENOMEM;
1428
1429         fp->prog = prog;
1430
1431         if (!__sk_filter_charge(sk, fp)) {
1432                 kfree(fp);
1433                 return -ENOMEM;
1434         }
1435         refcount_set(&fp->refcnt, 1);
1436
1437         old_fp = rcu_dereference_protected(sk->sk_filter,
1438                                            lockdep_sock_is_held(sk));
1439         rcu_assign_pointer(sk->sk_filter, fp);
1440
1441         if (old_fp)
1442                 sk_filter_uncharge(sk, old_fp);
1443
1444         return 0;
1445 }
1446
1447 static
1448 struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
1449 {
1450         unsigned int fsize = bpf_classic_proglen(fprog);
1451         struct bpf_prog *prog;
1452         int err;
1453
1454         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1455                 return ERR_PTR(-EPERM);
1456
1457         /* Make sure new filter is there and in the right amounts. */
1458         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1459                 return ERR_PTR(-EINVAL);
1460
1461         prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1462         if (!prog)
1463                 return ERR_PTR(-ENOMEM);
1464
1465         if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1466                 __bpf_prog_free(prog);
1467                 return ERR_PTR(-EFAULT);
1468         }
1469
1470         prog->len = fprog->len;
1471
1472         err = bpf_prog_store_orig_filter(prog, fprog);
1473         if (err) {
1474                 __bpf_prog_free(prog);
1475                 return ERR_PTR(-ENOMEM);
1476         }
1477
1478         /* bpf_prepare_filter() already takes care of freeing
1479          * memory in case something goes wrong.
1480          */
1481         return bpf_prepare_filter(prog, NULL);
1482 }
1483
1484 /**
1485  *      sk_attach_filter - attach a socket filter
1486  *      @fprog: the filter program
1487  *      @sk: the socket to use
1488  *
1489  * Attach the user's filter code. We first run some sanity checks on
1490  * it to make sure it does not explode on us later. If an error
1491  * occurs or there is insufficient memory for the filter a negative
1492  * errno code is returned. On success the return is zero.
1493  */
1494 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1495 {
1496         struct bpf_prog *prog = __get_filter(fprog, sk);
1497         int err;
1498
1499         if (IS_ERR(prog))
1500                 return PTR_ERR(prog);
1501
1502         err = __sk_attach_prog(prog, sk);
1503         if (err < 0) {
1504                 __bpf_prog_release(prog);
1505                 return err;
1506         }
1507
1508         return 0;
1509 }
1510 EXPORT_SYMBOL_GPL(sk_attach_filter);
1511
1512 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1513 {
1514         struct bpf_prog *prog = __get_filter(fprog, sk);
1515         int err;
1516
1517         if (IS_ERR(prog))
1518                 return PTR_ERR(prog);
1519
1520         if (bpf_prog_size(prog->len) > sysctl_optmem_max)
1521                 err = -ENOMEM;
1522         else
1523                 err = reuseport_attach_prog(sk, prog);
1524
1525         if (err)
1526                 __bpf_prog_release(prog);
1527
1528         return err;
1529 }
1530
1531 static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
1532 {
1533         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1534                 return ERR_PTR(-EPERM);
1535
1536         return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1537 }
1538
1539 int sk_attach_bpf(u32 ufd, struct sock *sk)
1540 {
1541         struct bpf_prog *prog = __get_bpf(ufd, sk);
1542         int err;
1543
1544         if (IS_ERR(prog))
1545                 return PTR_ERR(prog);
1546
1547         err = __sk_attach_prog(prog, sk);
1548         if (err < 0) {
1549                 bpf_prog_put(prog);
1550                 return err;
1551         }
1552
1553         return 0;
1554 }
1555
1556 int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
1557 {
1558         struct bpf_prog *prog;
1559         int err;
1560
1561         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1562                 return -EPERM;
1563
1564         prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1565         if (PTR_ERR(prog) == -EINVAL)
1566                 prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SK_REUSEPORT);
1567         if (IS_ERR(prog))
1568                 return PTR_ERR(prog);
1569
1570         if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) {
1571                 /* Like other non BPF_PROG_TYPE_SOCKET_FILTER
1572                  * bpf prog (e.g. sockmap).  It depends on the
1573                  * limitation imposed by bpf_prog_load().
1574                  * Hence, sysctl_optmem_max is not checked.
1575                  */
1576                 if ((sk->sk_type != SOCK_STREAM &&
1577                      sk->sk_type != SOCK_DGRAM) ||
1578                     (sk->sk_protocol != IPPROTO_UDP &&
1579                      sk->sk_protocol != IPPROTO_TCP) ||
1580                     (sk->sk_family != AF_INET &&
1581                      sk->sk_family != AF_INET6)) {
1582                         err = -ENOTSUPP;
1583                         goto err_prog_put;
1584                 }
1585         } else {
1586                 /* BPF_PROG_TYPE_SOCKET_FILTER */
1587                 if (bpf_prog_size(prog->len) > sysctl_optmem_max) {
1588                         err = -ENOMEM;
1589                         goto err_prog_put;
1590                 }
1591         }
1592
1593         err = reuseport_attach_prog(sk, prog);
1594 err_prog_put:
1595         if (err)
1596                 bpf_prog_put(prog);
1597
1598         return err;
1599 }
1600
1601 void sk_reuseport_prog_free(struct bpf_prog *prog)
1602 {
1603         if (!prog)
1604                 return;
1605
1606         if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT)
1607                 bpf_prog_put(prog);
1608         else
1609                 bpf_prog_destroy(prog);
1610 }
1611
1612 struct bpf_scratchpad {
1613         union {
1614                 __be32 diff[MAX_BPF_STACK / sizeof(__be32)];
1615                 u8     buff[MAX_BPF_STACK];
1616         };
1617 };
1618
1619 static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp);
1620
1621 static inline int __bpf_try_make_writable(struct sk_buff *skb,
1622                                           unsigned int write_len)
1623 {
1624         return skb_ensure_writable(skb, write_len);
1625 }
1626
1627 static inline int bpf_try_make_writable(struct sk_buff *skb,
1628                                         unsigned int write_len)
1629 {
1630         int err = __bpf_try_make_writable(skb, write_len);
1631
1632         bpf_compute_data_pointers(skb);
1633         return err;
1634 }
1635
1636 static int bpf_try_make_head_writable(struct sk_buff *skb)
1637 {
1638         return bpf_try_make_writable(skb, skb_headlen(skb));
1639 }
1640
1641 static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
1642 {
1643         if (skb_at_tc_ingress(skb))
1644                 skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1645 }
1646
1647 static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
1648 {
1649         if (skb_at_tc_ingress(skb))
1650                 skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1651 }
1652
1653 BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
1654            const void *, from, u32, len, u64, flags)
1655 {
1656         void *ptr;
1657
1658         if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1659                 return -EINVAL;
1660         if (unlikely(offset > 0xffff))
1661                 return -EFAULT;
1662         if (unlikely(bpf_try_make_writable(skb, offset + len)))
1663                 return -EFAULT;
1664
1665         ptr = skb->data + offset;
1666         if (flags & BPF_F_RECOMPUTE_CSUM)
1667                 __skb_postpull_rcsum(skb, ptr, len, offset);
1668
1669         memcpy(ptr, from, len);
1670
1671         if (flags & BPF_F_RECOMPUTE_CSUM)
1672                 __skb_postpush_rcsum(skb, ptr, len, offset);
1673         if (flags & BPF_F_INVALIDATE_HASH)
1674                 skb_clear_hash(skb);
1675
1676         return 0;
1677 }
1678
1679 static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1680         .func           = bpf_skb_store_bytes,
1681         .gpl_only       = false,
1682         .ret_type       = RET_INTEGER,
1683         .arg1_type      = ARG_PTR_TO_CTX,
1684         .arg2_type      = ARG_ANYTHING,
1685         .arg3_type      = ARG_PTR_TO_MEM,
1686         .arg4_type      = ARG_CONST_SIZE,
1687         .arg5_type      = ARG_ANYTHING,
1688 };
1689
1690 BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
1691            void *, to, u32, len)
1692 {
1693         void *ptr;
1694
1695         if (unlikely(offset > 0xffff))
1696                 goto err_clear;
1697
1698         ptr = skb_header_pointer(skb, offset, len, to);
1699         if (unlikely(!ptr))
1700                 goto err_clear;
1701         if (ptr != to)
1702                 memcpy(to, ptr, len);
1703
1704         return 0;
1705 err_clear:
1706         memset(to, 0, len);
1707         return -EFAULT;
1708 }
1709
1710 static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1711         .func           = bpf_skb_load_bytes,
1712         .gpl_only       = false,
1713         .ret_type       = RET_INTEGER,
1714         .arg1_type      = ARG_PTR_TO_CTX,
1715         .arg2_type      = ARG_ANYTHING,
1716         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1717         .arg4_type      = ARG_CONST_SIZE,
1718 };
1719
1720 BPF_CALL_4(bpf_flow_dissector_load_bytes,
1721            const struct bpf_flow_dissector *, ctx, u32, offset,
1722            void *, to, u32, len)
1723 {
1724         void *ptr;
1725
1726         if (unlikely(offset > 0xffff))
1727                 goto err_clear;
1728
1729         if (unlikely(!ctx->skb))
1730                 goto err_clear;
1731
1732         ptr = skb_header_pointer(ctx->skb, offset, len, to);
1733         if (unlikely(!ptr))
1734                 goto err_clear;
1735         if (ptr != to)
1736                 memcpy(to, ptr, len);
1737
1738         return 0;
1739 err_clear:
1740         memset(to, 0, len);
1741         return -EFAULT;
1742 }
1743
1744 static const struct bpf_func_proto bpf_flow_dissector_load_bytes_proto = {
1745         .func           = bpf_flow_dissector_load_bytes,
1746         .gpl_only       = false,
1747         .ret_type       = RET_INTEGER,
1748         .arg1_type      = ARG_PTR_TO_CTX,
1749         .arg2_type      = ARG_ANYTHING,
1750         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1751         .arg4_type      = ARG_CONST_SIZE,
1752 };
1753
1754 BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb,
1755            u32, offset, void *, to, u32, len, u32, start_header)
1756 {
1757         u8 *end = skb_tail_pointer(skb);
1758         u8 *net = skb_network_header(skb);
1759         u8 *mac = skb_mac_header(skb);
1760         u8 *ptr;
1761
1762         if (unlikely(offset > 0xffff || len > (end - mac)))
1763                 goto err_clear;
1764
1765         switch (start_header) {
1766         case BPF_HDR_START_MAC:
1767                 ptr = mac + offset;
1768                 break;
1769         case BPF_HDR_START_NET:
1770                 ptr = net + offset;
1771                 break;
1772         default:
1773                 goto err_clear;
1774         }
1775
1776         if (likely(ptr >= mac && ptr + len <= end)) {
1777                 memcpy(to, ptr, len);
1778                 return 0;
1779         }
1780
1781 err_clear:
1782         memset(to, 0, len);
1783         return -EFAULT;
1784 }
1785
1786 static const struct bpf_func_proto bpf_skb_load_bytes_relative_proto = {
1787         .func           = bpf_skb_load_bytes_relative,
1788         .gpl_only       = false,
1789         .ret_type       = RET_INTEGER,
1790         .arg1_type      = ARG_PTR_TO_CTX,
1791         .arg2_type      = ARG_ANYTHING,
1792         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1793         .arg4_type      = ARG_CONST_SIZE,
1794         .arg5_type      = ARG_ANYTHING,
1795 };
1796
1797 BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
1798 {
1799         /* Idea is the following: should the needed direct read/write
1800          * test fail during runtime, we can pull in more data and redo
1801          * again, since implicitly, we invalidate previous checks here.
1802          *
1803          * Or, since we know how much we need to make read/writeable,
1804          * this can be done once at the program beginning for direct
1805          * access case. By this we overcome limitations of only current
1806          * headroom being accessible.
1807          */
1808         return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
1809 }
1810
1811 static const struct bpf_func_proto bpf_skb_pull_data_proto = {
1812         .func           = bpf_skb_pull_data,
1813         .gpl_only       = false,
1814         .ret_type       = RET_INTEGER,
1815         .arg1_type      = ARG_PTR_TO_CTX,
1816         .arg2_type      = ARG_ANYTHING,
1817 };
1818
1819 BPF_CALL_1(bpf_sk_fullsock, struct sock *, sk)
1820 {
1821         return sk_fullsock(sk) ? (unsigned long)sk : (unsigned long)NULL;
1822 }
1823
1824 static const struct bpf_func_proto bpf_sk_fullsock_proto = {
1825         .func           = bpf_sk_fullsock,
1826         .gpl_only       = false,
1827         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
1828         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
1829 };
1830
1831 static inline int sk_skb_try_make_writable(struct sk_buff *skb,
1832                                            unsigned int write_len)
1833 {
1834         int err = __bpf_try_make_writable(skb, write_len);
1835
1836         bpf_compute_data_end_sk_skb(skb);
1837         return err;
1838 }
1839
1840 BPF_CALL_2(sk_skb_pull_data, struct sk_buff *, skb, u32, len)
1841 {
1842         /* Idea is the following: should the needed direct read/write
1843          * test fail during runtime, we can pull in more data and redo
1844          * again, since implicitly, we invalidate previous checks here.
1845          *
1846          * Or, since we know how much we need to make read/writeable,
1847          * this can be done once at the program beginning for direct
1848          * access case. By this we overcome limitations of only current
1849          * headroom being accessible.
1850          */
1851         return sk_skb_try_make_writable(skb, len ? : skb_headlen(skb));
1852 }
1853
1854 static const struct bpf_func_proto sk_skb_pull_data_proto = {
1855         .func           = sk_skb_pull_data,
1856         .gpl_only       = false,
1857         .ret_type       = RET_INTEGER,
1858         .arg1_type      = ARG_PTR_TO_CTX,
1859         .arg2_type      = ARG_ANYTHING,
1860 };
1861
1862 BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
1863            u64, from, u64, to, u64, flags)
1864 {
1865         __sum16 *ptr;
1866
1867         if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
1868                 return -EINVAL;
1869         if (unlikely(offset > 0xffff || offset & 1))
1870                 return -EFAULT;
1871         if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1872                 return -EFAULT;
1873
1874         ptr = (__sum16 *)(skb->data + offset);
1875         switch (flags & BPF_F_HDR_FIELD_MASK) {
1876         case 0:
1877                 if (unlikely(from != 0))
1878                         return -EINVAL;
1879
1880                 csum_replace_by_diff(ptr, to);
1881                 break;
1882         case 2:
1883                 csum_replace2(ptr, from, to);
1884                 break;
1885         case 4:
1886                 csum_replace4(ptr, from, to);
1887                 break;
1888         default:
1889                 return -EINVAL;
1890         }
1891
1892         return 0;
1893 }
1894
1895 static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1896         .func           = bpf_l3_csum_replace,
1897         .gpl_only       = false,
1898         .ret_type       = RET_INTEGER,
1899         .arg1_type      = ARG_PTR_TO_CTX,
1900         .arg2_type      = ARG_ANYTHING,
1901         .arg3_type      = ARG_ANYTHING,
1902         .arg4_type      = ARG_ANYTHING,
1903         .arg5_type      = ARG_ANYTHING,
1904 };
1905
1906 BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
1907            u64, from, u64, to, u64, flags)
1908 {
1909         bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1910         bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1911         bool do_mforce = flags & BPF_F_MARK_ENFORCE;
1912         __sum16 *ptr;
1913
1914         if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
1915                                BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK)))
1916                 return -EINVAL;
1917         if (unlikely(offset > 0xffff || offset & 1))
1918                 return -EFAULT;
1919         if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1920                 return -EFAULT;
1921
1922         ptr = (__sum16 *)(skb->data + offset);
1923         if (is_mmzero && !do_mforce && !*ptr)
1924                 return 0;
1925
1926         switch (flags & BPF_F_HDR_FIELD_MASK) {
1927         case 0:
1928                 if (unlikely(from != 0))
1929                         return -EINVAL;
1930
1931                 inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
1932                 break;
1933         case 2:
1934                 inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
1935                 break;
1936         case 4:
1937                 inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
1938                 break;
1939         default:
1940                 return -EINVAL;
1941         }
1942
1943         if (is_mmzero && !*ptr)
1944                 *ptr = CSUM_MANGLED_0;
1945         return 0;
1946 }
1947
1948 static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1949         .func           = bpf_l4_csum_replace,
1950         .gpl_only       = false,
1951         .ret_type       = RET_INTEGER,
1952         .arg1_type      = ARG_PTR_TO_CTX,
1953         .arg2_type      = ARG_ANYTHING,
1954         .arg3_type      = ARG_ANYTHING,
1955         .arg4_type      = ARG_ANYTHING,
1956         .arg5_type      = ARG_ANYTHING,
1957 };
1958
1959 BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
1960            __be32 *, to, u32, to_size, __wsum, seed)
1961 {
1962         struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1963         u32 diff_size = from_size + to_size;
1964         int i, j = 0;
1965
1966         /* This is quite flexible, some examples:
1967          *
1968          * from_size == 0, to_size > 0,  seed := csum --> pushing data
1969          * from_size > 0,  to_size == 0, seed := csum --> pulling data
1970          * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
1971          *
1972          * Even for diffing, from_size and to_size don't need to be equal.
1973          */
1974         if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) ||
1975                      diff_size > sizeof(sp->diff)))
1976                 return -EINVAL;
1977
1978         for (i = 0; i < from_size / sizeof(__be32); i++, j++)
1979                 sp->diff[j] = ~from[i];
1980         for (i = 0; i <   to_size / sizeof(__be32); i++, j++)
1981                 sp->diff[j] = to[i];
1982
1983         return csum_partial(sp->diff, diff_size, seed);
1984 }
1985
1986 static const struct bpf_func_proto bpf_csum_diff_proto = {
1987         .func           = bpf_csum_diff,
1988         .gpl_only       = false,
1989         .pkt_access     = true,
1990         .ret_type       = RET_INTEGER,
1991         .arg1_type      = ARG_PTR_TO_MEM_OR_NULL,
1992         .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
1993         .arg3_type      = ARG_PTR_TO_MEM_OR_NULL,
1994         .arg4_type      = ARG_CONST_SIZE_OR_ZERO,
1995         .arg5_type      = ARG_ANYTHING,
1996 };
1997
1998 BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
1999 {
2000         /* The interface is to be used in combination with bpf_csum_diff()
2001          * for direct packet writes. csum rotation for alignment as well
2002          * as emulating csum_sub() can be done from the eBPF program.
2003          */
2004         if (skb->ip_summed == CHECKSUM_COMPLETE)
2005                 return (skb->csum = csum_add(skb->csum, csum));
2006
2007         return -ENOTSUPP;
2008 }
2009
2010 static const struct bpf_func_proto bpf_csum_update_proto = {
2011         .func           = bpf_csum_update,
2012         .gpl_only       = false,
2013         .ret_type       = RET_INTEGER,
2014         .arg1_type      = ARG_PTR_TO_CTX,
2015         .arg2_type      = ARG_ANYTHING,
2016 };
2017
2018 BPF_CALL_2(bpf_csum_level, struct sk_buff *, skb, u64, level)
2019 {
2020         /* The interface is to be used in combination with bpf_skb_adjust_room()
2021          * for encap/decap of packet headers when BPF_F_ADJ_ROOM_NO_CSUM_RESET
2022          * is passed as flags, for example.
2023          */
2024         switch (level) {
2025         case BPF_CSUM_LEVEL_INC:
2026                 __skb_incr_checksum_unnecessary(skb);
2027                 break;
2028         case BPF_CSUM_LEVEL_DEC:
2029                 __skb_decr_checksum_unnecessary(skb);
2030                 break;
2031         case BPF_CSUM_LEVEL_RESET:
2032                 __skb_reset_checksum_unnecessary(skb);
2033                 break;
2034         case BPF_CSUM_LEVEL_QUERY:
2035                 return skb->ip_summed == CHECKSUM_UNNECESSARY ?
2036                        skb->csum_level : -EACCES;
2037         default:
2038                 return -EINVAL;
2039         }
2040
2041         return 0;
2042 }
2043
2044 static const struct bpf_func_proto bpf_csum_level_proto = {
2045         .func           = bpf_csum_level,
2046         .gpl_only       = false,
2047         .ret_type       = RET_INTEGER,
2048         .arg1_type      = ARG_PTR_TO_CTX,
2049         .arg2_type      = ARG_ANYTHING,
2050 };
2051
2052 static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
2053 {
2054         return dev_forward_skb(dev, skb);
2055 }
2056
2057 static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
2058                                       struct sk_buff *skb)
2059 {
2060         int ret = ____dev_forward_skb(dev, skb);
2061
2062         if (likely(!ret)) {
2063                 skb->dev = dev;
2064                 ret = netif_rx(skb);
2065         }
2066
2067         return ret;
2068 }
2069
2070 static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
2071 {
2072         int ret;
2073
2074         if (dev_xmit_recursion()) {
2075                 net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2076                 kfree_skb(skb);
2077                 return -ENETDOWN;
2078         }
2079
2080         skb->dev = dev;
2081         skb->tstamp = 0;
2082
2083         dev_xmit_recursion_inc();
2084         ret = dev_queue_xmit(skb);
2085         dev_xmit_recursion_dec();
2086
2087         return ret;
2088 }
2089
2090 static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
2091                                  u32 flags)
2092 {
2093         unsigned int mlen = skb_network_offset(skb);
2094
2095         if (mlen) {
2096                 __skb_pull(skb, mlen);
2097
2098                 /* At ingress, the mac header has already been pulled once.
2099                  * At egress, skb_pospull_rcsum has to be done in case that
2100                  * the skb is originated from ingress (i.e. a forwarded skb)
2101                  * to ensure that rcsum starts at net header.
2102                  */
2103                 if (!skb_at_tc_ingress(skb))
2104                         skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
2105         }
2106         skb_pop_mac_header(skb);
2107         skb_reset_mac_len(skb);
2108         return flags & BPF_F_INGRESS ?
2109                __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
2110 }
2111
2112 static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
2113                                  u32 flags)
2114 {
2115         /* Verify that a link layer header is carried */
2116         if (unlikely(skb->mac_header >= skb->network_header)) {
2117                 kfree_skb(skb);
2118                 return -ERANGE;
2119         }
2120
2121         bpf_push_mac_rcsum(skb);
2122         return flags & BPF_F_INGRESS ?
2123                __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
2124 }
2125
2126 static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
2127                           u32 flags)
2128 {
2129         if (dev_is_mac_header_xmit(dev))
2130                 return __bpf_redirect_common(skb, dev, flags);
2131         else
2132                 return __bpf_redirect_no_mac(skb, dev, flags);
2133 }
2134
2135 BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
2136 {
2137         struct net_device *dev;
2138         struct sk_buff *clone;
2139         int ret;
2140
2141         if (unlikely(flags & ~(BPF_F_INGRESS)))
2142                 return -EINVAL;
2143
2144         dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
2145         if (unlikely(!dev))
2146                 return -EINVAL;
2147
2148         clone = skb_clone(skb, GFP_ATOMIC);
2149         if (unlikely(!clone))
2150                 return -ENOMEM;
2151
2152         /* For direct write, we need to keep the invariant that the skbs
2153          * we're dealing with need to be uncloned. Should uncloning fail
2154          * here, we need to free the just generated clone to unclone once
2155          * again.
2156          */
2157         ret = bpf_try_make_head_writable(skb);
2158         if (unlikely(ret)) {
2159                 kfree_skb(clone);
2160                 return -ENOMEM;
2161         }
2162
2163         return __bpf_redirect(clone, dev, flags);
2164 }
2165
2166 static const struct bpf_func_proto bpf_clone_redirect_proto = {
2167         .func           = bpf_clone_redirect,
2168         .gpl_only       = false,
2169         .ret_type       = RET_INTEGER,
2170         .arg1_type      = ARG_PTR_TO_CTX,
2171         .arg2_type      = ARG_ANYTHING,
2172         .arg3_type      = ARG_ANYTHING,
2173 };
2174
2175 DEFINE_PER_CPU(struct bpf_redirect_info, bpf_redirect_info);
2176 EXPORT_PER_CPU_SYMBOL_GPL(bpf_redirect_info);
2177
2178 BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
2179 {
2180         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2181
2182         if (unlikely(flags & ~(BPF_F_INGRESS)))
2183                 return TC_ACT_SHOT;
2184
2185         ri->flags = flags;
2186         ri->tgt_index = ifindex;
2187
2188         return TC_ACT_REDIRECT;
2189 }
2190
2191 int skb_do_redirect(struct sk_buff *skb)
2192 {
2193         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2194         struct net_device *dev;
2195
2196         dev = dev_get_by_index_rcu(dev_net(skb->dev), ri->tgt_index);
2197         ri->tgt_index = 0;
2198         if (unlikely(!dev)) {
2199                 kfree_skb(skb);
2200                 return -EINVAL;
2201         }
2202
2203         return __bpf_redirect(skb, dev, ri->flags);
2204 }
2205
2206 static const struct bpf_func_proto bpf_redirect_proto = {
2207         .func           = bpf_redirect,
2208         .gpl_only       = false,
2209         .ret_type       = RET_INTEGER,
2210         .arg1_type      = ARG_ANYTHING,
2211         .arg2_type      = ARG_ANYTHING,
2212 };
2213
2214 BPF_CALL_2(bpf_msg_apply_bytes, struct sk_msg *, msg, u32, bytes)
2215 {
2216         msg->apply_bytes = bytes;
2217         return 0;
2218 }
2219
2220 static const struct bpf_func_proto bpf_msg_apply_bytes_proto = {
2221         .func           = bpf_msg_apply_bytes,
2222         .gpl_only       = false,
2223         .ret_type       = RET_INTEGER,
2224         .arg1_type      = ARG_PTR_TO_CTX,
2225         .arg2_type      = ARG_ANYTHING,
2226 };
2227
2228 BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg *, msg, u32, bytes)
2229 {
2230         msg->cork_bytes = bytes;
2231         return 0;
2232 }
2233
2234 static const struct bpf_func_proto bpf_msg_cork_bytes_proto = {
2235         .func           = bpf_msg_cork_bytes,
2236         .gpl_only       = false,
2237         .ret_type       = RET_INTEGER,
2238         .arg1_type      = ARG_PTR_TO_CTX,
2239         .arg2_type      = ARG_ANYTHING,
2240 };
2241
2242 BPF_CALL_4(bpf_msg_pull_data, struct sk_msg *, msg, u32, start,
2243            u32, end, u64, flags)
2244 {
2245         u32 len = 0, offset = 0, copy = 0, poffset = 0, bytes = end - start;
2246         u32 first_sge, last_sge, i, shift, bytes_sg_total;
2247         struct scatterlist *sge;
2248         u8 *raw, *to, *from;
2249         struct page *page;
2250
2251         if (unlikely(flags || end <= start))
2252                 return -EINVAL;
2253
2254         /* First find the starting scatterlist element */
2255         i = msg->sg.start;
2256         do {
2257                 offset += len;
2258                 len = sk_msg_elem(msg, i)->length;
2259                 if (start < offset + len)
2260                         break;
2261                 sk_msg_iter_var_next(i);
2262         } while (i != msg->sg.end);
2263
2264         if (unlikely(start >= offset + len))
2265                 return -EINVAL;
2266
2267         first_sge = i;
2268         /* The start may point into the sg element so we need to also
2269          * account for the headroom.
2270          */
2271         bytes_sg_total = start - offset + bytes;
2272         if (!test_bit(i, &msg->sg.copy) && bytes_sg_total <= len)
2273                 goto out;
2274
2275         /* At this point we need to linearize multiple scatterlist
2276          * elements or a single shared page. Either way we need to
2277          * copy into a linear buffer exclusively owned by BPF. Then
2278          * place the buffer in the scatterlist and fixup the original
2279          * entries by removing the entries now in the linear buffer
2280          * and shifting the remaining entries. For now we do not try
2281          * to copy partial entries to avoid complexity of running out
2282          * of sg_entry slots. The downside is reading a single byte
2283          * will copy the entire sg entry.
2284          */
2285         do {
2286                 copy += sk_msg_elem(msg, i)->length;
2287                 sk_msg_iter_var_next(i);
2288                 if (bytes_sg_total <= copy)
2289                         break;
2290         } while (i != msg->sg.end);
2291         last_sge = i;
2292
2293         if (unlikely(bytes_sg_total > copy))
2294                 return -EINVAL;
2295
2296         page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2297                            get_order(copy));
2298         if (unlikely(!page))
2299                 return -ENOMEM;
2300
2301         raw = page_address(page);
2302         i = first_sge;
2303         do {
2304                 sge = sk_msg_elem(msg, i);
2305                 from = sg_virt(sge);
2306                 len = sge->length;
2307                 to = raw + poffset;
2308
2309                 memcpy(to, from, len);
2310                 poffset += len;
2311                 sge->length = 0;
2312                 put_page(sg_page(sge));
2313
2314                 sk_msg_iter_var_next(i);
2315         } while (i != last_sge);
2316
2317         sg_set_page(&msg->sg.data[first_sge], page, copy, 0);
2318
2319         /* To repair sg ring we need to shift entries. If we only
2320          * had a single entry though we can just replace it and
2321          * be done. Otherwise walk the ring and shift the entries.
2322          */
2323         WARN_ON_ONCE(last_sge == first_sge);
2324         shift = last_sge > first_sge ?
2325                 last_sge - first_sge - 1 :
2326                 NR_MSG_FRAG_IDS - first_sge + last_sge - 1;
2327         if (!shift)
2328                 goto out;
2329
2330         i = first_sge;
2331         sk_msg_iter_var_next(i);
2332         do {
2333                 u32 move_from;
2334
2335                 if (i + shift >= NR_MSG_FRAG_IDS)
2336                         move_from = i + shift - NR_MSG_FRAG_IDS;
2337                 else
2338                         move_from = i + shift;
2339                 if (move_from == msg->sg.end)
2340                         break;
2341
2342                 msg->sg.data[i] = msg->sg.data[move_from];
2343                 msg->sg.data[move_from].length = 0;
2344                 msg->sg.data[move_from].page_link = 0;
2345                 msg->sg.data[move_from].offset = 0;
2346                 sk_msg_iter_var_next(i);
2347         } while (1);
2348
2349         msg->sg.end = msg->sg.end - shift > msg->sg.end ?
2350                       msg->sg.end - shift + NR_MSG_FRAG_IDS :
2351                       msg->sg.end - shift;
2352 out:
2353         msg->data = sg_virt(&msg->sg.data[first_sge]) + start - offset;
2354         msg->data_end = msg->data + bytes;
2355         return 0;
2356 }
2357
2358 static const struct bpf_func_proto bpf_msg_pull_data_proto = {
2359         .func           = bpf_msg_pull_data,
2360         .gpl_only       = false,
2361         .ret_type       = RET_INTEGER,
2362         .arg1_type      = ARG_PTR_TO_CTX,
2363         .arg2_type      = ARG_ANYTHING,
2364         .arg3_type      = ARG_ANYTHING,
2365         .arg4_type      = ARG_ANYTHING,
2366 };
2367
2368 BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start,
2369            u32, len, u64, flags)
2370 {
2371         struct scatterlist sge, nsge, nnsge, rsge = {0}, *psge;
2372         u32 new, i = 0, l = 0, space, copy = 0, offset = 0;
2373         u8 *raw, *to, *from;
2374         struct page *page;
2375
2376         if (unlikely(flags))
2377                 return -EINVAL;
2378
2379         /* First find the starting scatterlist element */
2380         i = msg->sg.start;
2381         do {
2382                 offset += l;
2383                 l = sk_msg_elem(msg, i)->length;
2384
2385                 if (start < offset + l)
2386                         break;
2387                 sk_msg_iter_var_next(i);
2388         } while (i != msg->sg.end);
2389
2390         if (start >= offset + l)
2391                 return -EINVAL;
2392
2393         space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2394
2395         /* If no space available will fallback to copy, we need at
2396          * least one scatterlist elem available to push data into
2397          * when start aligns to the beginning of an element or two
2398          * when it falls inside an element. We handle the start equals
2399          * offset case because its the common case for inserting a
2400          * header.
2401          */
2402         if (!space || (space == 1 && start != offset))
2403                 copy = msg->sg.data[i].length;
2404
2405         page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2406                            get_order(copy + len));
2407         if (unlikely(!page))
2408                 return -ENOMEM;
2409
2410         if (copy) {
2411                 int front, back;
2412
2413                 raw = page_address(page);
2414
2415                 psge = sk_msg_elem(msg, i);
2416                 front = start - offset;
2417                 back = psge->length - front;
2418                 from = sg_virt(psge);
2419
2420                 if (front)
2421                         memcpy(raw, from, front);
2422
2423                 if (back) {
2424                         from += front;
2425                         to = raw + front + len;
2426
2427                         memcpy(to, from, back);
2428                 }
2429
2430                 put_page(sg_page(psge));
2431         } else if (start - offset) {
2432                 psge = sk_msg_elem(msg, i);
2433                 rsge = sk_msg_elem_cpy(msg, i);
2434
2435                 psge->length = start - offset;
2436                 rsge.length -= psge->length;
2437                 rsge.offset += start;
2438
2439                 sk_msg_iter_var_next(i);
2440                 sg_unmark_end(psge);
2441                 sg_unmark_end(&rsge);
2442                 sk_msg_iter_next(msg, end);
2443         }
2444
2445         /* Slot(s) to place newly allocated data */
2446         new = i;
2447
2448         /* Shift one or two slots as needed */
2449         if (!copy) {
2450                 sge = sk_msg_elem_cpy(msg, i);
2451
2452                 sk_msg_iter_var_next(i);
2453                 sg_unmark_end(&sge);
2454                 sk_msg_iter_next(msg, end);
2455
2456                 nsge = sk_msg_elem_cpy(msg, i);
2457                 if (rsge.length) {
2458                         sk_msg_iter_var_next(i);
2459                         nnsge = sk_msg_elem_cpy(msg, i);
2460                 }
2461
2462                 while (i != msg->sg.end) {
2463                         msg->sg.data[i] = sge;
2464                         sge = nsge;
2465                         sk_msg_iter_var_next(i);
2466                         if (rsge.length) {
2467                                 nsge = nnsge;
2468                                 nnsge = sk_msg_elem_cpy(msg, i);
2469                         } else {
2470                                 nsge = sk_msg_elem_cpy(msg, i);
2471                         }
2472                 }
2473         }
2474
2475         /* Place newly allocated data buffer */
2476         sk_mem_charge(msg->sk, len);
2477         msg->sg.size += len;
2478         __clear_bit(new, &msg->sg.copy);
2479         sg_set_page(&msg->sg.data[new], page, len + copy, 0);
2480         if (rsge.length) {
2481                 get_page(sg_page(&rsge));
2482                 sk_msg_iter_var_next(new);
2483                 msg->sg.data[new] = rsge;
2484         }
2485
2486         sk_msg_compute_data_pointers(msg);
2487         return 0;
2488 }
2489
2490 static const struct bpf_func_proto bpf_msg_push_data_proto = {
2491         .func           = bpf_msg_push_data,
2492         .gpl_only       = false,
2493         .ret_type       = RET_INTEGER,
2494         .arg1_type      = ARG_PTR_TO_CTX,
2495         .arg2_type      = ARG_ANYTHING,
2496         .arg3_type      = ARG_ANYTHING,
2497         .arg4_type      = ARG_ANYTHING,
2498 };
2499
2500 static void sk_msg_shift_left(struct sk_msg *msg, int i)
2501 {
2502         int prev;
2503
2504         do {
2505                 prev = i;
2506                 sk_msg_iter_var_next(i);
2507                 msg->sg.data[prev] = msg->sg.data[i];
2508         } while (i != msg->sg.end);
2509
2510         sk_msg_iter_prev(msg, end);
2511 }
2512
2513 static void sk_msg_shift_right(struct sk_msg *msg, int i)
2514 {
2515         struct scatterlist tmp, sge;
2516
2517         sk_msg_iter_next(msg, end);
2518         sge = sk_msg_elem_cpy(msg, i);
2519         sk_msg_iter_var_next(i);
2520         tmp = sk_msg_elem_cpy(msg, i);
2521
2522         while (i != msg->sg.end) {
2523                 msg->sg.data[i] = sge;
2524                 sk_msg_iter_var_next(i);
2525                 sge = tmp;
2526                 tmp = sk_msg_elem_cpy(msg, i);
2527         }
2528 }
2529
2530 BPF_CALL_4(bpf_msg_pop_data, struct sk_msg *, msg, u32, start,
2531            u32, len, u64, flags)
2532 {
2533         u32 i = 0, l = 0, space, offset = 0;
2534         u64 last = start + len;
2535         int pop;
2536
2537         if (unlikely(flags))
2538                 return -EINVAL;
2539
2540         /* First find the starting scatterlist element */
2541         i = msg->sg.start;
2542         do {
2543                 offset += l;
2544                 l = sk_msg_elem(msg, i)->length;
2545
2546                 if (start < offset + l)
2547                         break;
2548                 sk_msg_iter_var_next(i);
2549         } while (i != msg->sg.end);
2550
2551         /* Bounds checks: start and pop must be inside message */
2552         if (start >= offset + l || last >= msg->sg.size)
2553                 return -EINVAL;
2554
2555         space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2556
2557         pop = len;
2558         /* --------------| offset
2559          * -| start      |-------- len -------|
2560          *
2561          *  |----- a ----|-------- pop -------|----- b ----|
2562          *  |______________________________________________| length
2563          *
2564          *
2565          * a:   region at front of scatter element to save
2566          * b:   region at back of scatter element to save when length > A + pop
2567          * pop: region to pop from element, same as input 'pop' here will be
2568          *      decremented below per iteration.
2569          *
2570          * Two top-level cases to handle when start != offset, first B is non
2571          * zero and second B is zero corresponding to when a pop includes more
2572          * than one element.
2573          *
2574          * Then if B is non-zero AND there is no space allocate space and
2575          * compact A, B regions into page. If there is space shift ring to
2576          * the rigth free'ing the next element in ring to place B, leaving
2577          * A untouched except to reduce length.
2578          */
2579         if (start != offset) {
2580                 struct scatterlist *nsge, *sge = sk_msg_elem(msg, i);
2581                 int a = start;
2582                 int b = sge->length - pop - a;
2583
2584                 sk_msg_iter_var_next(i);
2585
2586                 if (pop < sge->length - a) {
2587                         if (space) {
2588                                 sge->length = a;
2589                                 sk_msg_shift_right(msg, i);
2590                                 nsge = sk_msg_elem(msg, i);
2591                                 get_page(sg_page(sge));
2592                                 sg_set_page(nsge,
2593                                             sg_page(sge),
2594                                             b, sge->offset + pop + a);
2595                         } else {
2596                                 struct page *page, *orig;
2597                                 u8 *to, *from;
2598
2599                                 page = alloc_pages(__GFP_NOWARN |
2600                                                    __GFP_COMP   | GFP_ATOMIC,
2601                                                    get_order(a + b));
2602                                 if (unlikely(!page))
2603                                         return -ENOMEM;
2604
2605                                 sge->length = a;
2606                                 orig = sg_page(sge);
2607                                 from = sg_virt(sge);
2608                                 to = page_address(page);
2609                                 memcpy(to, from, a);
2610                                 memcpy(to + a, from + a + pop, b);
2611                                 sg_set_page(sge, page, a + b, 0);
2612                                 put_page(orig);
2613                         }
2614                         pop = 0;
2615                 } else if (pop >= sge->length - a) {
2616                         pop -= (sge->length - a);
2617                         sge->length = a;
2618                 }
2619         }
2620
2621         /* From above the current layout _must_ be as follows,
2622          *
2623          * -| offset
2624          * -| start
2625          *
2626          *  |---- pop ---|---------------- b ------------|
2627          *  |____________________________________________| length
2628          *
2629          * Offset and start of the current msg elem are equal because in the
2630          * previous case we handled offset != start and either consumed the
2631          * entire element and advanced to the next element OR pop == 0.
2632          *
2633          * Two cases to handle here are first pop is less than the length
2634          * leaving some remainder b above. Simply adjust the element's layout
2635          * in this case. Or pop >= length of the element so that b = 0. In this
2636          * case advance to next element decrementing pop.
2637          */
2638         while (pop) {
2639                 struct scatterlist *sge = sk_msg_elem(msg, i);
2640
2641                 if (pop < sge->length) {
2642                         sge->length -= pop;
2643                         sge->offset += pop;
2644                         pop = 0;
2645                 } else {
2646                         pop -= sge->length;
2647                         sk_msg_shift_left(msg, i);
2648                 }
2649                 sk_msg_iter_var_next(i);
2650         }
2651
2652         sk_mem_uncharge(msg->sk, len - pop);
2653         msg->sg.size -= (len - pop);
2654         sk_msg_compute_data_pointers(msg);
2655         return 0;
2656 }
2657
2658 static const struct bpf_func_proto bpf_msg_pop_data_proto = {
2659         .func           = bpf_msg_pop_data,
2660         .gpl_only       = false,
2661         .ret_type       = RET_INTEGER,
2662         .arg1_type      = ARG_PTR_TO_CTX,
2663         .arg2_type      = ARG_ANYTHING,
2664         .arg3_type      = ARG_ANYTHING,
2665         .arg4_type      = ARG_ANYTHING,
2666 };
2667
2668 #ifdef CONFIG_CGROUP_NET_CLASSID
2669 BPF_CALL_0(bpf_get_cgroup_classid_curr)
2670 {
2671         return __task_get_classid(current);
2672 }
2673
2674 static const struct bpf_func_proto bpf_get_cgroup_classid_curr_proto = {
2675         .func           = bpf_get_cgroup_classid_curr,
2676         .gpl_only       = false,
2677         .ret_type       = RET_INTEGER,
2678 };
2679 #endif
2680
2681 BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
2682 {
2683         return task_get_classid(skb);
2684 }
2685
2686 static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
2687         .func           = bpf_get_cgroup_classid,
2688         .gpl_only       = false,
2689         .ret_type       = RET_INTEGER,
2690         .arg1_type      = ARG_PTR_TO_CTX,
2691 };
2692
2693 BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
2694 {
2695         return dst_tclassid(skb);
2696 }
2697
2698 static const struct bpf_func_proto bpf_get_route_realm_proto = {
2699         .func           = bpf_get_route_realm,
2700         .gpl_only       = false,
2701         .ret_type       = RET_INTEGER,
2702         .arg1_type      = ARG_PTR_TO_CTX,
2703 };
2704
2705 BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
2706 {
2707         /* If skb_clear_hash() was called due to mangling, we can
2708          * trigger SW recalculation here. Later access to hash
2709          * can then use the inline skb->hash via context directly
2710          * instead of calling this helper again.
2711          */
2712         return skb_get_hash(skb);
2713 }
2714
2715 static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
2716         .func           = bpf_get_hash_recalc,
2717         .gpl_only       = false,
2718         .ret_type       = RET_INTEGER,
2719         .arg1_type      = ARG_PTR_TO_CTX,
2720 };
2721
2722 BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
2723 {
2724         /* After all direct packet write, this can be used once for
2725          * triggering a lazy recalc on next skb_get_hash() invocation.
2726          */
2727         skb_clear_hash(skb);
2728         return 0;
2729 }
2730
2731 static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
2732         .func           = bpf_set_hash_invalid,
2733         .gpl_only       = false,
2734         .ret_type       = RET_INTEGER,
2735         .arg1_type      = ARG_PTR_TO_CTX,
2736 };
2737
2738 BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
2739 {
2740         /* Set user specified hash as L4(+), so that it gets returned
2741          * on skb_get_hash() call unless BPF prog later on triggers a
2742          * skb_clear_hash().
2743          */
2744         __skb_set_sw_hash(skb, hash, true);
2745         return 0;
2746 }
2747
2748 static const struct bpf_func_proto bpf_set_hash_proto = {
2749         .func           = bpf_set_hash,
2750         .gpl_only       = false,
2751         .ret_type       = RET_INTEGER,
2752         .arg1_type      = ARG_PTR_TO_CTX,
2753         .arg2_type      = ARG_ANYTHING,
2754 };
2755
2756 BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
2757            u16, vlan_tci)
2758 {
2759         int ret;
2760
2761         if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
2762                      vlan_proto != htons(ETH_P_8021AD)))
2763                 vlan_proto = htons(ETH_P_8021Q);
2764
2765         bpf_push_mac_rcsum(skb);
2766         ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
2767         bpf_pull_mac_rcsum(skb);
2768
2769         bpf_compute_data_pointers(skb);
2770         return ret;
2771 }
2772
2773 static const struct bpf_func_proto bpf_skb_vlan_push_proto = {
2774         .func           = bpf_skb_vlan_push,
2775         .gpl_only       = false,
2776         .ret_type       = RET_INTEGER,
2777         .arg1_type      = ARG_PTR_TO_CTX,
2778         .arg2_type      = ARG_ANYTHING,
2779         .arg3_type      = ARG_ANYTHING,
2780 };
2781
2782 BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
2783 {
2784         int ret;
2785
2786         bpf_push_mac_rcsum(skb);
2787         ret = skb_vlan_pop(skb);
2788         bpf_pull_mac_rcsum(skb);
2789
2790         bpf_compute_data_pointers(skb);
2791         return ret;
2792 }
2793
2794 static const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
2795         .func           = bpf_skb_vlan_pop,
2796         .gpl_only       = false,
2797         .ret_type       = RET_INTEGER,
2798         .arg1_type      = ARG_PTR_TO_CTX,
2799 };
2800
2801 static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
2802 {
2803         /* Caller already did skb_cow() with len as headroom,
2804          * so no need to do it here.
2805          */
2806         skb_push(skb, len);
2807         memmove(skb->data, skb->data + len, off);
2808         memset(skb->data + off, 0, len);
2809
2810         /* No skb_postpush_rcsum(skb, skb->data + off, len)
2811          * needed here as it does not change the skb->csum
2812          * result for checksum complete when summing over
2813          * zeroed blocks.
2814          */
2815         return 0;
2816 }
2817
2818 static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
2819 {
2820         /* skb_ensure_writable() is not needed here, as we're
2821          * already working on an uncloned skb.
2822          */
2823         if (unlikely(!pskb_may_pull(skb, off + len)))
2824                 return -ENOMEM;
2825
2826         skb_postpull_rcsum(skb, skb->data + off, len);
2827         memmove(skb->data + len, skb->data, off);
2828         __skb_pull(skb, len);
2829
2830         return 0;
2831 }
2832
2833 static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
2834 {
2835         bool trans_same = skb->transport_header == skb->network_header;
2836         int ret;
2837
2838         /* There's no need for __skb_push()/__skb_pull() pair to
2839          * get to the start of the mac header as we're guaranteed
2840          * to always start from here under eBPF.
2841          */
2842         ret = bpf_skb_generic_push(skb, off, len);
2843         if (likely(!ret)) {
2844                 skb->mac_header -= len;
2845                 skb->network_header -= len;
2846                 if (trans_same)
2847                         skb->transport_header = skb->network_header;
2848         }
2849
2850         return ret;
2851 }
2852
2853 static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
2854 {
2855         bool trans_same = skb->transport_header == skb->network_header;
2856         int ret;
2857
2858         /* Same here, __skb_push()/__skb_pull() pair not needed. */
2859         ret = bpf_skb_generic_pop(skb, off, len);
2860         if (likely(!ret)) {
2861                 skb->mac_header += len;
2862                 skb->network_header += len;
2863                 if (trans_same)
2864                         skb->transport_header = skb->network_header;
2865         }
2866
2867         return ret;
2868 }
2869
2870 static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
2871 {
2872         const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2873         u32 off = skb_mac_header_len(skb);
2874         int ret;
2875
2876         if (skb_is_gso(skb) && !skb_is_gso_tcp(skb))
2877                 return -ENOTSUPP;
2878
2879         ret = skb_cow(skb, len_diff);
2880         if (unlikely(ret < 0))
2881                 return ret;
2882
2883         ret = bpf_skb_net_hdr_push(skb, off, len_diff);
2884         if (unlikely(ret < 0))
2885                 return ret;
2886
2887         if (skb_is_gso(skb)) {
2888                 struct skb_shared_info *shinfo = skb_shinfo(skb);
2889
2890                 /* SKB_GSO_TCPV4 needs to be changed into
2891                  * SKB_GSO_TCPV6.
2892                  */
2893                 if (shinfo->gso_type & SKB_GSO_TCPV4) {
2894                         shinfo->gso_type &= ~SKB_GSO_TCPV4;
2895                         shinfo->gso_type |=  SKB_GSO_TCPV6;
2896                 }
2897
2898                 /* Due to IPv6 header, MSS needs to be downgraded. */
2899                 skb_decrease_gso_size(shinfo, len_diff);
2900                 /* Header must be checked, and gso_segs recomputed. */
2901                 shinfo->gso_type |= SKB_GSO_DODGY;
2902                 shinfo->gso_segs = 0;
2903         }
2904
2905         skb->protocol = htons(ETH_P_IPV6);
2906         skb_clear_hash(skb);
2907
2908         return 0;
2909 }
2910
2911 static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
2912 {
2913         const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2914         u32 off = skb_mac_header_len(skb);
2915         int ret;
2916
2917         if (skb_is_gso(skb) && !skb_is_gso_tcp(skb))
2918                 return -ENOTSUPP;
2919
2920         ret = skb_unclone(skb, GFP_ATOMIC);
2921         if (unlikely(ret < 0))
2922                 return ret;
2923
2924         ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
2925         if (unlikely(ret < 0))
2926                 return ret;
2927
2928         if (skb_is_gso(skb)) {
2929                 struct skb_shared_info *shinfo = skb_shinfo(skb);
2930
2931                 /* SKB_GSO_TCPV6 needs to be changed into
2932                  * SKB_GSO_TCPV4.
2933                  */
2934                 if (shinfo->gso_type & SKB_GSO_TCPV6) {
2935                         shinfo->gso_type &= ~SKB_GSO_TCPV6;
2936                         shinfo->gso_type |=  SKB_GSO_TCPV4;
2937                 }
2938
2939                 /* Due to IPv4 header, MSS can be upgraded. */
2940                 skb_increase_gso_size(shinfo, len_diff);
2941                 /* Header must be checked, and gso_segs recomputed. */
2942                 shinfo->gso_type |= SKB_GSO_DODGY;
2943                 shinfo->gso_segs = 0;
2944         }
2945
2946         skb->protocol = htons(ETH_P_IP);
2947         skb_clear_hash(skb);
2948
2949         return 0;
2950 }
2951
2952 static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
2953 {
2954         __be16 from_proto = skb->protocol;
2955
2956         if (from_proto == htons(ETH_P_IP) &&
2957               to_proto == htons(ETH_P_IPV6))
2958                 return bpf_skb_proto_4_to_6(skb);
2959
2960         if (from_proto == htons(ETH_P_IPV6) &&
2961               to_proto == htons(ETH_P_IP))
2962                 return bpf_skb_proto_6_to_4(skb);
2963
2964         return -ENOTSUPP;
2965 }
2966
2967 BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
2968            u64, flags)
2969 {
2970         int ret;
2971
2972         if (unlikely(flags))
2973                 return -EINVAL;
2974
2975         /* General idea is that this helper does the basic groundwork
2976          * needed for changing the protocol, and eBPF program fills the
2977          * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
2978          * and other helpers, rather than passing a raw buffer here.
2979          *
2980          * The rationale is to keep this minimal and without a need to
2981          * deal with raw packet data. F.e. even if we would pass buffers
2982          * here, the program still needs to call the bpf_lX_csum_replace()
2983          * helpers anyway. Plus, this way we keep also separation of
2984          * concerns, since f.e. bpf_skb_store_bytes() should only take
2985          * care of stores.
2986          *
2987          * Currently, additional options and extension header space are
2988          * not supported, but flags register is reserved so we can adapt
2989          * that. For offloads, we mark packet as dodgy, so that headers
2990          * need to be verified first.
2991          */
2992         ret = bpf_skb_proto_xlat(skb, proto);
2993         bpf_compute_data_pointers(skb);
2994         return ret;
2995 }
2996
2997 static const struct bpf_func_proto bpf_skb_change_proto_proto = {
2998         .func           = bpf_skb_change_proto,
2999         .gpl_only       = false,
3000         .ret_type       = RET_INTEGER,
3001         .arg1_type      = ARG_PTR_TO_CTX,
3002         .arg2_type      = ARG_ANYTHING,
3003         .arg3_type      = ARG_ANYTHING,
3004 };
3005
3006 BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
3007 {
3008         /* We only allow a restricted subset to be changed for now. */
3009         if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
3010                      !skb_pkt_type_ok(pkt_type)))
3011                 return -EINVAL;
3012
3013         skb->pkt_type = pkt_type;
3014         return 0;
3015 }
3016
3017 static const struct bpf_func_proto bpf_skb_change_type_proto = {
3018         .func           = bpf_skb_change_type,
3019         .gpl_only       = false,
3020         .ret_type       = RET_INTEGER,
3021         .arg1_type      = ARG_PTR_TO_CTX,
3022         .arg2_type      = ARG_ANYTHING,
3023 };
3024
3025 static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
3026 {
3027         switch (skb->protocol) {
3028         case htons(ETH_P_IP):
3029                 return sizeof(struct iphdr);
3030         case htons(ETH_P_IPV6):
3031                 return sizeof(struct ipv6hdr);
3032         default:
3033                 return ~0U;
3034         }
3035 }
3036
3037 #define BPF_F_ADJ_ROOM_ENCAP_L3_MASK    (BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 | \
3038                                          BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3039
3040 #define BPF_F_ADJ_ROOM_MASK             (BPF_F_ADJ_ROOM_FIXED_GSO | \
3041                                          BPF_F_ADJ_ROOM_ENCAP_L3_MASK | \
3042                                          BPF_F_ADJ_ROOM_ENCAP_L4_GRE | \
3043                                          BPF_F_ADJ_ROOM_ENCAP_L4_UDP | \
3044                                          BPF_F_ADJ_ROOM_ENCAP_L2( \
3045                                           BPF_ADJ_ROOM_ENCAP_L2_MASK))
3046
3047 static int bpf_skb_net_grow(struct sk_buff *skb, u32 off, u32 len_diff,
3048                             u64 flags)
3049 {
3050         u8 inner_mac_len = flags >> BPF_ADJ_ROOM_ENCAP_L2_SHIFT;
3051         bool encap = flags & BPF_F_ADJ_ROOM_ENCAP_L3_MASK;
3052         u16 mac_len = 0, inner_net = 0, inner_trans = 0;
3053         unsigned int gso_type = SKB_GSO_DODGY;
3054         int ret;
3055
3056         if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3057                 /* udp gso_size delineates datagrams, only allow if fixed */
3058                 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3059                     !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3060                         return -ENOTSUPP;
3061         }
3062
3063         ret = skb_cow_head(skb, len_diff);
3064         if (unlikely(ret < 0))
3065                 return ret;
3066
3067         if (encap) {
3068                 if (skb->protocol != htons(ETH_P_IP) &&
3069                     skb->protocol != htons(ETH_P_IPV6))
3070                         return -ENOTSUPP;
3071
3072                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 &&
3073                     flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3074                         return -EINVAL;
3075
3076                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE &&
3077                     flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3078                         return -EINVAL;
3079
3080                 if (skb->encapsulation)
3081                         return -EALREADY;
3082
3083                 mac_len = skb->network_header - skb->mac_header;
3084                 inner_net = skb->network_header;
3085                 if (inner_mac_len > len_diff)
3086                         return -EINVAL;
3087                 inner_trans = skb->transport_header;
3088         }
3089
3090         ret = bpf_skb_net_hdr_push(skb, off, len_diff);
3091         if (unlikely(ret < 0))
3092                 return ret;
3093
3094         if (encap) {
3095                 skb->inner_mac_header = inner_net - inner_mac_len;
3096                 skb->inner_network_header = inner_net;
3097                 skb->inner_transport_header = inner_trans;
3098                 skb_set_inner_protocol(skb, skb->protocol);
3099
3100                 skb->encapsulation = 1;
3101                 skb_set_network_header(skb, mac_len);
3102
3103                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3104                         gso_type |= SKB_GSO_UDP_TUNNEL;
3105                 else if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE)
3106                         gso_type |= SKB_GSO_GRE;
3107                 else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3108                         gso_type |= SKB_GSO_IPXIP6;
3109                 else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3110                         gso_type |= SKB_GSO_IPXIP4;
3111
3112                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE ||
3113                     flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP) {
3114                         int nh_len = flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 ?
3115                                         sizeof(struct ipv6hdr) :
3116                                         sizeof(struct iphdr);
3117
3118                         skb_set_transport_header(skb, mac_len + nh_len);
3119                 }
3120
3121                 /* Match skb->protocol to new outer l3 protocol */
3122                 if (skb->protocol == htons(ETH_P_IP) &&
3123                     flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3124                         skb->protocol = htons(ETH_P_IPV6);
3125                 else if (skb->protocol == htons(ETH_P_IPV6) &&
3126                          flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3127                         skb->protocol = htons(ETH_P_IP);
3128         }
3129
3130         if (skb_is_gso(skb)) {
3131                 struct skb_shared_info *shinfo = skb_shinfo(skb);
3132
3133                 /* Due to header grow, MSS needs to be downgraded. */
3134                 if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3135                         skb_decrease_gso_size(shinfo, len_diff);
3136
3137                 /* Header must be checked, and gso_segs recomputed. */
3138                 shinfo->gso_type |= gso_type;
3139                 shinfo->gso_segs = 0;
3140         }
3141
3142         return 0;
3143 }
3144
3145 static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff,
3146                               u64 flags)
3147 {
3148         int ret;
3149
3150         if (unlikely(flags & ~(BPF_F_ADJ_ROOM_FIXED_GSO |
3151                                BPF_F_ADJ_ROOM_NO_CSUM_RESET)))
3152                 return -EINVAL;
3153
3154         if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3155                 /* udp gso_size delineates datagrams, only allow if fixed */
3156                 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3157                     !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3158                         return -ENOTSUPP;
3159         }
3160
3161         ret = skb_unclone(skb, GFP_ATOMIC);
3162         if (unlikely(ret < 0))
3163                 return ret;
3164
3165         ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
3166         if (unlikely(ret < 0))
3167                 return ret;
3168
3169         if (skb_is_gso(skb)) {
3170                 struct skb_shared_info *shinfo = skb_shinfo(skb);
3171
3172                 /* Due to header shrink, MSS can be upgraded. */
3173                 if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3174                         skb_increase_gso_size(shinfo, len_diff);
3175
3176                 /* Header must be checked, and gso_segs recomputed. */
3177                 shinfo->gso_type |= SKB_GSO_DODGY;
3178                 shinfo->gso_segs = 0;
3179         }
3180
3181         return 0;
3182 }
3183
3184 static u32 __bpf_skb_max_len(const struct sk_buff *skb)
3185 {
3186         return skb->dev ? skb->dev->mtu + skb->dev->hard_header_len :
3187                           SKB_MAX_ALLOC;
3188 }
3189
3190 BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
3191            u32, mode, u64, flags)
3192 {
3193         u32 len_cur, len_diff_abs = abs(len_diff);
3194         u32 len_min = bpf_skb_net_base_len(skb);
3195         u32 len_max = __bpf_skb_max_len(skb);
3196         __be16 proto = skb->protocol;
3197         bool shrink = len_diff < 0;
3198         u32 off;
3199         int ret;
3200
3201         if (unlikely(flags & ~(BPF_F_ADJ_ROOM_MASK |
3202                                BPF_F_ADJ_ROOM_NO_CSUM_RESET)))
3203                 return -EINVAL;
3204         if (unlikely(len_diff_abs > 0xfffU))
3205                 return -EFAULT;
3206         if (unlikely(proto != htons(ETH_P_IP) &&
3207                      proto != htons(ETH_P_IPV6)))
3208                 return -ENOTSUPP;
3209
3210         off = skb_mac_header_len(skb);
3211         switch (mode) {
3212         case BPF_ADJ_ROOM_NET:
3213                 off += bpf_skb_net_base_len(skb);
3214                 break;
3215         case BPF_ADJ_ROOM_MAC:
3216                 break;
3217         default:
3218                 return -ENOTSUPP;
3219         }
3220
3221         len_cur = skb->len - skb_network_offset(skb);
3222         if ((shrink && (len_diff_abs >= len_cur ||
3223                         len_cur - len_diff_abs < len_min)) ||
3224             (!shrink && (skb->len + len_diff_abs > len_max &&
3225                          !skb_is_gso(skb))))
3226                 return -ENOTSUPP;
3227
3228         ret = shrink ? bpf_skb_net_shrink(skb, off, len_diff_abs, flags) :
3229                        bpf_skb_net_grow(skb, off, len_diff_abs, flags);
3230         if (!ret && !(flags & BPF_F_ADJ_ROOM_NO_CSUM_RESET))
3231                 __skb_reset_checksum_unnecessary(skb);
3232
3233         bpf_compute_data_pointers(skb);
3234         return ret;
3235 }
3236
3237 static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
3238         .func           = bpf_skb_adjust_room,
3239         .gpl_only       = false,
3240         .ret_type       = RET_INTEGER,
3241         .arg1_type      = ARG_PTR_TO_CTX,
3242         .arg2_type      = ARG_ANYTHING,
3243         .arg3_type      = ARG_ANYTHING,
3244         .arg4_type      = ARG_ANYTHING,
3245 };
3246
3247 static u32 __bpf_skb_min_len(const struct sk_buff *skb)
3248 {
3249         u32 min_len = skb_network_offset(skb);
3250
3251         if (skb_transport_header_was_set(skb))
3252                 min_len = skb_transport_offset(skb);
3253         if (skb->ip_summed == CHECKSUM_PARTIAL)
3254                 min_len = skb_checksum_start_offset(skb) +
3255                           skb->csum_offset + sizeof(__sum16);
3256         return min_len;
3257 }
3258
3259 static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
3260 {
3261         unsigned int old_len = skb->len;
3262         int ret;
3263
3264         ret = __skb_grow_rcsum(skb, new_len);
3265         if (!ret)
3266                 memset(skb->data + old_len, 0, new_len - old_len);
3267         return ret;
3268 }
3269
3270 static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
3271 {
3272         return __skb_trim_rcsum(skb, new_len);
3273 }
3274
3275 static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len,
3276                                         u64 flags)
3277 {
3278         u32 max_len = __bpf_skb_max_len(skb);
3279         u32 min_len = __bpf_skb_min_len(skb);
3280         int ret;
3281
3282         if (unlikely(flags || new_len > max_len || new_len < min_len))
3283                 return -EINVAL;
3284         if (skb->encapsulation)
3285                 return -ENOTSUPP;
3286
3287         /* The basic idea of this helper is that it's performing the
3288          * needed work to either grow or trim an skb, and eBPF program
3289          * rewrites the rest via helpers like bpf_skb_store_bytes(),
3290          * bpf_lX_csum_replace() and others rather than passing a raw
3291          * buffer here. This one is a slow path helper and intended
3292          * for replies with control messages.
3293          *
3294          * Like in bpf_skb_change_proto(), we want to keep this rather
3295          * minimal and without protocol specifics so that we are able
3296          * to separate concerns as in bpf_skb_store_bytes() should only
3297          * be the one responsible for writing buffers.
3298          *
3299          * It's really expected to be a slow path operation here for
3300          * control message replies, so we're implicitly linearizing,
3301          * uncloning and drop offloads from the skb by this.
3302          */
3303         ret = __bpf_try_make_writable(skb, skb->len);
3304         if (!ret) {
3305                 if (new_len > skb->len)
3306                         ret = bpf_skb_grow_rcsum(skb, new_len);
3307                 else if (new_len < skb->len)
3308                         ret = bpf_skb_trim_rcsum(skb, new_len);
3309                 if (!ret && skb_is_gso(skb))
3310                         skb_gso_reset(skb);
3311         }
3312         return ret;
3313 }
3314
3315 BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3316            u64, flags)
3317 {
3318         int ret = __bpf_skb_change_tail(skb, new_len, flags);
3319
3320         bpf_compute_data_pointers(skb);
3321         return ret;
3322 }
3323
3324 static const struct bpf_func_proto bpf_skb_change_tail_proto = {
3325         .func           = bpf_skb_change_tail,
3326         .gpl_only       = false,
3327         .ret_type       = RET_INTEGER,
3328         .arg1_type      = ARG_PTR_TO_CTX,
3329         .arg2_type      = ARG_ANYTHING,
3330         .arg3_type      = ARG_ANYTHING,
3331 };
3332
3333 BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3334            u64, flags)
3335 {
3336         int ret = __bpf_skb_change_tail(skb, new_len, flags);
3337
3338         bpf_compute_data_end_sk_skb(skb);
3339         return ret;
3340 }
3341
3342 static const struct bpf_func_proto sk_skb_change_tail_proto = {
3343         .func           = sk_skb_change_tail,
3344         .gpl_only       = false,
3345         .ret_type       = RET_INTEGER,
3346         .arg1_type      = ARG_PTR_TO_CTX,
3347         .arg2_type      = ARG_ANYTHING,
3348         .arg3_type      = ARG_ANYTHING,
3349 };
3350
3351 static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room,
3352                                         u64 flags)
3353 {
3354         u32 max_len = __bpf_skb_max_len(skb);
3355         u32 new_len = skb->len + head_room;
3356         int ret;
3357
3358         if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
3359                      new_len < skb->len))
3360                 return -EINVAL;
3361
3362         ret = skb_cow(skb, head_room);
3363         if (likely(!ret)) {
3364                 /* Idea for this helper is that we currently only
3365                  * allow to expand on mac header. This means that
3366                  * skb->protocol network header, etc, stay as is.
3367                  * Compared to bpf_skb_change_tail(), we're more
3368                  * flexible due to not needing to linearize or
3369                  * reset GSO. Intention for this helper is to be
3370                  * used by an L3 skb that needs to push mac header
3371                  * for redirection into L2 device.
3372                  */
3373                 __skb_push(skb, head_room);
3374                 memset(skb->data, 0, head_room);
3375                 skb_reset_mac_header(skb);
3376         }
3377
3378         return ret;
3379 }
3380
3381 BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
3382            u64, flags)
3383 {
3384         int ret = __bpf_skb_change_head(skb, head_room, flags);
3385
3386         bpf_compute_data_pointers(skb);
3387         return ret;
3388 }
3389
3390 static const struct bpf_func_proto bpf_skb_change_head_proto = {
3391         .func           = bpf_skb_change_head,
3392         .gpl_only       = false,
3393         .ret_type       = RET_INTEGER,
3394         .arg1_type      = ARG_PTR_TO_CTX,
3395         .arg2_type      = ARG_ANYTHING,
3396         .arg3_type      = ARG_ANYTHING,
3397 };
3398
3399 BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room,
3400            u64, flags)
3401 {
3402         int ret = __bpf_skb_change_head(skb, head_room, flags);
3403
3404         bpf_compute_data_end_sk_skb(skb);
3405         return ret;
3406 }
3407
3408 static const struct bpf_func_proto sk_skb_change_head_proto = {
3409         .func           = sk_skb_change_head,
3410         .gpl_only       = false,
3411         .ret_type       = RET_INTEGER,
3412         .arg1_type      = ARG_PTR_TO_CTX,
3413         .arg2_type      = ARG_ANYTHING,
3414         .arg3_type      = ARG_ANYTHING,
3415 };
3416 static unsigned long xdp_get_metalen(const struct xdp_buff *xdp)
3417 {
3418         return xdp_data_meta_unsupported(xdp) ? 0 :
3419                xdp->data - xdp->data_meta;
3420 }
3421
3422 BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
3423 {
3424         void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3425         unsigned long metalen = xdp_get_metalen(xdp);
3426         void *data_start = xdp_frame_end + metalen;
3427         void *data = xdp->data + offset;
3428
3429         if (unlikely(data < data_start ||
3430                      data > xdp->data_end - ETH_HLEN))
3431                 return -EINVAL;
3432
3433         if (metalen)
3434                 memmove(xdp->data_meta + offset,
3435                         xdp->data_meta, metalen);
3436         xdp->data_meta += offset;
3437         xdp->data = data;
3438
3439         return 0;
3440 }
3441
3442 static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
3443         .func           = bpf_xdp_adjust_head,
3444         .gpl_only       = false,
3445         .ret_type       = RET_INTEGER,
3446         .arg1_type      = ARG_PTR_TO_CTX,
3447         .arg2_type      = ARG_ANYTHING,
3448 };
3449
3450 BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
3451 {
3452         void *data_hard_end = xdp_data_hard_end(xdp); /* use xdp->frame_sz */
3453         void *data_end = xdp->data_end + offset;
3454
3455         /* Notice that xdp_data_hard_end have reserved some tailroom */
3456         if (unlikely(data_end > data_hard_end))
3457                 return -EINVAL;
3458
3459         /* ALL drivers MUST init xdp->frame_sz, chicken check below */
3460         if (unlikely(xdp->frame_sz > PAGE_SIZE)) {
3461                 WARN_ONCE(1, "Too BIG xdp->frame_sz = %d\n", xdp->frame_sz);
3462                 return -EINVAL;
3463         }
3464
3465         if (unlikely(data_end < xdp->data + ETH_HLEN))
3466                 return -EINVAL;
3467
3468         /* Clear memory area on grow, can contain uninit kernel memory */
3469         if (offset > 0)
3470                 memset(xdp->data_end, 0, offset);
3471
3472         xdp->data_end = data_end;
3473
3474         return 0;
3475 }
3476
3477 static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
3478         .func           = bpf_xdp_adjust_tail,
3479         .gpl_only       = false,
3480         .ret_type       = RET_INTEGER,
3481         .arg1_type      = ARG_PTR_TO_CTX,
3482         .arg2_type      = ARG_ANYTHING,
3483 };
3484
3485 BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
3486 {
3487         void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3488         void *meta = xdp->data_meta + offset;
3489         unsigned long metalen = xdp->data - meta;
3490
3491         if (xdp_data_meta_unsupported(xdp))
3492                 return -ENOTSUPP;
3493         if (unlikely(meta < xdp_frame_end ||
3494                      meta > xdp->data))
3495                 return -EINVAL;
3496         if (unlikely((metalen & (sizeof(__u32) - 1)) ||
3497                      (metalen > 32)))
3498                 return -EACCES;
3499
3500         xdp->data_meta = meta;
3501
3502         return 0;
3503 }
3504
3505 static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
3506         .func           = bpf_xdp_adjust_meta,
3507         .gpl_only       = false,
3508         .ret_type       = RET_INTEGER,
3509         .arg1_type      = ARG_PTR_TO_CTX,
3510         .arg2_type      = ARG_ANYTHING,
3511 };
3512
3513 static int __bpf_tx_xdp_map(struct net_device *dev_rx, void *fwd,
3514                             struct bpf_map *map, struct xdp_buff *xdp)
3515 {
3516         switch (map->map_type) {
3517         case BPF_MAP_TYPE_DEVMAP:
3518         case BPF_MAP_TYPE_DEVMAP_HASH:
3519                 return dev_map_enqueue(fwd, xdp, dev_rx);
3520         case BPF_MAP_TYPE_CPUMAP:
3521                 return cpu_map_enqueue(fwd, xdp, dev_rx);
3522         case BPF_MAP_TYPE_XSKMAP:
3523                 return __xsk_map_redirect(fwd, xdp);
3524         default:
3525                 return -EBADRQC;
3526         }
3527         return 0;
3528 }
3529
3530 void xdp_do_flush(void)
3531 {
3532         __dev_flush();
3533         __cpu_map_flush();
3534         __xsk_map_flush();
3535 }
3536 EXPORT_SYMBOL_GPL(xdp_do_flush);
3537
3538 static inline void *__xdp_map_lookup_elem(struct bpf_map *map, u32 index)
3539 {
3540         switch (map->map_type) {
3541         case BPF_MAP_TYPE_DEVMAP:
3542                 return __dev_map_lookup_elem(map, index);
3543         case BPF_MAP_TYPE_DEVMAP_HASH:
3544                 return __dev_map_hash_lookup_elem(map, index);
3545         case BPF_MAP_TYPE_CPUMAP:
3546                 return __cpu_map_lookup_elem(map, index);
3547         case BPF_MAP_TYPE_XSKMAP:
3548                 return __xsk_map_lookup_elem(map, index);
3549         default:
3550                 return NULL;
3551         }
3552 }
3553
3554 void bpf_clear_redirect_map(struct bpf_map *map)
3555 {
3556         struct bpf_redirect_info *ri;
3557         int cpu;
3558
3559         for_each_possible_cpu(cpu) {
3560                 ri = per_cpu_ptr(&bpf_redirect_info, cpu);
3561                 /* Avoid polluting remote cacheline due to writes if
3562                  * not needed. Once we pass this test, we need the
3563                  * cmpxchg() to make sure it hasn't been changed in
3564                  * the meantime by remote CPU.
3565                  */
3566                 if (unlikely(READ_ONCE(ri->map) == map))
3567                         cmpxchg(&ri->map, map, NULL);
3568         }
3569 }
3570
3571 int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
3572                     struct bpf_prog *xdp_prog)
3573 {
3574         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3575         struct bpf_map *map = READ_ONCE(ri->map);
3576         u32 index = ri->tgt_index;
3577         void *fwd = ri->tgt_value;
3578         int err;
3579
3580         ri->tgt_index = 0;
3581         ri->tgt_value = NULL;
3582         WRITE_ONCE(ri->map, NULL);
3583
3584         if (unlikely(!map)) {
3585                 fwd = dev_get_by_index_rcu(dev_net(dev), index);
3586                 if (unlikely(!fwd)) {
3587                         err = -EINVAL;
3588                         goto err;
3589                 }
3590
3591                 err = dev_xdp_enqueue(fwd, xdp, dev);
3592         } else {
3593                 err = __bpf_tx_xdp_map(dev, fwd, map, xdp);
3594         }
3595
3596         if (unlikely(err))
3597                 goto err;
3598
3599         _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3600         return 0;
3601 err:
3602         _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3603         return err;
3604 }
3605 EXPORT_SYMBOL_GPL(xdp_do_redirect);
3606
3607 static int xdp_do_generic_redirect_map(struct net_device *dev,
3608                                        struct sk_buff *skb,
3609                                        struct xdp_buff *xdp,
3610                                        struct bpf_prog *xdp_prog,
3611                                        struct bpf_map *map)
3612 {
3613         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3614         u32 index = ri->tgt_index;
3615         void *fwd = ri->tgt_value;
3616         int err = 0;
3617
3618         ri->tgt_index = 0;
3619         ri->tgt_value = NULL;
3620         WRITE_ONCE(ri->map, NULL);
3621
3622         if (map->map_type == BPF_MAP_TYPE_DEVMAP ||
3623             map->map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
3624                 struct bpf_dtab_netdev *dst = fwd;
3625
3626                 err = dev_map_generic_redirect(dst, skb, xdp_prog);
3627                 if (unlikely(err))
3628                         goto err;
3629         } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
3630                 struct xdp_sock *xs = fwd;
3631
3632                 err = xsk_generic_rcv(xs, xdp);
3633                 if (err)
3634                         goto err;
3635                 consume_skb(skb);
3636         } else {
3637                 /* TODO: Handle BPF_MAP_TYPE_CPUMAP */
3638                 err = -EBADRQC;
3639                 goto err;
3640         }
3641
3642         _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3643         return 0;
3644 err:
3645         _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3646         return err;
3647 }
3648
3649 int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
3650                             struct xdp_buff *xdp, struct bpf_prog *xdp_prog)
3651 {
3652         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3653         struct bpf_map *map = READ_ONCE(ri->map);
3654         u32 index = ri->tgt_index;
3655         struct net_device *fwd;
3656         int err = 0;
3657
3658         if (map)
3659                 return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog,
3660                                                    map);
3661         ri->tgt_index = 0;
3662         fwd = dev_get_by_index_rcu(dev_net(dev), index);
3663         if (unlikely(!fwd)) {
3664                 err = -EINVAL;
3665                 goto err;
3666         }
3667
3668         err = xdp_ok_fwd_dev(fwd, skb->len);
3669         if (unlikely(err))
3670                 goto err;
3671
3672         skb->dev = fwd;
3673         _trace_xdp_redirect(dev, xdp_prog, index);
3674         generic_xdp_tx(skb, xdp_prog);
3675         return 0;
3676 err:
3677         _trace_xdp_redirect_err(dev, xdp_prog, index, err);
3678         return err;
3679 }
3680
3681 BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
3682 {
3683         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3684
3685         if (unlikely(flags))
3686                 return XDP_ABORTED;
3687
3688         ri->flags = flags;
3689         ri->tgt_index = ifindex;
3690         ri->tgt_value = NULL;
3691         WRITE_ONCE(ri->map, NULL);
3692
3693         return XDP_REDIRECT;
3694 }
3695
3696 static const struct bpf_func_proto bpf_xdp_redirect_proto = {
3697         .func           = bpf_xdp_redirect,
3698         .gpl_only       = false,
3699         .ret_type       = RET_INTEGER,
3700         .arg1_type      = ARG_ANYTHING,
3701         .arg2_type      = ARG_ANYTHING,
3702 };
3703
3704 BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u32, ifindex,
3705            u64, flags)
3706 {
3707         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3708
3709         /* Lower bits of the flags are used as return code on lookup failure */
3710         if (unlikely(flags > XDP_TX))
3711                 return XDP_ABORTED;
3712
3713         ri->tgt_value = __xdp_map_lookup_elem(map, ifindex);
3714         if (unlikely(!ri->tgt_value)) {
3715                 /* If the lookup fails we want to clear out the state in the
3716                  * redirect_info struct completely, so that if an eBPF program
3717                  * performs multiple lookups, the last one always takes
3718                  * precedence.
3719                  */
3720                 WRITE_ONCE(ri->map, NULL);
3721                 return flags;
3722         }
3723
3724         ri->flags = flags;
3725         ri->tgt_index = ifindex;
3726         WRITE_ONCE(ri->map, map);
3727
3728         return XDP_REDIRECT;
3729 }
3730
3731 static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
3732         .func           = bpf_xdp_redirect_map,
3733         .gpl_only       = false,
3734         .ret_type       = RET_INTEGER,
3735         .arg1_type      = ARG_CONST_MAP_PTR,
3736         .arg2_type      = ARG_ANYTHING,
3737         .arg3_type      = ARG_ANYTHING,
3738 };
3739
3740 static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
3741                                   unsigned long off, unsigned long len)
3742 {
3743         void *ptr = skb_header_pointer(skb, off, len, dst_buff);
3744
3745         if (unlikely(!ptr))
3746                 return len;
3747         if (ptr != dst_buff)
3748                 memcpy(dst_buff, ptr, len);
3749
3750         return 0;
3751 }
3752
3753 BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
3754            u64, flags, void *, meta, u64, meta_size)
3755 {
3756         u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
3757
3758         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
3759                 return -EINVAL;
3760         if (unlikely(!skb || skb_size > skb->len))
3761                 return -EFAULT;
3762
3763         return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
3764                                 bpf_skb_copy);
3765 }
3766
3767 static const struct bpf_func_proto bpf_skb_event_output_proto = {
3768         .func           = bpf_skb_event_output,
3769         .gpl_only       = true,
3770         .ret_type       = RET_INTEGER,
3771         .arg1_type      = ARG_PTR_TO_CTX,
3772         .arg2_type      = ARG_CONST_MAP_PTR,
3773         .arg3_type      = ARG_ANYTHING,
3774         .arg4_type      = ARG_PTR_TO_MEM,
3775         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
3776 };
3777
3778 static int bpf_skb_output_btf_ids[5];
3779 const struct bpf_func_proto bpf_skb_output_proto = {
3780         .func           = bpf_skb_event_output,
3781         .gpl_only       = true,
3782         .ret_type       = RET_INTEGER,
3783         .arg1_type      = ARG_PTR_TO_BTF_ID,
3784         .arg2_type      = ARG_CONST_MAP_PTR,
3785         .arg3_type      = ARG_ANYTHING,
3786         .arg4_type      = ARG_PTR_TO_MEM,
3787         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
3788         .btf_id         = bpf_skb_output_btf_ids,
3789 };
3790
3791 static unsigned short bpf_tunnel_key_af(u64 flags)
3792 {
3793         return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
3794 }
3795
3796 BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
3797            u32, size, u64, flags)
3798 {
3799         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3800         u8 compat[sizeof(struct bpf_tunnel_key)];
3801         void *to_orig = to;
3802         int err;
3803
3804         if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) {
3805                 err = -EINVAL;
3806                 goto err_clear;
3807         }
3808         if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
3809                 err = -EPROTO;
3810                 goto err_clear;
3811         }
3812         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3813                 err = -EINVAL;
3814                 switch (size) {
3815                 case offsetof(struct bpf_tunnel_key, tunnel_label):
3816                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
3817                         goto set_compat;
3818                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3819                         /* Fixup deprecated structure layouts here, so we have
3820                          * a common path later on.
3821                          */
3822                         if (ip_tunnel_info_af(info) != AF_INET)
3823                                 goto err_clear;
3824 set_compat:
3825                         to = (struct bpf_tunnel_key *)compat;
3826                         break;
3827                 default:
3828                         goto err_clear;
3829                 }
3830         }
3831
3832         to->tunnel_id = be64_to_cpu(info->key.tun_id);
3833         to->tunnel_tos = info->key.tos;
3834         to->tunnel_ttl = info->key.ttl;
3835         to->tunnel_ext = 0;
3836
3837         if (flags & BPF_F_TUNINFO_IPV6) {
3838                 memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
3839                        sizeof(to->remote_ipv6));
3840                 to->tunnel_label = be32_to_cpu(info->key.label);
3841         } else {
3842                 to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
3843                 memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
3844                 to->tunnel_label = 0;
3845         }
3846
3847         if (unlikely(size != sizeof(struct bpf_tunnel_key)))
3848                 memcpy(to_orig, to, size);
3849
3850         return 0;
3851 err_clear:
3852         memset(to_orig, 0, size);
3853         return err;
3854 }
3855
3856 static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
3857         .func           = bpf_skb_get_tunnel_key,
3858         .gpl_only       = false,
3859         .ret_type       = RET_INTEGER,
3860         .arg1_type      = ARG_PTR_TO_CTX,
3861         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
3862         .arg3_type      = ARG_CONST_SIZE,
3863         .arg4_type      = ARG_ANYTHING,
3864 };
3865
3866 BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
3867 {
3868         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3869         int err;
3870
3871         if (unlikely(!info ||
3872                      !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
3873                 err = -ENOENT;
3874                 goto err_clear;
3875         }
3876         if (unlikely(size < info->options_len)) {
3877                 err = -ENOMEM;
3878                 goto err_clear;
3879         }
3880
3881         ip_tunnel_info_opts_get(to, info);
3882         if (size > info->options_len)
3883                 memset(to + info->options_len, 0, size - info->options_len);
3884
3885         return info->options_len;
3886 err_clear:
3887         memset(to, 0, size);
3888         return err;
3889 }
3890
3891 static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
3892         .func           = bpf_skb_get_tunnel_opt,
3893         .gpl_only       = false,
3894         .ret_type       = RET_INTEGER,
3895         .arg1_type      = ARG_PTR_TO_CTX,
3896         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
3897         .arg3_type      = ARG_CONST_SIZE,
3898 };
3899
3900 static struct metadata_dst __percpu *md_dst;
3901
3902 BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
3903            const struct bpf_tunnel_key *, from, u32, size, u64, flags)
3904 {
3905         struct metadata_dst *md = this_cpu_ptr(md_dst);
3906         u8 compat[sizeof(struct bpf_tunnel_key)];
3907         struct ip_tunnel_info *info;
3908
3909         if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
3910                                BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER)))
3911                 return -EINVAL;
3912         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3913                 switch (size) {
3914                 case offsetof(struct bpf_tunnel_key, tunnel_label):
3915                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
3916                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3917                         /* Fixup deprecated structure layouts here, so we have
3918                          * a common path later on.
3919                          */
3920                         memcpy(compat, from, size);
3921                         memset(compat + size, 0, sizeof(compat) - size);
3922                         from = (const struct bpf_tunnel_key *) compat;
3923                         break;
3924                 default:
3925                         return -EINVAL;
3926                 }
3927         }
3928         if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
3929                      from->tunnel_ext))
3930                 return -EINVAL;
3931
3932         skb_dst_drop(skb);
3933         dst_hold((struct dst_entry *) md);
3934         skb_dst_set(skb, (struct dst_entry *) md);
3935
3936         info = &md->u.tun_info;
3937         memset(info, 0, sizeof(*info));
3938         info->mode = IP_TUNNEL_INFO_TX;
3939
3940         info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
3941         if (flags & BPF_F_DONT_FRAGMENT)
3942                 info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;
3943         if (flags & BPF_F_ZERO_CSUM_TX)
3944                 info->key.tun_flags &= ~TUNNEL_CSUM;
3945         if (flags & BPF_F_SEQ_NUMBER)
3946                 info->key.tun_flags |= TUNNEL_SEQ;
3947
3948         info->key.tun_id = cpu_to_be64(from->tunnel_id);
3949         info->key.tos = from->tunnel_tos;
3950         info->key.ttl = from->tunnel_ttl;
3951
3952         if (flags & BPF_F_TUNINFO_IPV6) {
3953                 info->mode |= IP_TUNNEL_INFO_IPV6;
3954                 memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
3955                        sizeof(from->remote_ipv6));
3956                 info->key.label = cpu_to_be32(from->tunnel_label) &
3957                                   IPV6_FLOWLABEL_MASK;
3958         } else {
3959                 info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
3960         }
3961
3962         return 0;
3963 }
3964
3965 static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
3966         .func           = bpf_skb_set_tunnel_key,
3967         .gpl_only       = false,
3968         .ret_type       = RET_INTEGER,
3969         .arg1_type      = ARG_PTR_TO_CTX,
3970         .arg2_type      = ARG_PTR_TO_MEM,
3971         .arg3_type      = ARG_CONST_SIZE,
3972         .arg4_type      = ARG_ANYTHING,
3973 };
3974
3975 BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
3976            const u8 *, from, u32, size)
3977 {
3978         struct ip_tunnel_info *info = skb_tunnel_info(skb);
3979         const struct metadata_dst *md = this_cpu_ptr(md_dst);
3980
3981         if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
3982                 return -EINVAL;
3983         if (unlikely(size > IP_TUNNEL_OPTS_MAX))
3984                 return -ENOMEM;
3985
3986         ip_tunnel_info_opts_set(info, from, size, TUNNEL_OPTIONS_PRESENT);
3987
3988         return 0;
3989 }
3990
3991 static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
3992         .func           = bpf_skb_set_tunnel_opt,
3993         .gpl_only       = false,
3994         .ret_type       = RET_INTEGER,
3995         .arg1_type      = ARG_PTR_TO_CTX,
3996         .arg2_type      = ARG_PTR_TO_MEM,
3997         .arg3_type      = ARG_CONST_SIZE,
3998 };
3999
4000 static const struct bpf_func_proto *
4001 bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
4002 {
4003         if (!md_dst) {
4004                 struct metadata_dst __percpu *tmp;
4005
4006                 tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
4007                                                 METADATA_IP_TUNNEL,
4008                                                 GFP_KERNEL);
4009                 if (!tmp)
4010                         return NULL;
4011                 if (cmpxchg(&md_dst, NULL, tmp))
4012                         metadata_dst_free_percpu(tmp);
4013         }
4014
4015         switch (which) {
4016         case BPF_FUNC_skb_set_tunnel_key:
4017                 return &bpf_skb_set_tunnel_key_proto;
4018         case BPF_FUNC_skb_set_tunnel_opt:
4019                 return &bpf_skb_set_tunnel_opt_proto;
4020         default:
4021                 return NULL;
4022         }
4023 }
4024
4025 BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
4026            u32, idx)
4027 {
4028         struct bpf_array *array = container_of(map, struct bpf_array, map);
4029         struct cgroup *cgrp;
4030         struct sock *sk;
4031
4032         sk = skb_to_full_sk(skb);
4033         if (!sk || !sk_fullsock(sk))
4034                 return -ENOENT;
4035         if (unlikely(idx >= array->map.max_entries))
4036                 return -E2BIG;
4037
4038         cgrp = READ_ONCE(array->ptrs[idx]);
4039         if (unlikely(!cgrp))
4040                 return -EAGAIN;
4041
4042         return sk_under_cgroup_hierarchy(sk, cgrp);
4043 }
4044
4045 static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
4046         .func           = bpf_skb_under_cgroup,
4047         .gpl_only       = false,
4048         .ret_type       = RET_INTEGER,
4049         .arg1_type      = ARG_PTR_TO_CTX,
4050         .arg2_type      = ARG_CONST_MAP_PTR,
4051         .arg3_type      = ARG_ANYTHING,
4052 };
4053
4054 #ifdef CONFIG_SOCK_CGROUP_DATA
4055 static inline u64 __bpf_sk_cgroup_id(struct sock *sk)
4056 {
4057         struct cgroup *cgrp;
4058
4059         cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4060         return cgroup_id(cgrp);
4061 }
4062
4063 BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
4064 {
4065         struct sock *sk = skb_to_full_sk(skb);
4066
4067         if (!sk || !sk_fullsock(sk))
4068                 return 0;
4069
4070         return __bpf_sk_cgroup_id(sk);
4071 }
4072
4073 static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
4074         .func           = bpf_skb_cgroup_id,
4075         .gpl_only       = false,
4076         .ret_type       = RET_INTEGER,
4077         .arg1_type      = ARG_PTR_TO_CTX,
4078 };
4079
4080 static inline u64 __bpf_sk_ancestor_cgroup_id(struct sock *sk,
4081                                               int ancestor_level)
4082 {
4083         struct cgroup *ancestor;
4084         struct cgroup *cgrp;
4085
4086         cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4087         ancestor = cgroup_ancestor(cgrp, ancestor_level);
4088         if (!ancestor)
4089                 return 0;
4090
4091         return cgroup_id(ancestor);
4092 }
4093
4094 BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
4095            ancestor_level)
4096 {
4097         struct sock *sk = skb_to_full_sk(skb);
4098
4099         if (!sk || !sk_fullsock(sk))
4100                 return 0;
4101
4102         return __bpf_sk_ancestor_cgroup_id(sk, ancestor_level);
4103 }
4104
4105 static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
4106         .func           = bpf_skb_ancestor_cgroup_id,
4107         .gpl_only       = false,
4108         .ret_type       = RET_INTEGER,
4109         .arg1_type      = ARG_PTR_TO_CTX,
4110         .arg2_type      = ARG_ANYTHING,
4111 };
4112
4113 BPF_CALL_1(bpf_sk_cgroup_id, struct sock *, sk)
4114 {
4115         return __bpf_sk_cgroup_id(sk);
4116 }
4117
4118 static const struct bpf_func_proto bpf_sk_cgroup_id_proto = {
4119         .func           = bpf_sk_cgroup_id,
4120         .gpl_only       = false,
4121         .ret_type       = RET_INTEGER,
4122         .arg1_type      = ARG_PTR_TO_SOCKET,
4123 };
4124
4125 BPF_CALL_2(bpf_sk_ancestor_cgroup_id, struct sock *, sk, int, ancestor_level)
4126 {
4127         return __bpf_sk_ancestor_cgroup_id(sk, ancestor_level);
4128 }
4129
4130 static const struct bpf_func_proto bpf_sk_ancestor_cgroup_id_proto = {
4131         .func           = bpf_sk_ancestor_cgroup_id,
4132         .gpl_only       = false,
4133         .ret_type       = RET_INTEGER,
4134         .arg1_type      = ARG_PTR_TO_SOCKET,
4135         .arg2_type      = ARG_ANYTHING,
4136 };
4137 #endif
4138
4139 static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff,
4140                                   unsigned long off, unsigned long len)
4141 {
4142         memcpy(dst_buff, src_buff + off, len);
4143         return 0;
4144 }
4145
4146 BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
4147            u64, flags, void *, meta, u64, meta_size)
4148 {
4149         u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
4150
4151         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
4152                 return -EINVAL;
4153         if (unlikely(!xdp ||
4154                      xdp_size > (unsigned long)(xdp->data_end - xdp->data)))
4155                 return -EFAULT;
4156
4157         return bpf_event_output(map, flags, meta, meta_size, xdp->data,
4158                                 xdp_size, bpf_xdp_copy);
4159 }
4160
4161 static const struct bpf_func_proto bpf_xdp_event_output_proto = {
4162         .func           = bpf_xdp_event_output,
4163         .gpl_only       = true,
4164         .ret_type       = RET_INTEGER,
4165         .arg1_type      = ARG_PTR_TO_CTX,
4166         .arg2_type      = ARG_CONST_MAP_PTR,
4167         .arg3_type      = ARG_ANYTHING,
4168         .arg4_type      = ARG_PTR_TO_MEM,
4169         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
4170 };
4171
4172 static int bpf_xdp_output_btf_ids[5];
4173 const struct bpf_func_proto bpf_xdp_output_proto = {
4174         .func           = bpf_xdp_event_output,
4175         .gpl_only       = true,
4176         .ret_type       = RET_INTEGER,
4177         .arg1_type      = ARG_PTR_TO_BTF_ID,
4178         .arg2_type      = ARG_CONST_MAP_PTR,
4179         .arg3_type      = ARG_ANYTHING,
4180         .arg4_type      = ARG_PTR_TO_MEM,
4181         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
4182         .btf_id         = bpf_xdp_output_btf_ids,
4183 };
4184
4185 BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
4186 {
4187         return skb->sk ? sock_gen_cookie(skb->sk) : 0;
4188 }
4189
4190 static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
4191         .func           = bpf_get_socket_cookie,
4192         .gpl_only       = false,
4193         .ret_type       = RET_INTEGER,
4194         .arg1_type      = ARG_PTR_TO_CTX,
4195 };
4196
4197 BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
4198 {
4199         return sock_gen_cookie(ctx->sk);
4200 }
4201
4202 static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
4203         .func           = bpf_get_socket_cookie_sock_addr,
4204         .gpl_only       = false,
4205         .ret_type       = RET_INTEGER,
4206         .arg1_type      = ARG_PTR_TO_CTX,
4207 };
4208
4209 BPF_CALL_1(bpf_get_socket_cookie_sock, struct sock *, ctx)
4210 {
4211         return sock_gen_cookie(ctx);
4212 }
4213
4214 static const struct bpf_func_proto bpf_get_socket_cookie_sock_proto = {
4215         .func           = bpf_get_socket_cookie_sock,
4216         .gpl_only       = false,
4217         .ret_type       = RET_INTEGER,
4218         .arg1_type      = ARG_PTR_TO_CTX,
4219 };
4220
4221 BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
4222 {
4223         return sock_gen_cookie(ctx->sk);
4224 }
4225
4226 static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
4227         .func           = bpf_get_socket_cookie_sock_ops,
4228         .gpl_only       = false,
4229         .ret_type       = RET_INTEGER,
4230         .arg1_type      = ARG_PTR_TO_CTX,
4231 };
4232
4233 static u64 __bpf_get_netns_cookie(struct sock *sk)
4234 {
4235 #ifdef CONFIG_NET_NS
4236         return net_gen_cookie(sk ? sk->sk_net.net : &init_net);
4237 #else
4238         return 0;
4239 #endif
4240 }
4241
4242 BPF_CALL_1(bpf_get_netns_cookie_sock, struct sock *, ctx)
4243 {
4244         return __bpf_get_netns_cookie(ctx);
4245 }
4246
4247 static const struct bpf_func_proto bpf_get_netns_cookie_sock_proto = {
4248         .func           = bpf_get_netns_cookie_sock,
4249         .gpl_only       = false,
4250         .ret_type       = RET_INTEGER,
4251         .arg1_type      = ARG_PTR_TO_CTX_OR_NULL,
4252 };
4253
4254 BPF_CALL_1(bpf_get_netns_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
4255 {
4256         return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
4257 }
4258
4259 static const struct bpf_func_proto bpf_get_netns_cookie_sock_addr_proto = {
4260         .func           = bpf_get_netns_cookie_sock_addr,
4261         .gpl_only       = false,
4262         .ret_type       = RET_INTEGER,
4263         .arg1_type      = ARG_PTR_TO_CTX_OR_NULL,
4264 };
4265
4266 BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
4267 {
4268         struct sock *sk = sk_to_full_sk(skb->sk);
4269         kuid_t kuid;
4270
4271         if (!sk || !sk_fullsock(sk))
4272                 return overflowuid;
4273         kuid = sock_net_uid(sock_net(sk), sk);
4274         return from_kuid_munged(sock_net(sk)->user_ns, kuid);
4275 }
4276
4277 static const struct bpf_func_proto bpf_get_socket_uid_proto = {
4278         .func           = bpf_get_socket_uid,
4279         .gpl_only       = false,
4280         .ret_type       = RET_INTEGER,
4281         .arg1_type      = ARG_PTR_TO_CTX,
4282 };
4283
4284 #define SOCKOPT_CC_REINIT (1 << 0)
4285
4286 static int _bpf_setsockopt(struct sock *sk, int level, int optname,
4287                            char *optval, int optlen, u32 flags)
4288 {
4289         char devname[IFNAMSIZ];
4290         struct net *net;
4291         int ifindex;
4292         int ret = 0;
4293         int val;
4294
4295         if (!sk_fullsock(sk))
4296                 return -EINVAL;
4297
4298         sock_owned_by_me(sk);
4299
4300         if (level == SOL_SOCKET) {
4301                 if (optlen != sizeof(int) && optname != SO_BINDTODEVICE)
4302                         return -EINVAL;
4303                 val = *((int *)optval);
4304
4305                 /* Only some socketops are supported */
4306                 switch (optname) {
4307                 case SO_RCVBUF:
4308                         val = min_t(u32, val, sysctl_rmem_max);
4309                         sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
4310                         WRITE_ONCE(sk->sk_rcvbuf,
4311                                    max_t(int, val * 2, SOCK_MIN_RCVBUF));
4312                         break;
4313                 case SO_SNDBUF:
4314                         val = min_t(u32, val, sysctl_wmem_max);
4315                         sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
4316                         WRITE_ONCE(sk->sk_sndbuf,
4317                                    max_t(int, val * 2, SOCK_MIN_SNDBUF));
4318                         break;
4319                 case SO_MAX_PACING_RATE: /* 32bit version */
4320                         if (val != ~0U)
4321                                 cmpxchg(&sk->sk_pacing_status,
4322                                         SK_PACING_NONE,
4323                                         SK_PACING_NEEDED);
4324                         sk->sk_max_pacing_rate = (val == ~0U) ? ~0UL : val;
4325                         sk->sk_pacing_rate = min(sk->sk_pacing_rate,
4326                                                  sk->sk_max_pacing_rate);
4327                         break;
4328                 case SO_PRIORITY:
4329                         sk->sk_priority = val;
4330                         break;
4331                 case SO_RCVLOWAT:
4332                         if (val < 0)
4333                                 val = INT_MAX;
4334                         WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
4335                         break;
4336                 case SO_MARK:
4337                         if (sk->sk_mark != val) {
4338                                 sk->sk_mark = val;
4339                                 sk_dst_reset(sk);
4340                         }
4341                         break;
4342                 case SO_BINDTODEVICE:
4343                         ret = -ENOPROTOOPT;
4344 #ifdef CONFIG_NETDEVICES
4345                         optlen = min_t(long, optlen, IFNAMSIZ - 1);
4346                         strncpy(devname, optval, optlen);
4347                         devname[optlen] = 0;
4348
4349                         ifindex = 0;
4350                         if (devname[0] != '\0') {
4351                                 struct net_device *dev;
4352
4353                                 ret = -ENODEV;
4354
4355                                 net = sock_net(sk);
4356                                 dev = dev_get_by_name(net, devname);
4357                                 if (!dev)
4358                                         break;
4359                                 ifindex = dev->ifindex;
4360                                 dev_put(dev);
4361                         }
4362                         ret = sock_bindtoindex(sk, ifindex, false);
4363 #endif
4364                         break;
4365                 default:
4366                         ret = -EINVAL;
4367                 }
4368 #ifdef CONFIG_INET
4369         } else if (level == SOL_IP) {
4370                 if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4371                         return -EINVAL;
4372
4373                 val = *((int *)optval);
4374                 /* Only some options are supported */
4375                 switch (optname) {
4376                 case IP_TOS:
4377                         if (val < -1 || val > 0xff) {
4378                                 ret = -EINVAL;
4379                         } else {
4380                                 struct inet_sock *inet = inet_sk(sk);
4381
4382                                 if (val == -1)
4383                                         val = 0;
4384                                 inet->tos = val;
4385                         }
4386                         break;
4387                 default:
4388                         ret = -EINVAL;
4389                 }
4390 #if IS_ENABLED(CONFIG_IPV6)
4391         } else if (level == SOL_IPV6) {
4392                 if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4393                         return -EINVAL;
4394
4395                 val = *((int *)optval);
4396                 /* Only some options are supported */
4397                 switch (optname) {
4398                 case IPV6_TCLASS:
4399                         if (val < -1 || val > 0xff) {
4400                                 ret = -EINVAL;
4401                         } else {
4402                                 struct ipv6_pinfo *np = inet6_sk(sk);
4403
4404                                 if (val == -1)
4405                                         val = 0;
4406                                 np->tclass = val;
4407                         }
4408                         break;
4409                 default:
4410                         ret = -EINVAL;
4411                 }
4412 #endif
4413         } else if (level == SOL_TCP &&
4414                    sk->sk_prot->setsockopt == tcp_setsockopt) {
4415                 if (optname == TCP_CONGESTION) {
4416                         char name[TCP_CA_NAME_MAX];
4417                         bool reinit = flags & SOCKOPT_CC_REINIT;
4418
4419                         strncpy(name, optval, min_t(long, optlen,
4420                                                     TCP_CA_NAME_MAX-1));
4421                         name[TCP_CA_NAME_MAX-1] = 0;
4422                         ret = tcp_set_congestion_control(sk, name, false,
4423                                                          reinit, true);
4424                 } else {
4425                         struct tcp_sock *tp = tcp_sk(sk);
4426
4427                         if (optlen != sizeof(int))
4428                                 return -EINVAL;
4429
4430                         val = *((int *)optval);
4431                         /* Only some options are supported */
4432                         switch (optname) {
4433                         case TCP_BPF_IW:
4434                                 if (val <= 0 || tp->data_segs_out > tp->syn_data)
4435                                         ret = -EINVAL;
4436                                 else
4437                                         tp->snd_cwnd = val;
4438                                 break;
4439                         case TCP_BPF_SNDCWND_CLAMP:
4440                                 if (val <= 0) {
4441                                         ret = -EINVAL;
4442                                 } else {
4443                                         tp->snd_cwnd_clamp = val;
4444                                         tp->snd_ssthresh = val;
4445                                 }
4446                                 break;
4447                         case TCP_SAVE_SYN:
4448                                 if (val < 0 || val > 1)
4449                                         ret = -EINVAL;
4450                                 else
4451                                         tp->save_syn = val;
4452                                 break;
4453                         default:
4454                                 ret = -EINVAL;
4455                         }
4456                 }
4457 #endif
4458         } else {
4459                 ret = -EINVAL;
4460         }
4461         return ret;
4462 }
4463
4464 static int _bpf_getsockopt(struct sock *sk, int level, int optname,
4465                            char *optval, int optlen)
4466 {
4467         if (!sk_fullsock(sk))
4468                 goto err_clear;
4469
4470         sock_owned_by_me(sk);
4471
4472 #ifdef CONFIG_INET
4473         if (level == SOL_TCP && sk->sk_prot->getsockopt == tcp_getsockopt) {
4474                 struct inet_connection_sock *icsk;
4475                 struct tcp_sock *tp;
4476
4477                 switch (optname) {
4478                 case TCP_CONGESTION:
4479                         icsk = inet_csk(sk);
4480
4481                         if (!icsk->icsk_ca_ops || optlen <= 1)
4482                                 goto err_clear;
4483                         strncpy(optval, icsk->icsk_ca_ops->name, optlen);
4484                         optval[optlen - 1] = 0;
4485                         break;
4486                 case TCP_SAVED_SYN:
4487                         tp = tcp_sk(sk);
4488
4489                         if (optlen <= 0 || !tp->saved_syn ||
4490                             optlen > tp->saved_syn[0])
4491                                 goto err_clear;
4492                         memcpy(optval, tp->saved_syn + 1, optlen);
4493                         break;
4494                 default:
4495                         goto err_clear;
4496                 }
4497         } else if (level == SOL_IP) {
4498                 struct inet_sock *inet = inet_sk(sk);
4499
4500                 if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4501                         goto err_clear;
4502
4503                 /* Only some options are supported */
4504                 switch (optname) {
4505                 case IP_TOS:
4506                         *((int *)optval) = (int)inet->tos;
4507                         break;
4508                 default:
4509                         goto err_clear;
4510                 }
4511 #if IS_ENABLED(CONFIG_IPV6)
4512         } else if (level == SOL_IPV6) {
4513                 struct ipv6_pinfo *np = inet6_sk(sk);
4514
4515                 if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4516                         goto err_clear;
4517
4518                 /* Only some options are supported */
4519                 switch (optname) {
4520                 case IPV6_TCLASS:
4521                         *((int *)optval) = (int)np->tclass;
4522                         break;
4523                 default:
4524                         goto err_clear;
4525                 }
4526 #endif
4527         } else {
4528                 goto err_clear;
4529         }
4530         return 0;
4531 #endif
4532 err_clear:
4533         memset(optval, 0, optlen);
4534         return -EINVAL;
4535 }
4536
4537 BPF_CALL_5(bpf_sock_addr_setsockopt, struct bpf_sock_addr_kern *, ctx,
4538            int, level, int, optname, char *, optval, int, optlen)
4539 {
4540         u32 flags = 0;
4541         return _bpf_setsockopt(ctx->sk, level, optname, optval, optlen,
4542                                flags);
4543 }
4544
4545 static const struct bpf_func_proto bpf_sock_addr_setsockopt_proto = {
4546         .func           = bpf_sock_addr_setsockopt,
4547         .gpl_only       = false,
4548         .ret_type       = RET_INTEGER,
4549         .arg1_type      = ARG_PTR_TO_CTX,
4550         .arg2_type      = ARG_ANYTHING,
4551         .arg3_type      = ARG_ANYTHING,
4552         .arg4_type      = ARG_PTR_TO_MEM,
4553         .arg5_type      = ARG_CONST_SIZE,
4554 };
4555
4556 BPF_CALL_5(bpf_sock_addr_getsockopt, struct bpf_sock_addr_kern *, ctx,
4557            int, level, int, optname, char *, optval, int, optlen)
4558 {
4559         return _bpf_getsockopt(ctx->sk, level, optname, optval, optlen);
4560 }
4561
4562 static const struct bpf_func_proto bpf_sock_addr_getsockopt_proto = {
4563         .func           = bpf_sock_addr_getsockopt,
4564         .gpl_only       = false,
4565         .ret_type       = RET_INTEGER,
4566         .arg1_type      = ARG_PTR_TO_CTX,
4567         .arg2_type      = ARG_ANYTHING,
4568         .arg3_type      = ARG_ANYTHING,
4569         .arg4_type      = ARG_PTR_TO_UNINIT_MEM,
4570         .arg5_type      = ARG_CONST_SIZE,
4571 };
4572
4573 BPF_CALL_5(bpf_sock_ops_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4574            int, level, int, optname, char *, optval, int, optlen)
4575 {
4576         u32 flags = 0;
4577         if (bpf_sock->op > BPF_SOCK_OPS_NEEDS_ECN)
4578                 flags |= SOCKOPT_CC_REINIT;
4579         return _bpf_setsockopt(bpf_sock->sk, level, optname, optval, optlen,
4580                                flags);
4581 }
4582
4583 static const struct bpf_func_proto bpf_sock_ops_setsockopt_proto = {
4584         .func           = bpf_sock_ops_setsockopt,
4585         .gpl_only       = false,
4586         .ret_type       = RET_INTEGER,
4587         .arg1_type      = ARG_PTR_TO_CTX,
4588         .arg2_type      = ARG_ANYTHING,
4589         .arg3_type      = ARG_ANYTHING,
4590         .arg4_type      = ARG_PTR_TO_MEM,
4591         .arg5_type      = ARG_CONST_SIZE,
4592 };
4593
4594 BPF_CALL_5(bpf_sock_ops_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4595            int, level, int, optname, char *, optval, int, optlen)
4596 {
4597         return _bpf_getsockopt(bpf_sock->sk, level, optname, optval, optlen);
4598 }
4599
4600 static const struct bpf_func_proto bpf_sock_ops_getsockopt_proto = {
4601         .func           = bpf_sock_ops_getsockopt,
4602         .gpl_only       = false,
4603         .ret_type       = RET_INTEGER,
4604         .arg1_type      = ARG_PTR_TO_CTX,
4605         .arg2_type      = ARG_ANYTHING,
4606         .arg3_type      = ARG_ANYTHING,
4607         .arg4_type      = ARG_PTR_TO_UNINIT_MEM,
4608         .arg5_type      = ARG_CONST_SIZE,
4609 };
4610
4611 BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
4612            int, argval)
4613 {
4614         struct sock *sk = bpf_sock->sk;
4615         int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
4616
4617         if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
4618                 return -EINVAL;
4619
4620         tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
4621
4622         return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
4623 }
4624
4625 static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
4626         .func           = bpf_sock_ops_cb_flags_set,
4627         .gpl_only       = false,
4628         .ret_type       = RET_INTEGER,
4629         .arg1_type      = ARG_PTR_TO_CTX,
4630         .arg2_type      = ARG_ANYTHING,
4631 };
4632
4633 const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly;
4634 EXPORT_SYMBOL_GPL(ipv6_bpf_stub);
4635
4636 BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
4637            int, addr_len)
4638 {
4639 #ifdef CONFIG_INET
4640         struct sock *sk = ctx->sk;
4641         u32 flags = BIND_FROM_BPF;
4642         int err;
4643
4644         err = -EINVAL;
4645         if (addr_len < offsetofend(struct sockaddr, sa_family))
4646                 return err;
4647         if (addr->sa_family == AF_INET) {
4648                 if (addr_len < sizeof(struct sockaddr_in))
4649                         return err;
4650                 if (((struct sockaddr_in *)addr)->sin_port == htons(0))
4651                         flags |= BIND_FORCE_ADDRESS_NO_PORT;
4652                 return __inet_bind(sk, addr, addr_len, flags);
4653 #if IS_ENABLED(CONFIG_IPV6)
4654         } else if (addr->sa_family == AF_INET6) {
4655                 if (addr_len < SIN6_LEN_RFC2133)
4656                         return err;
4657                 if (((struct sockaddr_in6 *)addr)->sin6_port == htons(0))
4658                         flags |= BIND_FORCE_ADDRESS_NO_PORT;
4659                 /* ipv6_bpf_stub cannot be NULL, since it's called from
4660                  * bpf_cgroup_inet6_connect hook and ipv6 is already loaded
4661                  */
4662                 return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, flags);
4663 #endif /* CONFIG_IPV6 */
4664         }
4665 #endif /* CONFIG_INET */
4666
4667         return -EAFNOSUPPORT;
4668 }
4669
4670 static const struct bpf_func_proto bpf_bind_proto = {
4671         .func           = bpf_bind,
4672         .gpl_only       = false,
4673         .ret_type       = RET_INTEGER,
4674         .arg1_type      = ARG_PTR_TO_CTX,
4675         .arg2_type      = ARG_PTR_TO_MEM,
4676         .arg3_type      = ARG_CONST_SIZE,
4677 };
4678
4679 #ifdef CONFIG_XFRM
4680 BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
4681            struct bpf_xfrm_state *, to, u32, size, u64, flags)
4682 {
4683         const struct sec_path *sp = skb_sec_path(skb);
4684         const struct xfrm_state *x;
4685
4686         if (!sp || unlikely(index >= sp->len || flags))
4687                 goto err_clear;
4688
4689         x = sp->xvec[index];
4690
4691         if (unlikely(size != sizeof(struct bpf_xfrm_state)))
4692                 goto err_clear;
4693
4694         to->reqid = x->props.reqid;
4695         to->spi = x->id.spi;
4696         to->family = x->props.family;
4697         to->ext = 0;
4698
4699         if (to->family == AF_INET6) {
4700                 memcpy(to->remote_ipv6, x->props.saddr.a6,
4701                        sizeof(to->remote_ipv6));
4702         } else {
4703                 to->remote_ipv4 = x->props.saddr.a4;
4704                 memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4705         }
4706
4707         return 0;
4708 err_clear:
4709         memset(to, 0, size);
4710         return -EINVAL;
4711 }
4712
4713 static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
4714         .func           = bpf_skb_get_xfrm_state,
4715         .gpl_only       = false,
4716         .ret_type       = RET_INTEGER,
4717         .arg1_type      = ARG_PTR_TO_CTX,
4718         .arg2_type      = ARG_ANYTHING,
4719         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
4720         .arg4_type      = ARG_CONST_SIZE,
4721         .arg5_type      = ARG_ANYTHING,
4722 };
4723 #endif
4724
4725 #if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
4726 static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params,
4727                                   const struct neighbour *neigh,
4728                                   const struct net_device *dev)
4729 {
4730         memcpy(params->dmac, neigh->ha, ETH_ALEN);
4731         memcpy(params->smac, dev->dev_addr, ETH_ALEN);
4732         params->h_vlan_TCI = 0;
4733         params->h_vlan_proto = 0;
4734         params->ifindex = dev->ifindex;
4735
4736         return 0;
4737 }
4738 #endif
4739
4740 #if IS_ENABLED(CONFIG_INET)
4741 static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4742                                u32 flags, bool check_mtu)
4743 {
4744         struct fib_nh_common *nhc;
4745         struct in_device *in_dev;
4746         struct neighbour *neigh;
4747         struct net_device *dev;
4748         struct fib_result res;
4749         struct flowi4 fl4;
4750         int err;
4751         u32 mtu;
4752
4753         dev = dev_get_by_index_rcu(net, params->ifindex);
4754         if (unlikely(!dev))
4755                 return -ENODEV;
4756
4757         /* verify forwarding is enabled on this interface */
4758         in_dev = __in_dev_get_rcu(dev);
4759         if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
4760                 return BPF_FIB_LKUP_RET_FWD_DISABLED;
4761
4762         if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4763                 fl4.flowi4_iif = 1;
4764                 fl4.flowi4_oif = params->ifindex;
4765         } else {
4766                 fl4.flowi4_iif = params->ifindex;
4767                 fl4.flowi4_oif = 0;
4768         }
4769         fl4.flowi4_tos = params->tos & IPTOS_RT_MASK;
4770         fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
4771         fl4.flowi4_flags = 0;
4772
4773         fl4.flowi4_proto = params->l4_protocol;
4774         fl4.daddr = params->ipv4_dst;
4775         fl4.saddr = params->ipv4_src;
4776         fl4.fl4_sport = params->sport;
4777         fl4.fl4_dport = params->dport;
4778
4779         if (flags & BPF_FIB_LOOKUP_DIRECT) {
4780                 u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4781                 struct fib_table *tb;
4782
4783                 tb = fib_get_table(net, tbid);
4784                 if (unlikely(!tb))
4785                         return BPF_FIB_LKUP_RET_NOT_FWDED;
4786
4787                 err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
4788         } else {
4789                 fl4.flowi4_mark = 0;
4790                 fl4.flowi4_secid = 0;
4791                 fl4.flowi4_tun_key.tun_id = 0;
4792                 fl4.flowi4_uid = sock_net_uid(net, NULL);
4793
4794                 err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
4795         }
4796
4797         if (err) {
4798                 /* map fib lookup errors to RTN_ type */
4799                 if (err == -EINVAL)
4800                         return BPF_FIB_LKUP_RET_BLACKHOLE;
4801                 if (err == -EHOSTUNREACH)
4802                         return BPF_FIB_LKUP_RET_UNREACHABLE;
4803                 if (err == -EACCES)
4804                         return BPF_FIB_LKUP_RET_PROHIBIT;
4805
4806                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4807         }
4808
4809         if (res.type != RTN_UNICAST)
4810                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4811
4812         if (fib_info_num_path(res.fi) > 1)
4813                 fib_select_path(net, &res, &fl4, NULL);
4814
4815         if (check_mtu) {
4816                 mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
4817                 if (params->tot_len > mtu)
4818                         return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4819         }
4820
4821         nhc = res.nhc;
4822
4823         /* do not handle lwt encaps right now */
4824         if (nhc->nhc_lwtstate)
4825                 return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4826
4827         dev = nhc->nhc_dev;
4828
4829         params->rt_metric = res.fi->fib_priority;
4830
4831         /* xdp and cls_bpf programs are run in RCU-bh so
4832          * rcu_read_lock_bh is not needed here
4833          */
4834         if (likely(nhc->nhc_gw_family != AF_INET6)) {
4835                 if (nhc->nhc_gw_family)
4836                         params->ipv4_dst = nhc->nhc_gw.ipv4;
4837
4838                 neigh = __ipv4_neigh_lookup_noref(dev,
4839                                                  (__force u32)params->ipv4_dst);
4840         } else {
4841                 struct in6_addr *dst = (struct in6_addr *)params->ipv6_dst;
4842
4843                 params->family = AF_INET6;
4844                 *dst = nhc->nhc_gw.ipv6;
4845                 neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
4846         }
4847
4848         if (!neigh)
4849                 return BPF_FIB_LKUP_RET_NO_NEIGH;
4850
4851         return bpf_fib_set_fwd_params(params, neigh, dev);
4852 }
4853 #endif
4854
4855 #if IS_ENABLED(CONFIG_IPV6)
4856 static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4857                                u32 flags, bool check_mtu)
4858 {
4859         struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
4860         struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
4861         struct fib6_result res = {};
4862         struct neighbour *neigh;
4863         struct net_device *dev;
4864         struct inet6_dev *idev;
4865         struct flowi6 fl6;
4866         int strict = 0;
4867         int oif, err;
4868         u32 mtu;
4869
4870         /* link local addresses are never forwarded */
4871         if (rt6_need_strict(dst) || rt6_need_strict(src))
4872                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4873
4874         dev = dev_get_by_index_rcu(net, params->ifindex);
4875         if (unlikely(!dev))
4876                 return -ENODEV;
4877
4878         idev = __in6_dev_get_safely(dev);
4879         if (unlikely(!idev || !idev->cnf.forwarding))
4880                 return BPF_FIB_LKUP_RET_FWD_DISABLED;
4881
4882         if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4883                 fl6.flowi6_iif = 1;
4884                 oif = fl6.flowi6_oif = params->ifindex;
4885         } else {
4886                 oif = fl6.flowi6_iif = params->ifindex;
4887                 fl6.flowi6_oif = 0;
4888                 strict = RT6_LOOKUP_F_HAS_SADDR;
4889         }
4890         fl6.flowlabel = params->flowinfo;
4891         fl6.flowi6_scope = 0;
4892         fl6.flowi6_flags = 0;
4893         fl6.mp_hash = 0;
4894
4895         fl6.flowi6_proto = params->l4_protocol;
4896         fl6.daddr = *dst;
4897         fl6.saddr = *src;
4898         fl6.fl6_sport = params->sport;
4899         fl6.fl6_dport = params->dport;
4900
4901         if (flags & BPF_FIB_LOOKUP_DIRECT) {
4902                 u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4903                 struct fib6_table *tb;
4904
4905                 tb = ipv6_stub->fib6_get_table(net, tbid);
4906                 if (unlikely(!tb))
4907                         return BPF_FIB_LKUP_RET_NOT_FWDED;
4908
4909                 err = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, &res,
4910                                                    strict);
4911         } else {
4912                 fl6.flowi6_mark = 0;
4913                 fl6.flowi6_secid = 0;
4914                 fl6.flowi6_tun_key.tun_id = 0;
4915                 fl6.flowi6_uid = sock_net_uid(net, NULL);
4916
4917                 err = ipv6_stub->fib6_lookup(net, oif, &fl6, &res, strict);
4918         }
4919
4920         if (unlikely(err || IS_ERR_OR_NULL(res.f6i) ||
4921                      res.f6i == net->ipv6.fib6_null_entry))
4922                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4923
4924         switch (res.fib6_type) {
4925         /* only unicast is forwarded */
4926         case RTN_UNICAST:
4927                 break;
4928         case RTN_BLACKHOLE:
4929                 return BPF_FIB_LKUP_RET_BLACKHOLE;
4930         case RTN_UNREACHABLE:
4931                 return BPF_FIB_LKUP_RET_UNREACHABLE;
4932         case RTN_PROHIBIT:
4933                 return BPF_FIB_LKUP_RET_PROHIBIT;
4934         default:
4935                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4936         }
4937
4938         ipv6_stub->fib6_select_path(net, &res, &fl6, fl6.flowi6_oif,
4939                                     fl6.flowi6_oif != 0, NULL, strict);
4940
4941         if (check_mtu) {
4942                 mtu = ipv6_stub->ip6_mtu_from_fib6(&res, dst, src);
4943                 if (params->tot_len > mtu)
4944                         return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4945         }
4946
4947         if (res.nh->fib_nh_lws)
4948                 return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4949
4950         if (res.nh->fib_nh_gw_family)
4951                 *dst = res.nh->fib_nh_gw6;
4952
4953         dev = res.nh->fib_nh_dev;
4954         params->rt_metric = res.f6i->fib6_metric;
4955
4956         /* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
4957          * not needed here.
4958          */
4959         neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
4960         if (!neigh)
4961                 return BPF_FIB_LKUP_RET_NO_NEIGH;
4962
4963         return bpf_fib_set_fwd_params(params, neigh, dev);
4964 }
4965 #endif
4966
4967 BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
4968            struct bpf_fib_lookup *, params, int, plen, u32, flags)
4969 {
4970         if (plen < sizeof(*params))
4971                 return -EINVAL;
4972
4973         if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4974                 return -EINVAL;
4975
4976         switch (params->family) {
4977 #if IS_ENABLED(CONFIG_INET)
4978         case AF_INET:
4979                 return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
4980                                            flags, true);
4981 #endif
4982 #if IS_ENABLED(CONFIG_IPV6)
4983         case AF_INET6:
4984                 return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
4985                                            flags, true);
4986 #endif
4987         }
4988         return -EAFNOSUPPORT;
4989 }
4990
4991 static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
4992         .func           = bpf_xdp_fib_lookup,
4993         .gpl_only       = true,
4994         .ret_type       = RET_INTEGER,
4995         .arg1_type      = ARG_PTR_TO_CTX,
4996         .arg2_type      = ARG_PTR_TO_MEM,
4997         .arg3_type      = ARG_CONST_SIZE,
4998         .arg4_type      = ARG_ANYTHING,
4999 };
5000
5001 BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
5002            struct bpf_fib_lookup *, params, int, plen, u32, flags)
5003 {
5004         struct net *net = dev_net(skb->dev);
5005         int rc = -EAFNOSUPPORT;
5006
5007         if (plen < sizeof(*params))
5008                 return -EINVAL;
5009
5010         if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
5011                 return -EINVAL;
5012
5013         switch (params->family) {
5014 #if IS_ENABLED(CONFIG_INET)
5015         case AF_INET:
5016                 rc = bpf_ipv4_fib_lookup(net, params, flags, false);
5017                 break;
5018 #endif
5019 #if IS_ENABLED(CONFIG_IPV6)
5020         case AF_INET6:
5021                 rc = bpf_ipv6_fib_lookup(net, params, flags, false);
5022                 break;
5023 #endif
5024         }
5025
5026         if (!rc) {
5027                 struct net_device *dev;
5028
5029                 dev = dev_get_by_index_rcu(net, params->ifindex);
5030                 if (!is_skb_forwardable(dev, skb))
5031                         rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
5032         }
5033
5034         return rc;
5035 }
5036
5037 static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
5038         .func           = bpf_skb_fib_lookup,
5039         .gpl_only       = true,
5040         .ret_type       = RET_INTEGER,
5041         .arg1_type      = ARG_PTR_TO_CTX,
5042         .arg2_type      = ARG_PTR_TO_MEM,
5043         .arg3_type      = ARG_CONST_SIZE,
5044         .arg4_type      = ARG_ANYTHING,
5045 };
5046
5047 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
5048 static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
5049 {
5050         int err;
5051         struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;
5052
5053         if (!seg6_validate_srh(srh, len))
5054                 return -EINVAL;
5055
5056         switch (type) {
5057         case BPF_LWT_ENCAP_SEG6_INLINE:
5058                 if (skb->protocol != htons(ETH_P_IPV6))
5059                         return -EBADMSG;
5060
5061                 err = seg6_do_srh_inline(skb, srh);
5062                 break;
5063         case BPF_LWT_ENCAP_SEG6:
5064                 skb_reset_inner_headers(skb);
5065                 skb->encapsulation = 1;
5066                 err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
5067                 break;
5068         default:
5069                 return -EINVAL;
5070         }
5071
5072         bpf_compute_data_pointers(skb);
5073         if (err)
5074                 return err;
5075
5076         ipv6_hdr(skb)->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
5077         skb_set_transport_header(skb, sizeof(struct ipv6hdr));
5078
5079         return seg6_lookup_nexthop(skb, NULL, 0);
5080 }
5081 #endif /* CONFIG_IPV6_SEG6_BPF */
5082
5083 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
5084 static int bpf_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len,
5085                              bool ingress)
5086 {
5087         return bpf_lwt_push_ip_encap(skb, hdr, len, ingress);
5088 }
5089 #endif
5090
5091 BPF_CALL_4(bpf_lwt_in_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
5092            u32, len)
5093 {
5094         switch (type) {
5095 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
5096         case BPF_LWT_ENCAP_SEG6:
5097         case BPF_LWT_ENCAP_SEG6_INLINE:
5098                 return bpf_push_seg6_encap(skb, type, hdr, len);
5099 #endif
5100 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
5101         case BPF_LWT_ENCAP_IP:
5102                 return bpf_push_ip_encap(skb, hdr, len, true /* ingress */);
5103 #endif
5104         default:
5105                 return -EINVAL;
5106         }
5107 }
5108
5109 BPF_CALL_4(bpf_lwt_xmit_push_encap, struct sk_buff *, skb, u32, type,
5110            void *, hdr, u32, len)
5111 {
5112         switch (type) {
5113 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
5114         case BPF_LWT_ENCAP_IP:
5115                 return bpf_push_ip_encap(skb, hdr, len, false /* egress */);
5116 #endif
5117         default:
5118                 return -EINVAL;
5119         }
5120 }
5121
5122 static const struct bpf_func_proto bpf_lwt_in_push_encap_proto = {
5123         .func           = bpf_lwt_in_push_encap,
5124         .gpl_only       = false,
5125         .ret_type       = RET_INTEGER,
5126         .arg1_type      = ARG_PTR_TO_CTX,
5127         .arg2_type      = ARG_ANYTHING,
5128         .arg3_type      = ARG_PTR_TO_MEM,
5129         .arg4_type      = ARG_CONST_SIZE
5130 };
5131
5132 static const struct bpf_func_proto bpf_lwt_xmit_push_encap_proto = {
5133         .func           = bpf_lwt_xmit_push_encap,
5134         .gpl_only       = false,
5135         .ret_type       = RET_INTEGER,
5136         .arg1_type      = ARG_PTR_TO_CTX,
5137         .arg2_type      = ARG_ANYTHING,
5138         .arg3_type      = ARG_PTR_TO_MEM,
5139         .arg4_type      = ARG_CONST_SIZE
5140 };
5141
5142 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
5143 BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
5144            const void *, from, u32, len)
5145 {
5146         struct seg6_bpf_srh_state *srh_state =
5147                 this_cpu_ptr(&seg6_bpf_srh_states);
5148         struct ipv6_sr_hdr *srh = srh_state->srh;
5149         void *srh_tlvs, *srh_end, *ptr;
5150         int srhoff = 0;
5151
5152         if (srh == NULL)
5153                 return -EINVAL;
5154
5155         srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
5156         srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
5157
5158         ptr = skb->data + offset;
5159         if (ptr >= srh_tlvs && ptr + len <= srh_end)
5160                 srh_state->valid = false;
5161         else if (ptr < (void *)&srh->flags ||
5162                  ptr + len > (void *)&srh->segments)
5163                 return -EFAULT;
5164
5165         if (unlikely(bpf_try_make_writable(skb, offset + len)))
5166                 return -EFAULT;
5167         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
5168                 return -EINVAL;
5169         srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5170
5171         memcpy(skb->data + offset, from, len);
5172         return 0;
5173 }
5174
5175 static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
5176         .func           = bpf_lwt_seg6_store_bytes,
5177         .gpl_only       = false,
5178         .ret_type       = RET_INTEGER,
5179         .arg1_type      = ARG_PTR_TO_CTX,
5180         .arg2_type      = ARG_ANYTHING,
5181         .arg3_type      = ARG_PTR_TO_MEM,
5182         .arg4_type      = ARG_CONST_SIZE
5183 };
5184
5185 static void bpf_update_srh_state(struct sk_buff *skb)
5186 {
5187         struct seg6_bpf_srh_state *srh_state =
5188                 this_cpu_ptr(&seg6_bpf_srh_states);
5189         int srhoff = 0;
5190
5191         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) {
5192                 srh_state->srh = NULL;
5193         } else {
5194                 srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5195                 srh_state->hdrlen = srh_state->srh->hdrlen << 3;
5196                 srh_state->valid = true;
5197         }
5198 }
5199
5200 BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
5201            u32, action, void *, param, u32, param_len)
5202 {
5203         struct seg6_bpf_srh_state *srh_state =
5204                 this_cpu_ptr(&seg6_bpf_srh_states);
5205         int hdroff = 0;
5206         int err;
5207
5208         switch (action) {
5209         case SEG6_LOCAL_ACTION_END_X:
5210                 if (!seg6_bpf_has_valid_srh(skb))
5211                         return -EBADMSG;
5212                 if (param_len != sizeof(struct in6_addr))
5213                         return -EINVAL;
5214                 return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
5215         case SEG6_LOCAL_ACTION_END_T:
5216                 if (!seg6_bpf_has_valid_srh(skb))
5217                         return -EBADMSG;
5218                 if (param_len != sizeof(int))
5219                         return -EINVAL;
5220                 return seg6_lookup_nexthop(skb, NULL, *(int *)param);
5221         case SEG6_LOCAL_ACTION_END_DT6:
5222                 if (!seg6_bpf_has_valid_srh(skb))
5223                         return -EBADMSG;
5224                 if (param_len != sizeof(int))
5225                         return -EINVAL;
5226
5227                 if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
5228                         return -EBADMSG;
5229                 if (!pskb_pull(skb, hdroff))
5230                         return -EBADMSG;
5231
5232                 skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
5233                 skb_reset_network_header(skb);
5234                 skb_reset_transport_header(skb);
5235                 skb->encapsulation = 0;
5236
5237                 bpf_compute_data_pointers(skb);
5238                 bpf_update_srh_state(skb);
5239                 return seg6_lookup_nexthop(skb, NULL, *(int *)param);
5240         case SEG6_LOCAL_ACTION_END_B6:
5241                 if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
5242                         return -EBADMSG;
5243                 err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
5244                                           param, param_len);
5245                 if (!err)
5246                         bpf_update_srh_state(skb);
5247
5248                 return err;
5249         case SEG6_LOCAL_ACTION_END_B6_ENCAP:
5250                 if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
5251                         return -EBADMSG;
5252                 err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
5253                                           param, param_len);
5254                 if (!err)
5255                         bpf_update_srh_state(skb);
5256
5257                 return err;
5258         default:
5259                 return -EINVAL;
5260         }
5261 }
5262
5263 static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
5264         .func           = bpf_lwt_seg6_action,
5265         .gpl_only       = false,
5266         .ret_type       = RET_INTEGER,
5267         .arg1_type      = ARG_PTR_TO_CTX,
5268         .arg2_type      = ARG_ANYTHING,
5269         .arg3_type      = ARG_PTR_TO_MEM,
5270         .arg4_type      = ARG_CONST_SIZE
5271 };
5272
5273 BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
5274            s32, len)
5275 {
5276         struct seg6_bpf_srh_state *srh_state =
5277                 this_cpu_ptr(&seg6_bpf_srh_states);
5278         struct ipv6_sr_hdr *srh = srh_state->srh;
5279         void *srh_end, *srh_tlvs, *ptr;
5280         struct ipv6hdr *hdr;
5281         int srhoff = 0;
5282         int ret;
5283
5284         if (unlikely(srh == NULL))
5285                 return -EINVAL;
5286
5287         srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
5288                         ((srh->first_segment + 1) << 4));
5289         srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
5290                         srh_state->hdrlen);
5291         ptr = skb->data + offset;
5292
5293         if (unlikely(ptr < srh_tlvs || ptr > srh_end))
5294                 return -EFAULT;
5295         if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
5296                 return -EFAULT;
5297
5298         if (len > 0) {
5299                 ret = skb_cow_head(skb, len);
5300                 if (unlikely(ret < 0))
5301                         return ret;
5302
5303                 ret = bpf_skb_net_hdr_push(skb, offset, len);
5304         } else {
5305                 ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
5306         }
5307
5308         bpf_compute_data_pointers(skb);
5309         if (unlikely(ret < 0))
5310                 return ret;
5311
5312         hdr = (struct ipv6hdr *)skb->data;
5313         hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
5314
5315         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
5316                 return -EINVAL;
5317         srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5318         srh_state->hdrlen += len;
5319         srh_state->valid = false;
5320         return 0;
5321 }
5322
5323 static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
5324         .func           = bpf_lwt_seg6_adjust_srh,
5325         .gpl_only       = false,
5326         .ret_type       = RET_INTEGER,
5327         .arg1_type      = ARG_PTR_TO_CTX,
5328         .arg2_type      = ARG_ANYTHING,
5329         .arg3_type      = ARG_ANYTHING,
5330 };
5331 #endif /* CONFIG_IPV6_SEG6_BPF */
5332
5333 #ifdef CONFIG_INET
5334 static struct sock *sk_lookup(struct net *net, struct bpf_sock_tuple *tuple,
5335                               int dif, int sdif, u8 family, u8 proto)
5336 {
5337         bool refcounted = false;
5338         struct sock *sk = NULL;
5339
5340         if (family == AF_INET) {
5341                 __be32 src4 = tuple->ipv4.saddr;
5342                 __be32 dst4 = tuple->ipv4.daddr;
5343
5344                 if (proto == IPPROTO_TCP)
5345                         sk = __inet_lookup(net, &tcp_hashinfo, NULL, 0,
5346                                            src4, tuple->ipv4.sport,
5347                                            dst4, tuple->ipv4.dport,
5348                                            dif, sdif, &refcounted);
5349                 else
5350                         sk = __udp4_lib_lookup(net, src4, tuple->ipv4.sport,
5351                                                dst4, tuple->ipv4.dport,
5352                                                dif, sdif, &udp_table, NULL);
5353 #if IS_ENABLED(CONFIG_IPV6)
5354         } else {
5355                 struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr;
5356                 struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr;
5357
5358                 if (proto == IPPROTO_TCP)
5359                         sk = __inet6_lookup(net, &tcp_hashinfo, NULL, 0,
5360                                             src6, tuple->ipv6.sport,
5361                                             dst6, ntohs(tuple->ipv6.dport),
5362                                             dif, sdif, &refcounted);
5363                 else if (likely(ipv6_bpf_stub))
5364                         sk = ipv6_bpf_stub->udp6_lib_lookup(net,
5365                                                             src6, tuple->ipv6.sport,
5366                                                             dst6, tuple->ipv6.dport,
5367                                                             dif, sdif,
5368                                                             &udp_table, NULL);
5369 #endif
5370         }
5371
5372         if (unlikely(sk && !refcounted && !sock_flag(sk, SOCK_RCU_FREE))) {
5373                 WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
5374                 sk = NULL;
5375         }
5376         return sk;
5377 }
5378
5379 /* bpf_skc_lookup performs the core lookup for different types of sockets,
5380  * taking a reference on the socket if it doesn't have the flag SOCK_RCU_FREE.
5381  * Returns the socket as an 'unsigned long' to simplify the casting in the
5382  * callers to satisfy BPF_CALL declarations.
5383  */
5384 static struct sock *
5385 __bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5386                  struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
5387                  u64 flags)
5388 {
5389         struct sock *sk = NULL;
5390         u8 family = AF_UNSPEC;
5391         struct net *net;
5392         int sdif;
5393
5394         if (len == sizeof(tuple->ipv4))
5395                 family = AF_INET;
5396         else if (len == sizeof(tuple->ipv6))
5397                 family = AF_INET6;
5398         else
5399                 return NULL;
5400
5401         if (unlikely(family == AF_UNSPEC || flags ||
5402                      !((s32)netns_id < 0 || netns_id <= S32_MAX)))
5403                 goto out;
5404
5405         if (family == AF_INET)
5406                 sdif = inet_sdif(skb);
5407         else
5408                 sdif = inet6_sdif(skb);
5409
5410         if ((s32)netns_id < 0) {
5411                 net = caller_net;
5412                 sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
5413         } else {
5414                 net = get_net_ns_by_id(caller_net, netns_id);
5415                 if (unlikely(!net))
5416                         goto out;
5417                 sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
5418                 put_net(net);
5419         }
5420
5421 out:
5422         return sk;
5423 }
5424
5425 static struct sock *
5426 __bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5427                 struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
5428                 u64 flags)
5429 {
5430         struct sock *sk = __bpf_skc_lookup(skb, tuple, len, caller_net,
5431                                            ifindex, proto, netns_id, flags);
5432
5433         if (sk) {
5434                 sk = sk_to_full_sk(sk);
5435                 if (!sk_fullsock(sk)) {
5436                         sock_gen_put(sk);
5437                         return NULL;
5438                 }
5439         }
5440
5441         return sk;
5442 }
5443
5444 static struct sock *
5445 bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5446                u8 proto, u64 netns_id, u64 flags)
5447 {
5448         struct net *caller_net;
5449         int ifindex;
5450
5451         if (skb->dev) {
5452                 caller_net = dev_net(skb->dev);
5453                 ifindex = skb->dev->ifindex;
5454         } else {
5455                 caller_net = sock_net(skb->sk);
5456                 ifindex = 0;
5457         }
5458
5459         return __bpf_skc_lookup(skb, tuple, len, caller_net, ifindex, proto,
5460                                 netns_id, flags);
5461 }
5462
5463 static struct sock *
5464 bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5465               u8 proto, u64 netns_id, u64 flags)
5466 {
5467         struct sock *sk = bpf_skc_lookup(skb, tuple, len, proto, netns_id,
5468                                          flags);
5469
5470         if (sk) {
5471                 sk = sk_to_full_sk(sk);
5472                 if (!sk_fullsock(sk)) {
5473                         sock_gen_put(sk);
5474                         return NULL;
5475                 }
5476         }
5477
5478         return sk;
5479 }
5480
5481 BPF_CALL_5(bpf_skc_lookup_tcp, struct sk_buff *, skb,
5482            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5483 {
5484         return (unsigned long)bpf_skc_lookup(skb, tuple, len, IPPROTO_TCP,
5485                                              netns_id, flags);
5486 }
5487
5488 static const struct bpf_func_proto bpf_skc_lookup_tcp_proto = {
5489         .func           = bpf_skc_lookup_tcp,
5490         .gpl_only       = false,
5491         .pkt_access     = true,
5492         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5493         .arg1_type      = ARG_PTR_TO_CTX,
5494         .arg2_type      = ARG_PTR_TO_MEM,
5495         .arg3_type      = ARG_CONST_SIZE,
5496         .arg4_type      = ARG_ANYTHING,
5497         .arg5_type      = ARG_ANYTHING,
5498 };
5499
5500 BPF_CALL_5(bpf_sk_lookup_tcp, struct sk_buff *, skb,
5501            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5502 {
5503         return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_TCP,
5504                                             netns_id, flags);
5505 }
5506
5507 static const struct bpf_func_proto bpf_sk_lookup_tcp_proto = {
5508         .func           = bpf_sk_lookup_tcp,
5509         .gpl_only       = false,
5510         .pkt_access     = true,
5511         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5512         .arg1_type      = ARG_PTR_TO_CTX,
5513         .arg2_type      = ARG_PTR_TO_MEM,
5514         .arg3_type      = ARG_CONST_SIZE,
5515         .arg4_type      = ARG_ANYTHING,
5516         .arg5_type      = ARG_ANYTHING,
5517 };
5518
5519 BPF_CALL_5(bpf_sk_lookup_udp, struct sk_buff *, skb,
5520            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5521 {
5522         return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_UDP,
5523                                             netns_id, flags);
5524 }
5525
5526 static const struct bpf_func_proto bpf_sk_lookup_udp_proto = {
5527         .func           = bpf_sk_lookup_udp,
5528         .gpl_only       = false,
5529         .pkt_access     = true,
5530         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5531         .arg1_type      = ARG_PTR_TO_CTX,
5532         .arg2_type      = ARG_PTR_TO_MEM,
5533         .arg3_type      = ARG_CONST_SIZE,
5534         .arg4_type      = ARG_ANYTHING,
5535         .arg5_type      = ARG_ANYTHING,
5536 };
5537
5538 BPF_CALL_1(bpf_sk_release, struct sock *, sk)
5539 {
5540         if (sk_is_refcounted(sk))
5541                 sock_gen_put(sk);
5542         return 0;
5543 }
5544
5545 static const struct bpf_func_proto bpf_sk_release_proto = {
5546         .func           = bpf_sk_release,
5547         .gpl_only       = false,
5548         .ret_type       = RET_INTEGER,
5549         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5550 };
5551
5552 BPF_CALL_5(bpf_xdp_sk_lookup_udp, struct xdp_buff *, ctx,
5553            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5554 {
5555         struct net *caller_net = dev_net(ctx->rxq->dev);
5556         int ifindex = ctx->rxq->dev->ifindex;
5557
5558         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
5559                                               ifindex, IPPROTO_UDP, netns_id,
5560                                               flags);
5561 }
5562
5563 static const struct bpf_func_proto bpf_xdp_sk_lookup_udp_proto = {
5564         .func           = bpf_xdp_sk_lookup_udp,
5565         .gpl_only       = false,
5566         .pkt_access     = true,
5567         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5568         .arg1_type      = ARG_PTR_TO_CTX,
5569         .arg2_type      = ARG_PTR_TO_MEM,
5570         .arg3_type      = ARG_CONST_SIZE,
5571         .arg4_type      = ARG_ANYTHING,
5572         .arg5_type      = ARG_ANYTHING,
5573 };
5574
5575 BPF_CALL_5(bpf_xdp_skc_lookup_tcp, struct xdp_buff *, ctx,
5576            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5577 {
5578         struct net *caller_net = dev_net(ctx->rxq->dev);
5579         int ifindex = ctx->rxq->dev->ifindex;
5580
5581         return (unsigned long)__bpf_skc_lookup(NULL, tuple, len, caller_net,
5582                                                ifindex, IPPROTO_TCP, netns_id,
5583                                                flags);
5584 }
5585
5586 static const struct bpf_func_proto bpf_xdp_skc_lookup_tcp_proto = {
5587         .func           = bpf_xdp_skc_lookup_tcp,
5588         .gpl_only       = false,
5589         .pkt_access     = true,
5590         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5591         .arg1_type      = ARG_PTR_TO_CTX,
5592         .arg2_type      = ARG_PTR_TO_MEM,
5593         .arg3_type      = ARG_CONST_SIZE,
5594         .arg4_type      = ARG_ANYTHING,
5595         .arg5_type      = ARG_ANYTHING,
5596 };
5597
5598 BPF_CALL_5(bpf_xdp_sk_lookup_tcp, struct xdp_buff *, ctx,
5599            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5600 {
5601         struct net *caller_net = dev_net(ctx->rxq->dev);
5602         int ifindex = ctx->rxq->dev->ifindex;
5603
5604         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
5605                                               ifindex, IPPROTO_TCP, netns_id,
5606                                               flags);
5607 }
5608
5609 static const struct bpf_func_proto bpf_xdp_sk_lookup_tcp_proto = {
5610         .func           = bpf_xdp_sk_lookup_tcp,
5611         .gpl_only       = false,
5612         .pkt_access     = true,
5613         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5614         .arg1_type      = ARG_PTR_TO_CTX,
5615         .arg2_type      = ARG_PTR_TO_MEM,
5616         .arg3_type      = ARG_CONST_SIZE,
5617         .arg4_type      = ARG_ANYTHING,
5618         .arg5_type      = ARG_ANYTHING,
5619 };
5620
5621 BPF_CALL_5(bpf_sock_addr_skc_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
5622            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5623 {
5624         return (unsigned long)__bpf_skc_lookup(NULL, tuple, len,
5625                                                sock_net(ctx->sk), 0,
5626                                                IPPROTO_TCP, netns_id, flags);
5627 }
5628
5629 static const struct bpf_func_proto bpf_sock_addr_skc_lookup_tcp_proto = {
5630         .func           = bpf_sock_addr_skc_lookup_tcp,
5631         .gpl_only       = false,
5632         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5633         .arg1_type      = ARG_PTR_TO_CTX,
5634         .arg2_type      = ARG_PTR_TO_MEM,
5635         .arg3_type      = ARG_CONST_SIZE,
5636         .arg4_type      = ARG_ANYTHING,
5637         .arg5_type      = ARG_ANYTHING,
5638 };
5639
5640 BPF_CALL_5(bpf_sock_addr_sk_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
5641            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5642 {
5643         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
5644                                               sock_net(ctx->sk), 0, IPPROTO_TCP,
5645                                               netns_id, flags);
5646 }
5647
5648 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_tcp_proto = {
5649         .func           = bpf_sock_addr_sk_lookup_tcp,
5650         .gpl_only       = false,
5651         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5652         .arg1_type      = ARG_PTR_TO_CTX,
5653         .arg2_type      = ARG_PTR_TO_MEM,
5654         .arg3_type      = ARG_CONST_SIZE,
5655         .arg4_type      = ARG_ANYTHING,
5656         .arg5_type      = ARG_ANYTHING,
5657 };
5658
5659 BPF_CALL_5(bpf_sock_addr_sk_lookup_udp, struct bpf_sock_addr_kern *, ctx,
5660            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5661 {
5662         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
5663                                               sock_net(ctx->sk), 0, IPPROTO_UDP,
5664                                               netns_id, flags);
5665 }
5666
5667 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_udp_proto = {
5668         .func           = bpf_sock_addr_sk_lookup_udp,
5669         .gpl_only       = false,
5670         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5671         .arg1_type      = ARG_PTR_TO_CTX,
5672         .arg2_type      = ARG_PTR_TO_MEM,
5673         .arg3_type      = ARG_CONST_SIZE,
5674         .arg4_type      = ARG_ANYTHING,
5675         .arg5_type      = ARG_ANYTHING,
5676 };
5677
5678 bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
5679                                   struct bpf_insn_access_aux *info)
5680 {
5681         if (off < 0 || off >= offsetofend(struct bpf_tcp_sock,
5682                                           icsk_retransmits))
5683                 return false;
5684
5685         if (off % size != 0)
5686                 return false;
5687
5688         switch (off) {
5689         case offsetof(struct bpf_tcp_sock, bytes_received):
5690         case offsetof(struct bpf_tcp_sock, bytes_acked):
5691                 return size == sizeof(__u64);
5692         default:
5693                 return size == sizeof(__u32);
5694         }
5695 }
5696
5697 u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
5698                                     const struct bpf_insn *si,
5699                                     struct bpf_insn *insn_buf,
5700                                     struct bpf_prog *prog, u32 *target_size)
5701 {
5702         struct bpf_insn *insn = insn_buf;
5703
5704 #define BPF_TCP_SOCK_GET_COMMON(FIELD)                                  \
5705         do {                                                            \
5706                 BUILD_BUG_ON(sizeof_field(struct tcp_sock, FIELD) >     \
5707                              sizeof_field(struct bpf_tcp_sock, FIELD)); \
5708                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_sock, FIELD),\
5709                                       si->dst_reg, si->src_reg,         \
5710                                       offsetof(struct tcp_sock, FIELD)); \
5711         } while (0)
5712
5713 #define BPF_INET_SOCK_GET_COMMON(FIELD)                                 \
5714         do {                                                            \
5715                 BUILD_BUG_ON(sizeof_field(struct inet_connection_sock,  \
5716                                           FIELD) >                      \
5717                              sizeof_field(struct bpf_tcp_sock, FIELD)); \
5718                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                 \
5719                                         struct inet_connection_sock,    \
5720                                         FIELD),                         \
5721                                       si->dst_reg, si->src_reg,         \
5722                                       offsetof(                         \
5723                                         struct inet_connection_sock,    \
5724                                         FIELD));                        \
5725         } while (0)
5726
5727         if (insn > insn_buf)
5728                 return insn - insn_buf;
5729
5730         switch (si->off) {
5731         case offsetof(struct bpf_tcp_sock, rtt_min):
5732                 BUILD_BUG_ON(sizeof_field(struct tcp_sock, rtt_min) !=
5733                              sizeof(struct minmax));
5734                 BUILD_BUG_ON(sizeof(struct minmax) <
5735                              sizeof(struct minmax_sample));
5736
5737                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5738                                       offsetof(struct tcp_sock, rtt_min) +
5739                                       offsetof(struct minmax_sample, v));
5740                 break;
5741         case offsetof(struct bpf_tcp_sock, snd_cwnd):
5742                 BPF_TCP_SOCK_GET_COMMON(snd_cwnd);
5743                 break;
5744         case offsetof(struct bpf_tcp_sock, srtt_us):
5745                 BPF_TCP_SOCK_GET_COMMON(srtt_us);
5746                 break;
5747         case offsetof(struct bpf_tcp_sock, snd_ssthresh):
5748                 BPF_TCP_SOCK_GET_COMMON(snd_ssthresh);
5749                 break;
5750         case offsetof(struct bpf_tcp_sock, rcv_nxt):
5751                 BPF_TCP_SOCK_GET_COMMON(rcv_nxt);
5752                 break;
5753         case offsetof(struct bpf_tcp_sock, snd_nxt):
5754                 BPF_TCP_SOCK_GET_COMMON(snd_nxt);
5755                 break;
5756         case offsetof(struct bpf_tcp_sock, snd_una):
5757                 BPF_TCP_SOCK_GET_COMMON(snd_una);
5758                 break;
5759         case offsetof(struct bpf_tcp_sock, mss_cache):
5760                 BPF_TCP_SOCK_GET_COMMON(mss_cache);
5761                 break;
5762         case offsetof(struct bpf_tcp_sock, ecn_flags):
5763                 BPF_TCP_SOCK_GET_COMMON(ecn_flags);
5764                 break;
5765         case offsetof(struct bpf_tcp_sock, rate_delivered):
5766                 BPF_TCP_SOCK_GET_COMMON(rate_delivered);
5767                 break;
5768         case offsetof(struct bpf_tcp_sock, rate_interval_us):
5769                 BPF_TCP_SOCK_GET_COMMON(rate_interval_us);
5770                 break;
5771         case offsetof(struct bpf_tcp_sock, packets_out):
5772                 BPF_TCP_SOCK_GET_COMMON(packets_out);
5773                 break;
5774         case offsetof(struct bpf_tcp_sock, retrans_out):
5775                 BPF_TCP_SOCK_GET_COMMON(retrans_out);
5776                 break;
5777         case offsetof(struct bpf_tcp_sock, total_retrans):
5778                 BPF_TCP_SOCK_GET_COMMON(total_retrans);
5779                 break;
5780         case offsetof(struct bpf_tcp_sock, segs_in):
5781                 BPF_TCP_SOCK_GET_COMMON(segs_in);
5782                 break;
5783         case offsetof(struct bpf_tcp_sock, data_segs_in):
5784                 BPF_TCP_SOCK_GET_COMMON(data_segs_in);
5785                 break;
5786         case offsetof(struct bpf_tcp_sock, segs_out):
5787                 BPF_TCP_SOCK_GET_COMMON(segs_out);
5788                 break;
5789         case offsetof(struct bpf_tcp_sock, data_segs_out):
5790                 BPF_TCP_SOCK_GET_COMMON(data_segs_out);
5791                 break;
5792         case offsetof(struct bpf_tcp_sock, lost_out):
5793                 BPF_TCP_SOCK_GET_COMMON(lost_out);
5794                 break;
5795         case offsetof(struct bpf_tcp_sock, sacked_out):
5796                 BPF_TCP_SOCK_GET_COMMON(sacked_out);
5797                 break;
5798         case offsetof(struct bpf_tcp_sock, bytes_received):
5799                 BPF_TCP_SOCK_GET_COMMON(bytes_received);
5800                 break;
5801         case offsetof(struct bpf_tcp_sock, bytes_acked):
5802                 BPF_TCP_SOCK_GET_COMMON(bytes_acked);
5803                 break;
5804         case offsetof(struct bpf_tcp_sock, dsack_dups):
5805                 BPF_TCP_SOCK_GET_COMMON(dsack_dups);
5806                 break;
5807         case offsetof(struct bpf_tcp_sock, delivered):
5808                 BPF_TCP_SOCK_GET_COMMON(delivered);
5809                 break;
5810         case offsetof(struct bpf_tcp_sock, delivered_ce):
5811                 BPF_TCP_SOCK_GET_COMMON(delivered_ce);
5812                 break;
5813         case offsetof(struct bpf_tcp_sock, icsk_retransmits):
5814                 BPF_INET_SOCK_GET_COMMON(icsk_retransmits);
5815                 break;
5816         }
5817
5818         return insn - insn_buf;
5819 }
5820
5821 BPF_CALL_1(bpf_tcp_sock, struct sock *, sk)
5822 {
5823         if (sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP)
5824                 return (unsigned long)sk;
5825
5826         return (unsigned long)NULL;
5827 }
5828
5829 const struct bpf_func_proto bpf_tcp_sock_proto = {
5830         .func           = bpf_tcp_sock,
5831         .gpl_only       = false,
5832         .ret_type       = RET_PTR_TO_TCP_SOCK_OR_NULL,
5833         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5834 };
5835
5836 BPF_CALL_1(bpf_get_listener_sock, struct sock *, sk)
5837 {
5838         sk = sk_to_full_sk(sk);
5839
5840         if (sk->sk_state == TCP_LISTEN && sock_flag(sk, SOCK_RCU_FREE))
5841                 return (unsigned long)sk;
5842
5843         return (unsigned long)NULL;
5844 }
5845
5846 static const struct bpf_func_proto bpf_get_listener_sock_proto = {
5847         .func           = bpf_get_listener_sock,
5848         .gpl_only       = false,
5849         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5850         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5851 };
5852
5853 BPF_CALL_1(bpf_skb_ecn_set_ce, struct sk_buff *, skb)
5854 {
5855         unsigned int iphdr_len;
5856
5857         if (skb->protocol == cpu_to_be16(ETH_P_IP))
5858                 iphdr_len = sizeof(struct iphdr);
5859         else if (skb->protocol == cpu_to_be16(ETH_P_IPV6))
5860                 iphdr_len = sizeof(struct ipv6hdr);
5861         else
5862                 return 0;
5863
5864         if (skb_headlen(skb) < iphdr_len)
5865                 return 0;
5866
5867         if (skb_cloned(skb) && !skb_clone_writable(skb, iphdr_len))
5868                 return 0;
5869
5870         return INET_ECN_set_ce(skb);
5871 }
5872
5873 bool bpf_xdp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
5874                                   struct bpf_insn_access_aux *info)
5875 {
5876         if (off < 0 || off >= offsetofend(struct bpf_xdp_sock, queue_id))
5877                 return false;
5878
5879         if (off % size != 0)
5880                 return false;
5881
5882         switch (off) {
5883         default:
5884                 return size == sizeof(__u32);
5885         }
5886 }
5887
5888 u32 bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,
5889                                     const struct bpf_insn *si,
5890                                     struct bpf_insn *insn_buf,
5891                                     struct bpf_prog *prog, u32 *target_size)
5892 {
5893         struct bpf_insn *insn = insn_buf;
5894
5895 #define BPF_XDP_SOCK_GET(FIELD)                                         \
5896         do {                                                            \
5897                 BUILD_BUG_ON(sizeof_field(struct xdp_sock, FIELD) >     \
5898                              sizeof_field(struct bpf_xdp_sock, FIELD)); \
5899                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_sock, FIELD),\
5900                                       si->dst_reg, si->src_reg,         \
5901                                       offsetof(struct xdp_sock, FIELD)); \
5902         } while (0)
5903
5904         switch (si->off) {
5905         case offsetof(struct bpf_xdp_sock, queue_id):
5906                 BPF_XDP_SOCK_GET(queue_id);
5907                 break;
5908         }
5909
5910         return insn - insn_buf;
5911 }
5912
5913 static const struct bpf_func_proto bpf_skb_ecn_set_ce_proto = {
5914         .func           = bpf_skb_ecn_set_ce,
5915         .gpl_only       = false,
5916         .ret_type       = RET_INTEGER,
5917         .arg1_type      = ARG_PTR_TO_CTX,
5918 };
5919
5920 BPF_CALL_5(bpf_tcp_check_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
5921            struct tcphdr *, th, u32, th_len)
5922 {
5923 #ifdef CONFIG_SYN_COOKIES
5924         u32 cookie;
5925         int ret;
5926
5927         if (unlikely(th_len < sizeof(*th)))
5928                 return -EINVAL;
5929
5930         /* sk_listener() allows TCP_NEW_SYN_RECV, which makes no sense here. */
5931         if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
5932                 return -EINVAL;
5933
5934         if (!sock_net(sk)->ipv4.sysctl_tcp_syncookies)
5935                 return -EINVAL;
5936
5937         if (!th->ack || th->rst || th->syn)
5938                 return -ENOENT;
5939
5940         if (tcp_synq_no_recent_overflow(sk))
5941                 return -ENOENT;
5942
5943         cookie = ntohl(th->ack_seq) - 1;
5944
5945         switch (sk->sk_family) {
5946         case AF_INET:
5947                 if (unlikely(iph_len < sizeof(struct iphdr)))
5948                         return -EINVAL;
5949
5950                 ret = __cookie_v4_check((struct iphdr *)iph, th, cookie);
5951                 break;
5952
5953 #if IS_BUILTIN(CONFIG_IPV6)
5954         case AF_INET6:
5955                 if (unlikely(iph_len < sizeof(struct ipv6hdr)))
5956                         return -EINVAL;
5957
5958                 ret = __cookie_v6_check((struct ipv6hdr *)iph, th, cookie);
5959                 break;
5960 #endif /* CONFIG_IPV6 */
5961
5962         default:
5963                 return -EPROTONOSUPPORT;
5964         }
5965
5966         if (ret > 0)
5967                 return 0;
5968
5969         return -ENOENT;
5970 #else
5971         return -ENOTSUPP;
5972 #endif
5973 }
5974
5975 static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = {
5976         .func           = bpf_tcp_check_syncookie,
5977         .gpl_only       = true,
5978         .pkt_access     = true,
5979         .ret_type       = RET_INTEGER,
5980         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5981         .arg2_type      = ARG_PTR_TO_MEM,
5982         .arg3_type      = ARG_CONST_SIZE,
5983         .arg4_type      = ARG_PTR_TO_MEM,
5984         .arg5_type      = ARG_CONST_SIZE,
5985 };
5986
5987 BPF_CALL_5(bpf_tcp_gen_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
5988            struct tcphdr *, th, u32, th_len)
5989 {
5990 #ifdef CONFIG_SYN_COOKIES
5991         u32 cookie;
5992         u16 mss;
5993
5994         if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
5995                 return -EINVAL;
5996
5997         if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
5998                 return -EINVAL;
5999
6000         if (!sock_net(sk)->ipv4.sysctl_tcp_syncookies)
6001                 return -ENOENT;
6002
6003         if (!th->syn || th->ack || th->fin || th->rst)
6004                 return -EINVAL;
6005
6006         if (unlikely(iph_len < sizeof(struct iphdr)))
6007                 return -EINVAL;
6008
6009         /* Both struct iphdr and struct ipv6hdr have the version field at the
6010          * same offset so we can cast to the shorter header (struct iphdr).
6011          */
6012         switch (((struct iphdr *)iph)->version) {
6013         case 4:
6014                 if (sk->sk_family == AF_INET6 && sk->sk_ipv6only)
6015                         return -EINVAL;
6016
6017                 mss = tcp_v4_get_syncookie(sk, iph, th, &cookie);
6018                 break;
6019
6020 #if IS_BUILTIN(CONFIG_IPV6)
6021         case 6:
6022                 if (unlikely(iph_len < sizeof(struct ipv6hdr)))
6023                         return -EINVAL;
6024
6025                 if (sk->sk_family != AF_INET6)
6026                         return -EINVAL;
6027
6028                 mss = tcp_v6_get_syncookie(sk, iph, th, &cookie);
6029                 break;
6030 #endif /* CONFIG_IPV6 */
6031
6032         default:
6033                 return -EPROTONOSUPPORT;
6034         }
6035         if (mss == 0)
6036                 return -ENOENT;
6037
6038         return cookie | ((u64)mss << 32);
6039 #else
6040         return -EOPNOTSUPP;
6041 #endif /* CONFIG_SYN_COOKIES */
6042 }
6043
6044 static const struct bpf_func_proto bpf_tcp_gen_syncookie_proto = {
6045         .func           = bpf_tcp_gen_syncookie,
6046         .gpl_only       = true, /* __cookie_v*_init_sequence() is GPL */
6047         .pkt_access     = true,
6048         .ret_type       = RET_INTEGER,
6049         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
6050         .arg2_type      = ARG_PTR_TO_MEM,
6051         .arg3_type      = ARG_CONST_SIZE,
6052         .arg4_type      = ARG_PTR_TO_MEM,
6053         .arg5_type      = ARG_CONST_SIZE,
6054 };
6055
6056 BPF_CALL_3(bpf_sk_assign, struct sk_buff *, skb, struct sock *, sk, u64, flags)
6057 {
6058         if (flags != 0)
6059                 return -EINVAL;
6060         if (!skb_at_tc_ingress(skb))
6061                 return -EOPNOTSUPP;
6062         if (unlikely(dev_net(skb->dev) != sock_net(sk)))
6063                 return -ENETUNREACH;
6064         if (unlikely(sk_fullsock(sk) && sk->sk_reuseport))
6065                 return -ESOCKTNOSUPPORT;
6066         if (sk_is_refcounted(sk) &&
6067             unlikely(!refcount_inc_not_zero(&sk->sk_refcnt)))
6068                 return -ENOENT;
6069
6070         skb_orphan(skb);
6071         skb->sk = sk;
6072         skb->destructor = sock_pfree;
6073
6074         return 0;
6075 }
6076
6077 static const struct bpf_func_proto bpf_sk_assign_proto = {
6078         .func           = bpf_sk_assign,
6079         .gpl_only       = false,
6080         .ret_type       = RET_INTEGER,
6081         .arg1_type      = ARG_PTR_TO_CTX,
6082         .arg2_type      = ARG_PTR_TO_SOCK_COMMON,
6083         .arg3_type      = ARG_ANYTHING,
6084 };
6085
6086 #endif /* CONFIG_INET */
6087
6088 bool bpf_helper_changes_pkt_data(void *func)
6089 {
6090         if (func == bpf_skb_vlan_push ||
6091             func == bpf_skb_vlan_pop ||
6092             func == bpf_skb_store_bytes ||
6093             func == bpf_skb_change_proto ||
6094             func == bpf_skb_change_head ||
6095             func == sk_skb_change_head ||
6096             func == bpf_skb_change_tail ||
6097             func == sk_skb_change_tail ||
6098             func == bpf_skb_adjust_room ||
6099             func == bpf_skb_pull_data ||
6100             func == sk_skb_pull_data ||
6101             func == bpf_clone_redirect ||
6102             func == bpf_l3_csum_replace ||
6103             func == bpf_l4_csum_replace ||
6104             func == bpf_xdp_adjust_head ||
6105             func == bpf_xdp_adjust_meta ||
6106             func == bpf_msg_pull_data ||
6107             func == bpf_msg_push_data ||
6108             func == bpf_msg_pop_data ||
6109             func == bpf_xdp_adjust_tail ||
6110 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6111             func == bpf_lwt_seg6_store_bytes ||
6112             func == bpf_lwt_seg6_adjust_srh ||
6113             func == bpf_lwt_seg6_action ||
6114 #endif
6115             func == bpf_lwt_in_push_encap ||
6116             func == bpf_lwt_xmit_push_encap)
6117                 return true;
6118
6119         return false;
6120 }
6121
6122 const struct bpf_func_proto bpf_event_output_data_proto __weak;
6123
6124 static const struct bpf_func_proto *
6125 sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6126 {
6127         switch (func_id) {
6128         /* inet and inet6 sockets are created in a process
6129          * context so there is always a valid uid/gid
6130          */
6131         case BPF_FUNC_get_current_uid_gid:
6132                 return &bpf_get_current_uid_gid_proto;
6133         case BPF_FUNC_get_local_storage:
6134                 return &bpf_get_local_storage_proto;
6135         case BPF_FUNC_get_socket_cookie:
6136                 return &bpf_get_socket_cookie_sock_proto;
6137         case BPF_FUNC_get_netns_cookie:
6138                 return &bpf_get_netns_cookie_sock_proto;
6139         case BPF_FUNC_perf_event_output:
6140                 return &bpf_event_output_data_proto;
6141         case BPF_FUNC_get_current_pid_tgid:
6142                 return &bpf_get_current_pid_tgid_proto;
6143         case BPF_FUNC_get_current_comm:
6144                 return &bpf_get_current_comm_proto;
6145 #ifdef CONFIG_CGROUPS
6146         case BPF_FUNC_get_current_cgroup_id:
6147                 return &bpf_get_current_cgroup_id_proto;
6148         case BPF_FUNC_get_current_ancestor_cgroup_id:
6149                 return &bpf_get_current_ancestor_cgroup_id_proto;
6150 #endif
6151 #ifdef CONFIG_CGROUP_NET_CLASSID
6152         case BPF_FUNC_get_cgroup_classid:
6153                 return &bpf_get_cgroup_classid_curr_proto;
6154 #endif
6155         default:
6156                 return bpf_base_func_proto(func_id);
6157         }
6158 }
6159
6160 static const struct bpf_func_proto *
6161 sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6162 {
6163         switch (func_id) {
6164         /* inet and inet6 sockets are created in a process
6165          * context so there is always a valid uid/gid
6166          */
6167         case BPF_FUNC_get_current_uid_gid:
6168                 return &bpf_get_current_uid_gid_proto;
6169         case BPF_FUNC_bind:
6170                 switch (prog->expected_attach_type) {
6171                 case BPF_CGROUP_INET4_CONNECT:
6172                 case BPF_CGROUP_INET6_CONNECT:
6173                         return &bpf_bind_proto;
6174                 default:
6175                         return NULL;
6176                 }
6177         case BPF_FUNC_get_socket_cookie:
6178                 return &bpf_get_socket_cookie_sock_addr_proto;
6179         case BPF_FUNC_get_netns_cookie:
6180                 return &bpf_get_netns_cookie_sock_addr_proto;
6181         case BPF_FUNC_get_local_storage:
6182                 return &bpf_get_local_storage_proto;
6183         case BPF_FUNC_perf_event_output:
6184                 return &bpf_event_output_data_proto;
6185         case BPF_FUNC_get_current_pid_tgid:
6186                 return &bpf_get_current_pid_tgid_proto;
6187         case BPF_FUNC_get_current_comm:
6188                 return &bpf_get_current_comm_proto;
6189 #ifdef CONFIG_CGROUPS
6190         case BPF_FUNC_get_current_cgroup_id:
6191                 return &bpf_get_current_cgroup_id_proto;
6192         case BPF_FUNC_get_current_ancestor_cgroup_id:
6193                 return &bpf_get_current_ancestor_cgroup_id_proto;
6194 #endif
6195 #ifdef CONFIG_CGROUP_NET_CLASSID
6196         case BPF_FUNC_get_cgroup_classid:
6197                 return &bpf_get_cgroup_classid_curr_proto;
6198 #endif
6199 #ifdef CONFIG_INET
6200         case BPF_FUNC_sk_lookup_tcp:
6201                 return &bpf_sock_addr_sk_lookup_tcp_proto;
6202         case BPF_FUNC_sk_lookup_udp:
6203                 return &bpf_sock_addr_sk_lookup_udp_proto;
6204         case BPF_FUNC_sk_release:
6205                 return &bpf_sk_release_proto;
6206         case BPF_FUNC_skc_lookup_tcp:
6207                 return &bpf_sock_addr_skc_lookup_tcp_proto;
6208 #endif /* CONFIG_INET */
6209         case BPF_FUNC_sk_storage_get:
6210                 return &bpf_sk_storage_get_proto;
6211         case BPF_FUNC_sk_storage_delete:
6212                 return &bpf_sk_storage_delete_proto;
6213         case BPF_FUNC_setsockopt:
6214                 switch (prog->expected_attach_type) {
6215                 case BPF_CGROUP_INET4_CONNECT:
6216                 case BPF_CGROUP_INET6_CONNECT:
6217                         return &bpf_sock_addr_setsockopt_proto;
6218                 default:
6219                         return NULL;
6220                 }
6221         case BPF_FUNC_getsockopt:
6222                 switch (prog->expected_attach_type) {
6223                 case BPF_CGROUP_INET4_CONNECT:
6224                 case BPF_CGROUP_INET6_CONNECT:
6225                         return &bpf_sock_addr_getsockopt_proto;
6226                 default:
6227                         return NULL;
6228                 }
6229         default:
6230                 return bpf_base_func_proto(func_id);
6231         }
6232 }
6233
6234 static const struct bpf_func_proto *
6235 sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6236 {
6237         switch (func_id) {
6238         case BPF_FUNC_skb_load_bytes:
6239                 return &bpf_skb_load_bytes_proto;
6240         case BPF_FUNC_skb_load_bytes_relative:
6241                 return &bpf_skb_load_bytes_relative_proto;
6242         case BPF_FUNC_get_socket_cookie:
6243                 return &bpf_get_socket_cookie_proto;
6244         case BPF_FUNC_get_socket_uid:
6245                 return &bpf_get_socket_uid_proto;
6246         case BPF_FUNC_perf_event_output:
6247                 return &bpf_skb_event_output_proto;
6248         default:
6249                 return bpf_base_func_proto(func_id);
6250         }
6251 }
6252
6253 const struct bpf_func_proto bpf_sk_storage_get_proto __weak;
6254 const struct bpf_func_proto bpf_sk_storage_delete_proto __weak;
6255
6256 static const struct bpf_func_proto *
6257 cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6258 {
6259         switch (func_id) {
6260         case BPF_FUNC_get_local_storage:
6261                 return &bpf_get_local_storage_proto;
6262         case BPF_FUNC_sk_fullsock:
6263                 return &bpf_sk_fullsock_proto;
6264         case BPF_FUNC_sk_storage_get:
6265                 return &bpf_sk_storage_get_proto;
6266         case BPF_FUNC_sk_storage_delete:
6267                 return &bpf_sk_storage_delete_proto;
6268         case BPF_FUNC_perf_event_output:
6269                 return &bpf_skb_event_output_proto;
6270 #ifdef CONFIG_SOCK_CGROUP_DATA
6271         case BPF_FUNC_skb_cgroup_id:
6272                 return &bpf_skb_cgroup_id_proto;
6273         case BPF_FUNC_skb_ancestor_cgroup_id:
6274                 return &bpf_skb_ancestor_cgroup_id_proto;
6275         case BPF_FUNC_sk_cgroup_id:
6276                 return &bpf_sk_cgroup_id_proto;
6277         case BPF_FUNC_sk_ancestor_cgroup_id:
6278                 return &bpf_sk_ancestor_cgroup_id_proto;
6279 #endif
6280 #ifdef CONFIG_INET
6281         case BPF_FUNC_sk_lookup_tcp:
6282                 return &bpf_sk_lookup_tcp_proto;
6283         case BPF_FUNC_sk_lookup_udp:
6284                 return &bpf_sk_lookup_udp_proto;
6285         case BPF_FUNC_sk_release:
6286                 return &bpf_sk_release_proto;
6287         case BPF_FUNC_skc_lookup_tcp:
6288                 return &bpf_skc_lookup_tcp_proto;
6289         case BPF_FUNC_tcp_sock:
6290                 return &bpf_tcp_sock_proto;
6291         case BPF_FUNC_get_listener_sock:
6292                 return &bpf_get_listener_sock_proto;
6293         case BPF_FUNC_skb_ecn_set_ce:
6294                 return &bpf_skb_ecn_set_ce_proto;
6295 #endif
6296         default:
6297                 return sk_filter_func_proto(func_id, prog);
6298         }
6299 }
6300
6301 static const struct bpf_func_proto *
6302 tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6303 {
6304         switch (func_id) {
6305         case BPF_FUNC_skb_store_bytes:
6306                 return &bpf_skb_store_bytes_proto;
6307         case BPF_FUNC_skb_load_bytes:
6308                 return &bpf_skb_load_bytes_proto;
6309         case BPF_FUNC_skb_load_bytes_relative:
6310                 return &bpf_skb_load_bytes_relative_proto;
6311         case BPF_FUNC_skb_pull_data:
6312                 return &bpf_skb_pull_data_proto;
6313         case BPF_FUNC_csum_diff:
6314                 return &bpf_csum_diff_proto;
6315         case BPF_FUNC_csum_update:
6316                 return &bpf_csum_update_proto;
6317         case BPF_FUNC_csum_level:
6318                 return &bpf_csum_level_proto;
6319         case BPF_FUNC_l3_csum_replace:
6320                 return &bpf_l3_csum_replace_proto;
6321         case BPF_FUNC_l4_csum_replace:
6322                 return &bpf_l4_csum_replace_proto;
6323         case BPF_FUNC_clone_redirect:
6324                 return &bpf_clone_redirect_proto;
6325         case BPF_FUNC_get_cgroup_classid:
6326                 return &bpf_get_cgroup_classid_proto;
6327         case BPF_FUNC_skb_vlan_push:
6328                 return &bpf_skb_vlan_push_proto;
6329         case BPF_FUNC_skb_vlan_pop:
6330                 return &bpf_skb_vlan_pop_proto;
6331         case BPF_FUNC_skb_change_proto:
6332                 return &bpf_skb_change_proto_proto;
6333         case BPF_FUNC_skb_change_type:
6334                 return &bpf_skb_change_type_proto;
6335         case BPF_FUNC_skb_adjust_room:
6336                 return &bpf_skb_adjust_room_proto;
6337         case BPF_FUNC_skb_change_tail:
6338                 return &bpf_skb_change_tail_proto;
6339         case BPF_FUNC_skb_change_head:
6340                 return &bpf_skb_change_head_proto;
6341         case BPF_FUNC_skb_get_tunnel_key:
6342                 return &bpf_skb_get_tunnel_key_proto;
6343         case BPF_FUNC_skb_set_tunnel_key:
6344                 return bpf_get_skb_set_tunnel_proto(func_id);
6345         case BPF_FUNC_skb_get_tunnel_opt:
6346                 return &bpf_skb_get_tunnel_opt_proto;
6347         case BPF_FUNC_skb_set_tunnel_opt:
6348                 return bpf_get_skb_set_tunnel_proto(func_id);
6349         case BPF_FUNC_redirect:
6350                 return &bpf_redirect_proto;
6351         case BPF_FUNC_get_route_realm:
6352                 return &bpf_get_route_realm_proto;
6353         case BPF_FUNC_get_hash_recalc:
6354                 return &bpf_get_hash_recalc_proto;
6355         case BPF_FUNC_set_hash_invalid:
6356                 return &bpf_set_hash_invalid_proto;
6357         case BPF_FUNC_set_hash:
6358                 return &bpf_set_hash_proto;
6359         case BPF_FUNC_perf_event_output:
6360                 return &bpf_skb_event_output_proto;
6361         case BPF_FUNC_get_smp_processor_id:
6362                 return &bpf_get_smp_processor_id_proto;
6363         case BPF_FUNC_skb_under_cgroup:
6364                 return &bpf_skb_under_cgroup_proto;
6365         case BPF_FUNC_get_socket_cookie:
6366                 return &bpf_get_socket_cookie_proto;
6367         case BPF_FUNC_get_socket_uid:
6368                 return &bpf_get_socket_uid_proto;
6369         case BPF_FUNC_fib_lookup:
6370                 return &bpf_skb_fib_lookup_proto;
6371         case BPF_FUNC_sk_fullsock:
6372                 return &bpf_sk_fullsock_proto;
6373         case BPF_FUNC_sk_storage_get:
6374                 return &bpf_sk_storage_get_proto;
6375         case BPF_FUNC_sk_storage_delete:
6376                 return &bpf_sk_storage_delete_proto;
6377 #ifdef CONFIG_XFRM
6378         case BPF_FUNC_skb_get_xfrm_state:
6379                 return &bpf_skb_get_xfrm_state_proto;
6380 #endif
6381 #ifdef CONFIG_SOCK_CGROUP_DATA
6382         case BPF_FUNC_skb_cgroup_id:
6383                 return &bpf_skb_cgroup_id_proto;
6384         case BPF_FUNC_skb_ancestor_cgroup_id:
6385                 return &bpf_skb_ancestor_cgroup_id_proto;
6386 #endif
6387 #ifdef CONFIG_INET
6388         case BPF_FUNC_sk_lookup_tcp:
6389                 return &bpf_sk_lookup_tcp_proto;
6390         case BPF_FUNC_sk_lookup_udp:
6391                 return &bpf_sk_lookup_udp_proto;
6392         case BPF_FUNC_sk_release:
6393                 return &bpf_sk_release_proto;
6394         case BPF_FUNC_tcp_sock:
6395                 return &bpf_tcp_sock_proto;
6396         case BPF_FUNC_get_listener_sock:
6397                 return &bpf_get_listener_sock_proto;
6398         case BPF_FUNC_skc_lookup_tcp:
6399                 return &bpf_skc_lookup_tcp_proto;
6400         case BPF_FUNC_tcp_check_syncookie:
6401                 return &bpf_tcp_check_syncookie_proto;
6402         case BPF_FUNC_skb_ecn_set_ce:
6403                 return &bpf_skb_ecn_set_ce_proto;
6404         case BPF_FUNC_tcp_gen_syncookie:
6405                 return &bpf_tcp_gen_syncookie_proto;
6406         case BPF_FUNC_sk_assign:
6407                 return &bpf_sk_assign_proto;
6408 #endif
6409         default:
6410                 return bpf_base_func_proto(func_id);
6411         }
6412 }
6413
6414 static const struct bpf_func_proto *
6415 xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6416 {
6417         switch (func_id) {
6418         case BPF_FUNC_perf_event_output:
6419                 return &bpf_xdp_event_output_proto;
6420         case BPF_FUNC_get_smp_processor_id:
6421                 return &bpf_get_smp_processor_id_proto;
6422         case BPF_FUNC_csum_diff:
6423                 return &bpf_csum_diff_proto;
6424         case BPF_FUNC_xdp_adjust_head:
6425                 return &bpf_xdp_adjust_head_proto;
6426         case BPF_FUNC_xdp_adjust_meta:
6427                 return &bpf_xdp_adjust_meta_proto;
6428         case BPF_FUNC_redirect:
6429                 return &bpf_xdp_redirect_proto;
6430         case BPF_FUNC_redirect_map:
6431                 return &bpf_xdp_redirect_map_proto;
6432         case BPF_FUNC_xdp_adjust_tail:
6433                 return &bpf_xdp_adjust_tail_proto;
6434         case BPF_FUNC_fib_lookup:
6435                 return &bpf_xdp_fib_lookup_proto;
6436 #ifdef CONFIG_INET
6437         case BPF_FUNC_sk_lookup_udp:
6438                 return &bpf_xdp_sk_lookup_udp_proto;
6439         case BPF_FUNC_sk_lookup_tcp:
6440                 return &bpf_xdp_sk_lookup_tcp_proto;
6441         case BPF_FUNC_sk_release:
6442                 return &bpf_sk_release_proto;
6443         case BPF_FUNC_skc_lookup_tcp:
6444                 return &bpf_xdp_skc_lookup_tcp_proto;
6445         case BPF_FUNC_tcp_check_syncookie:
6446                 return &bpf_tcp_check_syncookie_proto;
6447         case BPF_FUNC_tcp_gen_syncookie:
6448                 return &bpf_tcp_gen_syncookie_proto;
6449 #endif
6450         default:
6451                 return bpf_base_func_proto(func_id);
6452         }
6453 }
6454
6455 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
6456 const struct bpf_func_proto bpf_sock_hash_update_proto __weak;
6457
6458 static const struct bpf_func_proto *
6459 sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6460 {
6461         switch (func_id) {
6462         case BPF_FUNC_setsockopt:
6463                 return &bpf_sock_ops_setsockopt_proto;
6464         case BPF_FUNC_getsockopt:
6465                 return &bpf_sock_ops_getsockopt_proto;
6466         case BPF_FUNC_sock_ops_cb_flags_set:
6467                 return &bpf_sock_ops_cb_flags_set_proto;
6468         case BPF_FUNC_sock_map_update:
6469                 return &bpf_sock_map_update_proto;
6470         case BPF_FUNC_sock_hash_update:
6471                 return &bpf_sock_hash_update_proto;
6472         case BPF_FUNC_get_socket_cookie:
6473                 return &bpf_get_socket_cookie_sock_ops_proto;
6474         case BPF_FUNC_get_local_storage:
6475                 return &bpf_get_local_storage_proto;
6476         case BPF_FUNC_perf_event_output:
6477                 return &bpf_event_output_data_proto;
6478         case BPF_FUNC_sk_storage_get:
6479                 return &bpf_sk_storage_get_proto;
6480         case BPF_FUNC_sk_storage_delete:
6481                 return &bpf_sk_storage_delete_proto;
6482 #ifdef CONFIG_INET
6483         case BPF_FUNC_tcp_sock:
6484                 return &bpf_tcp_sock_proto;
6485 #endif /* CONFIG_INET */
6486         default:
6487                 return bpf_base_func_proto(func_id);
6488         }
6489 }
6490
6491 const struct bpf_func_proto bpf_msg_redirect_map_proto __weak;
6492 const struct bpf_func_proto bpf_msg_redirect_hash_proto __weak;
6493
6494 static const struct bpf_func_proto *
6495 sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6496 {
6497         switch (func_id) {
6498         case BPF_FUNC_msg_redirect_map:
6499                 return &bpf_msg_redirect_map_proto;
6500         case BPF_FUNC_msg_redirect_hash:
6501                 return &bpf_msg_redirect_hash_proto;
6502         case BPF_FUNC_msg_apply_bytes:
6503                 return &bpf_msg_apply_bytes_proto;
6504         case BPF_FUNC_msg_cork_bytes:
6505                 return &bpf_msg_cork_bytes_proto;
6506         case BPF_FUNC_msg_pull_data:
6507                 return &bpf_msg_pull_data_proto;
6508         case BPF_FUNC_msg_push_data:
6509                 return &bpf_msg_push_data_proto;
6510         case BPF_FUNC_msg_pop_data:
6511                 return &bpf_msg_pop_data_proto;
6512         case BPF_FUNC_perf_event_output:
6513                 return &bpf_event_output_data_proto;
6514         case BPF_FUNC_get_current_uid_gid:
6515                 return &bpf_get_current_uid_gid_proto;
6516         case BPF_FUNC_get_current_pid_tgid:
6517                 return &bpf_get_current_pid_tgid_proto;
6518         case BPF_FUNC_sk_storage_get:
6519                 return &bpf_sk_storage_get_proto;
6520         case BPF_FUNC_sk_storage_delete:
6521                 return &bpf_sk_storage_delete_proto;
6522 #ifdef CONFIG_CGROUPS
6523         case BPF_FUNC_get_current_cgroup_id:
6524                 return &bpf_get_current_cgroup_id_proto;
6525         case BPF_FUNC_get_current_ancestor_cgroup_id:
6526                 return &bpf_get_current_ancestor_cgroup_id_proto;
6527 #endif
6528 #ifdef CONFIG_CGROUP_NET_CLASSID
6529         case BPF_FUNC_get_cgroup_classid:
6530                 return &bpf_get_cgroup_classid_curr_proto;
6531 #endif
6532         default:
6533                 return bpf_base_func_proto(func_id);
6534         }
6535 }
6536
6537 const struct bpf_func_proto bpf_sk_redirect_map_proto __weak;
6538 const struct bpf_func_proto bpf_sk_redirect_hash_proto __weak;
6539
6540 static const struct bpf_func_proto *
6541 sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6542 {
6543         switch (func_id) {
6544         case BPF_FUNC_skb_store_bytes:
6545                 return &bpf_skb_store_bytes_proto;
6546         case BPF_FUNC_skb_load_bytes:
6547                 return &bpf_skb_load_bytes_proto;
6548         case BPF_FUNC_skb_pull_data:
6549                 return &sk_skb_pull_data_proto;
6550         case BPF_FUNC_skb_change_tail:
6551                 return &sk_skb_change_tail_proto;
6552         case BPF_FUNC_skb_change_head:
6553                 return &sk_skb_change_head_proto;
6554         case BPF_FUNC_get_socket_cookie:
6555                 return &bpf_get_socket_cookie_proto;
6556         case BPF_FUNC_get_socket_uid:
6557                 return &bpf_get_socket_uid_proto;
6558         case BPF_FUNC_sk_redirect_map:
6559                 return &bpf_sk_redirect_map_proto;
6560         case BPF_FUNC_sk_redirect_hash:
6561                 return &bpf_sk_redirect_hash_proto;
6562         case BPF_FUNC_perf_event_output:
6563                 return &bpf_skb_event_output_proto;
6564 #ifdef CONFIG_INET
6565         case BPF_FUNC_sk_lookup_tcp:
6566                 return &bpf_sk_lookup_tcp_proto;
6567         case BPF_FUNC_sk_lookup_udp:
6568                 return &bpf_sk_lookup_udp_proto;
6569         case BPF_FUNC_sk_release:
6570                 return &bpf_sk_release_proto;
6571         case BPF_FUNC_skc_lookup_tcp:
6572                 return &bpf_skc_lookup_tcp_proto;
6573 #endif
6574         default:
6575                 return bpf_base_func_proto(func_id);
6576         }
6577 }
6578
6579 static const struct bpf_func_proto *
6580 flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6581 {
6582         switch (func_id) {
6583         case BPF_FUNC_skb_load_bytes:
6584                 return &bpf_flow_dissector_load_bytes_proto;
6585         default:
6586                 return bpf_base_func_proto(func_id);
6587         }
6588 }
6589
6590 static const struct bpf_func_proto *
6591 lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6592 {
6593         switch (func_id) {
6594         case BPF_FUNC_skb_load_bytes:
6595                 return &bpf_skb_load_bytes_proto;
6596         case BPF_FUNC_skb_pull_data:
6597                 return &bpf_skb_pull_data_proto;
6598         case BPF_FUNC_csum_diff:
6599                 return &bpf_csum_diff_proto;
6600         case BPF_FUNC_get_cgroup_classid:
6601                 return &bpf_get_cgroup_classid_proto;
6602         case BPF_FUNC_get_route_realm:
6603                 return &bpf_get_route_realm_proto;
6604         case BPF_FUNC_get_hash_recalc:
6605                 return &bpf_get_hash_recalc_proto;
6606         case BPF_FUNC_perf_event_output:
6607                 return &bpf_skb_event_output_proto;
6608         case BPF_FUNC_get_smp_processor_id:
6609                 return &bpf_get_smp_processor_id_proto;
6610         case BPF_FUNC_skb_under_cgroup:
6611                 return &bpf_skb_under_cgroup_proto;
6612         default:
6613                 return bpf_base_func_proto(func_id);
6614         }
6615 }
6616
6617 static const struct bpf_func_proto *
6618 lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6619 {
6620         switch (func_id) {
6621         case BPF_FUNC_lwt_push_encap:
6622                 return &bpf_lwt_in_push_encap_proto;
6623         default:
6624                 return lwt_out_func_proto(func_id, prog);
6625         }
6626 }
6627
6628 static const struct bpf_func_proto *
6629 lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6630 {
6631         switch (func_id) {
6632         case BPF_FUNC_skb_get_tunnel_key:
6633                 return &bpf_skb_get_tunnel_key_proto;
6634         case BPF_FUNC_skb_set_tunnel_key:
6635                 return bpf_get_skb_set_tunnel_proto(func_id);
6636         case BPF_FUNC_skb_get_tunnel_opt:
6637                 return &bpf_skb_get_tunnel_opt_proto;
6638         case BPF_FUNC_skb_set_tunnel_opt:
6639                 return bpf_get_skb_set_tunnel_proto(func_id);
6640         case BPF_FUNC_redirect:
6641                 return &bpf_redirect_proto;
6642         case BPF_FUNC_clone_redirect:
6643                 return &bpf_clone_redirect_proto;
6644         case BPF_FUNC_skb_change_tail:
6645                 return &bpf_skb_change_tail_proto;
6646         case BPF_FUNC_skb_change_head:
6647                 return &bpf_skb_change_head_proto;
6648         case BPF_FUNC_skb_store_bytes:
6649                 return &bpf_skb_store_bytes_proto;
6650         case BPF_FUNC_csum_update:
6651                 return &bpf_csum_update_proto;
6652         case BPF_FUNC_csum_level:
6653                 return &bpf_csum_level_proto;
6654         case BPF_FUNC_l3_csum_replace:
6655                 return &bpf_l3_csum_replace_proto;
6656         case BPF_FUNC_l4_csum_replace:
6657                 return &bpf_l4_csum_replace_proto;
6658         case BPF_FUNC_set_hash_invalid:
6659                 return &bpf_set_hash_invalid_proto;
6660         case BPF_FUNC_lwt_push_encap:
6661                 return &bpf_lwt_xmit_push_encap_proto;
6662         default:
6663                 return lwt_out_func_proto(func_id, prog);
6664         }
6665 }
6666
6667 static const struct bpf_func_proto *
6668 lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6669 {
6670         switch (func_id) {
6671 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6672         case BPF_FUNC_lwt_seg6_store_bytes:
6673                 return &bpf_lwt_seg6_store_bytes_proto;
6674         case BPF_FUNC_lwt_seg6_action:
6675                 return &bpf_lwt_seg6_action_proto;
6676         case BPF_FUNC_lwt_seg6_adjust_srh:
6677                 return &bpf_lwt_seg6_adjust_srh_proto;
6678 #endif
6679         default:
6680                 return lwt_out_func_proto(func_id, prog);
6681         }
6682 }
6683
6684 static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
6685                                     const struct bpf_prog *prog,
6686                                     struct bpf_insn_access_aux *info)
6687 {
6688         const int size_default = sizeof(__u32);
6689
6690         if (off < 0 || off >= sizeof(struct __sk_buff))
6691                 return false;
6692
6693         /* The verifier guarantees that size > 0. */
6694         if (off % size != 0)
6695                 return false;
6696
6697         switch (off) {
6698         case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6699                 if (off + size > offsetofend(struct __sk_buff, cb[4]))
6700                         return false;
6701                 break;
6702         case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
6703         case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
6704         case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
6705         case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
6706         case bpf_ctx_range(struct __sk_buff, data):
6707         case bpf_ctx_range(struct __sk_buff, data_meta):
6708         case bpf_ctx_range(struct __sk_buff, data_end):
6709                 if (size != size_default)
6710                         return false;
6711                 break;
6712         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6713                 return false;
6714         case bpf_ctx_range(struct __sk_buff, tstamp):
6715                 if (size != sizeof(__u64))
6716                         return false;
6717                 break;
6718         case offsetof(struct __sk_buff, sk):
6719                 if (type == BPF_WRITE || size != sizeof(__u64))
6720                         return false;
6721                 info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
6722                 break;
6723         default:
6724                 /* Only narrow read access allowed for now. */
6725                 if (type == BPF_WRITE) {
6726                         if (size != size_default)
6727                                 return false;
6728                 } else {
6729                         bpf_ctx_record_field_size(info, size_default);
6730                         if (!bpf_ctx_narrow_access_ok(off, size, size_default))
6731                                 return false;
6732                 }
6733         }
6734
6735         return true;
6736 }
6737
6738 static bool sk_filter_is_valid_access(int off, int size,
6739                                       enum bpf_access_type type,
6740                                       const struct bpf_prog *prog,
6741                                       struct bpf_insn_access_aux *info)
6742 {
6743         switch (off) {
6744         case bpf_ctx_range(struct __sk_buff, tc_classid):
6745         case bpf_ctx_range(struct __sk_buff, data):
6746         case bpf_ctx_range(struct __sk_buff, data_meta):
6747         case bpf_ctx_range(struct __sk_buff, data_end):
6748         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6749         case bpf_ctx_range(struct __sk_buff, tstamp):
6750         case bpf_ctx_range(struct __sk_buff, wire_len):
6751                 return false;
6752         }
6753
6754         if (type == BPF_WRITE) {
6755                 switch (off) {
6756                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6757                         break;
6758                 default:
6759                         return false;
6760                 }
6761         }
6762
6763         return bpf_skb_is_valid_access(off, size, type, prog, info);
6764 }
6765
6766 static bool cg_skb_is_valid_access(int off, int size,
6767                                    enum bpf_access_type type,
6768                                    const struct bpf_prog *prog,
6769                                    struct bpf_insn_access_aux *info)
6770 {
6771         switch (off) {
6772         case bpf_ctx_range(struct __sk_buff, tc_classid):
6773         case bpf_ctx_range(struct __sk_buff, data_meta):
6774         case bpf_ctx_range(struct __sk_buff, wire_len):
6775                 return false;
6776         case bpf_ctx_range(struct __sk_buff, data):
6777         case bpf_ctx_range(struct __sk_buff, data_end):
6778                 if (!bpf_capable())
6779                         return false;
6780                 break;
6781         }
6782
6783         if (type == BPF_WRITE) {
6784                 switch (off) {
6785                 case bpf_ctx_range(struct __sk_buff, mark):
6786                 case bpf_ctx_range(struct __sk_buff, priority):
6787                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6788                         break;
6789                 case bpf_ctx_range(struct __sk_buff, tstamp):
6790                         if (!bpf_capable())
6791                                 return false;
6792                         break;
6793                 default:
6794                         return false;
6795                 }
6796         }
6797
6798         switch (off) {
6799         case bpf_ctx_range(struct __sk_buff, data):
6800                 info->reg_type = PTR_TO_PACKET;
6801                 break;
6802         case bpf_ctx_range(struct __sk_buff, data_end):
6803                 info->reg_type = PTR_TO_PACKET_END;
6804                 break;
6805         }
6806
6807         return bpf_skb_is_valid_access(off, size, type, prog, info);
6808 }
6809
6810 static bool lwt_is_valid_access(int off, int size,
6811                                 enum bpf_access_type type,
6812                                 const struct bpf_prog *prog,
6813                                 struct bpf_insn_access_aux *info)
6814 {
6815         switch (off) {
6816         case bpf_ctx_range(struct __sk_buff, tc_classid):
6817         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6818         case bpf_ctx_range(struct __sk_buff, data_meta):
6819         case bpf_ctx_range(struct __sk_buff, tstamp):
6820         case bpf_ctx_range(struct __sk_buff, wire_len):
6821                 return false;
6822         }
6823
6824         if (type == BPF_WRITE) {
6825                 switch (off) {
6826                 case bpf_ctx_range(struct __sk_buff, mark):
6827                 case bpf_ctx_range(struct __sk_buff, priority):
6828                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6829                         break;
6830                 default:
6831                         return false;
6832                 }
6833         }
6834
6835         switch (off) {
6836         case bpf_ctx_range(struct __sk_buff, data):
6837                 info->reg_type = PTR_TO_PACKET;
6838                 break;
6839         case bpf_ctx_range(struct __sk_buff, data_end):
6840                 info->reg_type = PTR_TO_PACKET_END;
6841                 break;
6842         }
6843
6844         return bpf_skb_is_valid_access(off, size, type, prog, info);
6845 }
6846
6847 /* Attach type specific accesses */
6848 static bool __sock_filter_check_attach_type(int off,
6849                                             enum bpf_access_type access_type,
6850                                             enum bpf_attach_type attach_type)
6851 {
6852         switch (off) {
6853         case offsetof(struct bpf_sock, bound_dev_if):
6854         case offsetof(struct bpf_sock, mark):
6855         case offsetof(struct bpf_sock, priority):
6856                 switch (attach_type) {
6857                 case BPF_CGROUP_INET_SOCK_CREATE:
6858                         goto full_access;
6859                 default:
6860                         return false;
6861                 }
6862         case bpf_ctx_range(struct bpf_sock, src_ip4):
6863                 switch (attach_type) {
6864                 case BPF_CGROUP_INET4_POST_BIND:
6865                         goto read_only;
6866                 default:
6867                         return false;
6868                 }
6869         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6870                 switch (attach_type) {
6871                 case BPF_CGROUP_INET6_POST_BIND:
6872                         goto read_only;
6873                 default:
6874                         return false;
6875                 }
6876         case bpf_ctx_range(struct bpf_sock, src_port):
6877                 switch (attach_type) {
6878                 case BPF_CGROUP_INET4_POST_BIND:
6879                 case BPF_CGROUP_INET6_POST_BIND:
6880                         goto read_only;
6881                 default:
6882                         return false;
6883                 }
6884         }
6885 read_only:
6886         return access_type == BPF_READ;
6887 full_access:
6888         return true;
6889 }
6890
6891 bool bpf_sock_common_is_valid_access(int off, int size,
6892                                      enum bpf_access_type type,
6893                                      struct bpf_insn_access_aux *info)
6894 {
6895         switch (off) {
6896         case bpf_ctx_range_till(struct bpf_sock, type, priority):
6897                 return false;
6898         default:
6899                 return bpf_sock_is_valid_access(off, size, type, info);
6900         }
6901 }
6902
6903 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
6904                               struct bpf_insn_access_aux *info)
6905 {
6906         const int size_default = sizeof(__u32);
6907
6908         if (off < 0 || off >= sizeof(struct bpf_sock))
6909                 return false;
6910         if (off % size != 0)
6911                 return false;
6912
6913         switch (off) {
6914         case offsetof(struct bpf_sock, state):
6915         case offsetof(struct bpf_sock, family):
6916         case offsetof(struct bpf_sock, type):
6917         case offsetof(struct bpf_sock, protocol):
6918         case offsetof(struct bpf_sock, dst_port):
6919         case offsetof(struct bpf_sock, src_port):
6920         case offsetof(struct bpf_sock, rx_queue_mapping):
6921         case bpf_ctx_range(struct bpf_sock, src_ip4):
6922         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6923         case bpf_ctx_range(struct bpf_sock, dst_ip4):
6924         case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
6925                 bpf_ctx_record_field_size(info, size_default);
6926                 return bpf_ctx_narrow_access_ok(off, size, size_default);
6927         }
6928
6929         return size == size_default;
6930 }
6931
6932 static bool sock_filter_is_valid_access(int off, int size,
6933                                         enum bpf_access_type type,
6934                                         const struct bpf_prog *prog,
6935                                         struct bpf_insn_access_aux *info)
6936 {
6937         if (!bpf_sock_is_valid_access(off, size, type, info))
6938                 return false;
6939         return __sock_filter_check_attach_type(off, type,
6940                                                prog->expected_attach_type);
6941 }
6942
6943 static int bpf_noop_prologue(struct bpf_insn *insn_buf, bool direct_write,
6944                              const struct bpf_prog *prog)
6945 {
6946         /* Neither direct read nor direct write requires any preliminary
6947          * action.
6948          */
6949         return 0;
6950 }
6951
6952 static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
6953                                 const struct bpf_prog *prog, int drop_verdict)
6954 {
6955         struct bpf_insn *insn = insn_buf;
6956
6957         if (!direct_write)
6958                 return 0;
6959
6960         /* if (!skb->cloned)
6961          *       goto start;
6962          *
6963          * (Fast-path, otherwise approximation that we might be
6964          *  a clone, do the rest in helper.)
6965          */
6966         *insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET());
6967         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
6968         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
6969
6970         /* ret = bpf_skb_pull_data(skb, 0); */
6971         *insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
6972         *insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
6973         *insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
6974                                BPF_FUNC_skb_pull_data);
6975         /* if (!ret)
6976          *      goto restore;
6977          * return TC_ACT_SHOT;
6978          */
6979         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
6980         *insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
6981         *insn++ = BPF_EXIT_INSN();
6982
6983         /* restore: */
6984         *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
6985         /* start: */
6986         *insn++ = prog->insnsi[0];
6987
6988         return insn - insn_buf;
6989 }
6990
6991 static int bpf_gen_ld_abs(const struct bpf_insn *orig,
6992                           struct bpf_insn *insn_buf)
6993 {
6994         bool indirect = BPF_MODE(orig->code) == BPF_IND;
6995         struct bpf_insn *insn = insn_buf;
6996
6997         /* We're guaranteed here that CTX is in R6. */
6998         *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
6999         if (!indirect) {
7000                 *insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
7001         } else {
7002                 *insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
7003                 if (orig->imm)
7004                         *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
7005         }
7006
7007         switch (BPF_SIZE(orig->code)) {
7008         case BPF_B:
7009                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
7010                 break;
7011         case BPF_H:
7012                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
7013                 break;
7014         case BPF_W:
7015                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
7016                 break;
7017         }
7018
7019         *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
7020         *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
7021         *insn++ = BPF_EXIT_INSN();
7022
7023         return insn - insn_buf;
7024 }
7025
7026 static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
7027                                const struct bpf_prog *prog)
7028 {
7029         return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
7030 }
7031
7032 static bool tc_cls_act_is_valid_access(int off, int size,
7033                                        enum bpf_access_type type,
7034                                        const struct bpf_prog *prog,
7035                                        struct bpf_insn_access_aux *info)
7036 {
7037         if (type == BPF_WRITE) {
7038                 switch (off) {
7039                 case bpf_ctx_range(struct __sk_buff, mark):
7040                 case bpf_ctx_range(struct __sk_buff, tc_index):
7041                 case bpf_ctx_range(struct __sk_buff, priority):
7042                 case bpf_ctx_range(struct __sk_buff, tc_classid):
7043                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
7044                 case bpf_ctx_range(struct __sk_buff, tstamp):
7045                 case bpf_ctx_range(struct __sk_buff, queue_mapping):
7046                         break;
7047                 default:
7048                         return false;
7049                 }
7050         }
7051
7052         switch (off) {
7053         case bpf_ctx_range(struct __sk_buff, data):
7054                 info->reg_type = PTR_TO_PACKET;
7055                 break;
7056         case bpf_ctx_range(struct __sk_buff, data_meta):
7057                 info->reg_type = PTR_TO_PACKET_META;
7058                 break;
7059         case bpf_ctx_range(struct __sk_buff, data_end):
7060                 info->reg_type = PTR_TO_PACKET_END;
7061                 break;
7062         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
7063                 return false;
7064         }
7065
7066         return bpf_skb_is_valid_access(off, size, type, prog, info);
7067 }
7068
7069 static bool __is_valid_xdp_access(int off, int size)
7070 {
7071         if (off < 0 || off >= sizeof(struct xdp_md))
7072                 return false;
7073         if (off % size != 0)
7074                 return false;
7075         if (size != sizeof(__u32))
7076                 return false;
7077
7078         return true;
7079 }
7080
7081 static bool xdp_is_valid_access(int off, int size,
7082                                 enum bpf_access_type type,
7083                                 const struct bpf_prog *prog,
7084                                 struct bpf_insn_access_aux *info)
7085 {
7086         if (prog->expected_attach_type != BPF_XDP_DEVMAP) {
7087                 switch (off) {
7088                 case offsetof(struct xdp_md, egress_ifindex):
7089                         return false;
7090                 }
7091         }
7092
7093         if (type == BPF_WRITE) {
7094                 if (bpf_prog_is_dev_bound(prog->aux)) {
7095                         switch (off) {
7096                         case offsetof(struct xdp_md, rx_queue_index):
7097                                 return __is_valid_xdp_access(off, size);
7098                         }
7099                 }
7100                 return false;
7101         }
7102
7103         switch (off) {
7104         case offsetof(struct xdp_md, data):
7105                 info->reg_type = PTR_TO_PACKET;
7106                 break;
7107         case offsetof(struct xdp_md, data_meta):
7108                 info->reg_type = PTR_TO_PACKET_META;
7109                 break;
7110         case offsetof(struct xdp_md, data_end):
7111                 info->reg_type = PTR_TO_PACKET_END;
7112                 break;
7113         }
7114
7115         return __is_valid_xdp_access(off, size);
7116 }
7117
7118 void bpf_warn_invalid_xdp_action(u32 act)
7119 {
7120         const u32 act_max = XDP_REDIRECT;
7121
7122         WARN_ONCE(1, "%s XDP return value %u, expect packet loss!\n",
7123                   act > act_max ? "Illegal" : "Driver unsupported",
7124                   act);
7125 }
7126 EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
7127
7128 static bool sock_addr_is_valid_access(int off, int size,
7129                                       enum bpf_access_type type,
7130                                       const struct bpf_prog *prog,
7131                                       struct bpf_insn_access_aux *info)
7132 {
7133         const int size_default = sizeof(__u32);
7134
7135         if (off < 0 || off >= sizeof(struct bpf_sock_addr))
7136                 return false;
7137         if (off % size != 0)
7138                 return false;
7139
7140         /* Disallow access to IPv6 fields from IPv4 contex and vise
7141          * versa.
7142          */
7143         switch (off) {
7144         case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
7145                 switch (prog->expected_attach_type) {
7146                 case BPF_CGROUP_INET4_BIND:
7147                 case BPF_CGROUP_INET4_CONNECT:
7148                 case BPF_CGROUP_INET4_GETPEERNAME:
7149                 case BPF_CGROUP_INET4_GETSOCKNAME:
7150                 case BPF_CGROUP_UDP4_SENDMSG:
7151                 case BPF_CGROUP_UDP4_RECVMSG:
7152                         break;
7153                 default:
7154                         return false;
7155                 }
7156                 break;
7157         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
7158                 switch (prog->expected_attach_type) {
7159                 case BPF_CGROUP_INET6_BIND:
7160                 case BPF_CGROUP_INET6_CONNECT:
7161                 case BPF_CGROUP_INET6_GETPEERNAME:
7162                 case BPF_CGROUP_INET6_GETSOCKNAME:
7163                 case BPF_CGROUP_UDP6_SENDMSG:
7164                 case BPF_CGROUP_UDP6_RECVMSG:
7165                         break;
7166                 default:
7167                         return false;
7168                 }
7169                 break;
7170         case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
7171                 switch (prog->expected_attach_type) {
7172                 case BPF_CGROUP_UDP4_SENDMSG:
7173                         break;
7174                 default:
7175                         return false;
7176                 }
7177                 break;
7178         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
7179                                 msg_src_ip6[3]):
7180                 switch (prog->expected_attach_type) {
7181                 case BPF_CGROUP_UDP6_SENDMSG:
7182                         break;
7183                 default:
7184                         return false;
7185                 }
7186                 break;
7187         }
7188
7189         switch (off) {
7190         case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
7191         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
7192         case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
7193         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
7194                                 msg_src_ip6[3]):
7195         case bpf_ctx_range(struct bpf_sock_addr, user_port):
7196                 if (type == BPF_READ) {
7197                         bpf_ctx_record_field_size(info, size_default);
7198
7199                         if (bpf_ctx_wide_access_ok(off, size,
7200                                                    struct bpf_sock_addr,
7201                                                    user_ip6))
7202                                 return true;
7203
7204                         if (bpf_ctx_wide_access_ok(off, size,
7205                                                    struct bpf_sock_addr,
7206                                                    msg_src_ip6))
7207                                 return true;
7208
7209                         if (!bpf_ctx_narrow_access_ok(off, size, size_default))
7210                                 return false;
7211                 } else {
7212                         if (bpf_ctx_wide_access_ok(off, size,
7213                                                    struct bpf_sock_addr,
7214                                                    user_ip6))
7215                                 return true;
7216
7217                         if (bpf_ctx_wide_access_ok(off, size,
7218                                                    struct bpf_sock_addr,
7219                                                    msg_src_ip6))
7220                                 return true;
7221
7222                         if (size != size_default)
7223                                 return false;
7224                 }
7225                 break;
7226         case offsetof(struct bpf_sock_addr, sk):
7227                 if (type != BPF_READ)
7228                         return false;
7229                 if (size != sizeof(__u64))
7230                         return false;
7231                 info->reg_type = PTR_TO_SOCKET;
7232                 break;
7233         default:
7234                 if (type == BPF_READ) {
7235                         if (size != size_default)
7236                                 return false;
7237                 } else {
7238                         return false;
7239                 }
7240         }
7241
7242         return true;
7243 }
7244
7245 static bool sock_ops_is_valid_access(int off, int size,
7246                                      enum bpf_access_type type,
7247                                      const struct bpf_prog *prog,
7248                                      struct bpf_insn_access_aux *info)
7249 {
7250         const int size_default = sizeof(__u32);
7251
7252         if (off < 0 || off >= sizeof(struct bpf_sock_ops))
7253                 return false;
7254
7255         /* The verifier guarantees that size > 0. */
7256         if (off % size != 0)
7257                 return false;
7258
7259         if (type == BPF_WRITE) {
7260                 switch (off) {
7261                 case offsetof(struct bpf_sock_ops, reply):
7262                 case offsetof(struct bpf_sock_ops, sk_txhash):
7263                         if (size != size_default)
7264                                 return false;
7265                         break;
7266                 default:
7267                         return false;
7268                 }
7269         } else {
7270                 switch (off) {
7271                 case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received,
7272                                         bytes_acked):
7273                         if (size != sizeof(__u64))
7274                                 return false;
7275                         break;
7276                 case offsetof(struct bpf_sock_ops, sk):
7277                         if (size != sizeof(__u64))
7278                                 return false;
7279                         info->reg_type = PTR_TO_SOCKET_OR_NULL;
7280                         break;
7281                 default:
7282                         if (size != size_default)
7283                                 return false;
7284                         break;
7285                 }
7286         }
7287
7288         return true;
7289 }
7290
7291 static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
7292                            const struct bpf_prog *prog)
7293 {
7294         return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
7295 }
7296
7297 static bool sk_skb_is_valid_access(int off, int size,
7298                                    enum bpf_access_type type,
7299                                    const struct bpf_prog *prog,
7300                                    struct bpf_insn_access_aux *info)
7301 {
7302         switch (off) {
7303         case bpf_ctx_range(struct __sk_buff, tc_classid):
7304         case bpf_ctx_range(struct __sk_buff, data_meta):
7305         case bpf_ctx_range(struct __sk_buff, tstamp):
7306         case bpf_ctx_range(struct __sk_buff, wire_len):
7307                 return false;
7308         }
7309
7310         if (type == BPF_WRITE) {
7311                 switch (off) {
7312                 case bpf_ctx_range(struct __sk_buff, tc_index):
7313                 case bpf_ctx_range(struct __sk_buff, priority):
7314                         break;
7315                 default:
7316                         return false;
7317                 }
7318         }
7319
7320         switch (off) {
7321         case bpf_ctx_range(struct __sk_buff, mark):
7322                 return false;
7323         case bpf_ctx_range(struct __sk_buff, data):
7324                 info->reg_type = PTR_TO_PACKET;
7325                 break;
7326         case bpf_ctx_range(struct __sk_buff, data_end):
7327                 info->reg_type = PTR_TO_PACKET_END;
7328                 break;
7329         }
7330
7331         return bpf_skb_is_valid_access(off, size, type, prog, info);
7332 }
7333
7334 static bool sk_msg_is_valid_access(int off, int size,
7335                                    enum bpf_access_type type,
7336                                    const struct bpf_prog *prog,
7337                                    struct bpf_insn_access_aux *info)
7338 {
7339         if (type == BPF_WRITE)
7340                 return false;
7341
7342         if (off % size != 0)
7343                 return false;
7344
7345         switch (off) {
7346         case offsetof(struct sk_msg_md, data):
7347                 info->reg_type = PTR_TO_PACKET;
7348                 if (size != sizeof(__u64))
7349                         return false;
7350                 break;
7351         case offsetof(struct sk_msg_md, data_end):
7352                 info->reg_type = PTR_TO_PACKET_END;
7353                 if (size != sizeof(__u64))
7354                         return false;
7355                 break;
7356         case offsetof(struct sk_msg_md, sk):
7357                 if (size != sizeof(__u64))
7358                         return false;
7359                 info->reg_type = PTR_TO_SOCKET;
7360                 break;
7361         case bpf_ctx_range(struct sk_msg_md, family):
7362         case bpf_ctx_range(struct sk_msg_md, remote_ip4):
7363         case bpf_ctx_range(struct sk_msg_md, local_ip4):
7364         case bpf_ctx_range_till(struct sk_msg_md, remote_ip6[0], remote_ip6[3]):
7365         case bpf_ctx_range_till(struct sk_msg_md, local_ip6[0], local_ip6[3]):
7366         case bpf_ctx_range(struct sk_msg_md, remote_port):
7367         case bpf_ctx_range(struct sk_msg_md, local_port):
7368         case bpf_ctx_range(struct sk_msg_md, size):
7369                 if (size != sizeof(__u32))
7370                         return false;
7371                 break;
7372         default:
7373                 return false;
7374         }
7375         return true;
7376 }
7377
7378 static bool flow_dissector_is_valid_access(int off, int size,
7379                                            enum bpf_access_type type,
7380                                            const struct bpf_prog *prog,
7381                                            struct bpf_insn_access_aux *info)
7382 {
7383         const int size_default = sizeof(__u32);
7384
7385         if (off < 0 || off >= sizeof(struct __sk_buff))
7386                 return false;
7387
7388         if (type == BPF_WRITE)
7389                 return false;
7390
7391         switch (off) {
7392         case bpf_ctx_range(struct __sk_buff, data):
7393                 if (size != size_default)
7394                         return false;
7395                 info->reg_type = PTR_TO_PACKET;
7396                 return true;
7397         case bpf_ctx_range(struct __sk_buff, data_end):
7398                 if (size != size_default)
7399                         return false;
7400                 info->reg_type = PTR_TO_PACKET_END;
7401                 return true;
7402         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
7403                 if (size != sizeof(__u64))
7404                         return false;
7405                 info->reg_type = PTR_TO_FLOW_KEYS;
7406                 return true;
7407         default:
7408                 return false;
7409         }
7410 }
7411
7412 static u32 flow_dissector_convert_ctx_access(enum bpf_access_type type,
7413                                              const struct bpf_insn *si,
7414                                              struct bpf_insn *insn_buf,
7415                                              struct bpf_prog *prog,
7416                                              u32 *target_size)
7417
7418 {
7419         struct bpf_insn *insn = insn_buf;
7420
7421         switch (si->off) {
7422         case offsetof(struct __sk_buff, data):
7423                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data),
7424                                       si->dst_reg, si->src_reg,
7425                                       offsetof(struct bpf_flow_dissector, data));
7426                 break;
7427
7428         case offsetof(struct __sk_buff, data_end):
7429                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data_end),
7430                                       si->dst_reg, si->src_reg,
7431                                       offsetof(struct bpf_flow_dissector, data_end));
7432                 break;
7433
7434         case offsetof(struct __sk_buff, flow_keys):
7435                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, flow_keys),
7436                                       si->dst_reg, si->src_reg,
7437                                       offsetof(struct bpf_flow_dissector, flow_keys));
7438                 break;
7439         }
7440
7441         return insn - insn_buf;
7442 }
7443
7444 static struct bpf_insn *bpf_convert_shinfo_access(const struct bpf_insn *si,
7445                                                   struct bpf_insn *insn)
7446 {
7447         /* si->dst_reg = skb_shinfo(SKB); */
7448 #ifdef NET_SKBUFF_DATA_USES_OFFSET
7449         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
7450                               BPF_REG_AX, si->src_reg,
7451                               offsetof(struct sk_buff, end));
7452         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, head),
7453                               si->dst_reg, si->src_reg,
7454                               offsetof(struct sk_buff, head));
7455         *insn++ = BPF_ALU64_REG(BPF_ADD, si->dst_reg, BPF_REG_AX);
7456 #else
7457         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
7458                               si->dst_reg, si->src_reg,
7459                               offsetof(struct sk_buff, end));
7460 #endif
7461
7462         return insn;
7463 }
7464
7465 static u32 bpf_convert_ctx_access(enum bpf_access_type type,
7466                                   const struct bpf_insn *si,
7467                                   struct bpf_insn *insn_buf,
7468                                   struct bpf_prog *prog, u32 *target_size)
7469 {
7470         struct bpf_insn *insn = insn_buf;
7471         int off;
7472
7473         switch (si->off) {
7474         case offsetof(struct __sk_buff, len):
7475                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7476                                       bpf_target_off(struct sk_buff, len, 4,
7477                                                      target_size));
7478                 break;
7479
7480         case offsetof(struct __sk_buff, protocol):
7481                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7482                                       bpf_target_off(struct sk_buff, protocol, 2,
7483                                                      target_size));
7484                 break;
7485
7486         case offsetof(struct __sk_buff, vlan_proto):
7487                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7488                                       bpf_target_off(struct sk_buff, vlan_proto, 2,
7489                                                      target_size));
7490                 break;
7491
7492         case offsetof(struct __sk_buff, priority):
7493                 if (type == BPF_WRITE)
7494                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7495                                               bpf_target_off(struct sk_buff, priority, 4,
7496                                                              target_size));
7497                 else
7498                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7499                                               bpf_target_off(struct sk_buff, priority, 4,
7500                                                              target_size));
7501                 break;
7502
7503         case offsetof(struct __sk_buff, ingress_ifindex):
7504                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7505                                       bpf_target_off(struct sk_buff, skb_iif, 4,
7506                                                      target_size));
7507                 break;
7508
7509         case offsetof(struct __sk_buff, ifindex):
7510                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
7511                                       si->dst_reg, si->src_reg,
7512                                       offsetof(struct sk_buff, dev));
7513                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
7514                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7515                                       bpf_target_off(struct net_device, ifindex, 4,
7516                                                      target_size));
7517                 break;
7518
7519         case offsetof(struct __sk_buff, hash):
7520                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7521                                       bpf_target_off(struct sk_buff, hash, 4,
7522                                                      target_size));
7523                 break;
7524
7525         case offsetof(struct __sk_buff, mark):
7526                 if (type == BPF_WRITE)
7527                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7528                                               bpf_target_off(struct sk_buff, mark, 4,
7529                                                              target_size));
7530                 else
7531                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7532                                               bpf_target_off(struct sk_buff, mark, 4,
7533                                                              target_size));
7534                 break;
7535
7536         case offsetof(struct __sk_buff, pkt_type):
7537                 *target_size = 1;
7538                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
7539                                       PKT_TYPE_OFFSET());
7540                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
7541 #ifdef __BIG_ENDIAN_BITFIELD
7542                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
7543 #endif
7544                 break;
7545
7546         case offsetof(struct __sk_buff, queue_mapping):
7547                 if (type == BPF_WRITE) {
7548                         *insn++ = BPF_JMP_IMM(BPF_JGE, si->src_reg, NO_QUEUE_MAPPING, 1);
7549                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
7550                                               bpf_target_off(struct sk_buff,
7551                                                              queue_mapping,
7552                                                              2, target_size));
7553                 } else {
7554                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7555                                               bpf_target_off(struct sk_buff,
7556                                                              queue_mapping,
7557                                                              2, target_size));
7558                 }
7559                 break;
7560
7561         case offsetof(struct __sk_buff, vlan_present):
7562                 *target_size = 1;
7563                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
7564                                       PKT_VLAN_PRESENT_OFFSET());
7565                 if (PKT_VLAN_PRESENT_BIT)
7566                         *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, PKT_VLAN_PRESENT_BIT);
7567                 if (PKT_VLAN_PRESENT_BIT < 7)
7568                         *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1);
7569                 break;
7570
7571         case offsetof(struct __sk_buff, vlan_tci):
7572                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7573                                       bpf_target_off(struct sk_buff, vlan_tci, 2,
7574                                                      target_size));
7575                 break;
7576
7577         case offsetof(struct __sk_buff, cb[0]) ...
7578              offsetofend(struct __sk_buff, cb[4]) - 1:
7579                 BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, data) < 20);
7580                 BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
7581                               offsetof(struct qdisc_skb_cb, data)) %
7582                              sizeof(__u64));
7583
7584                 prog->cb_access = 1;
7585                 off  = si->off;
7586                 off -= offsetof(struct __sk_buff, cb[0]);
7587                 off += offsetof(struct sk_buff, cb);
7588                 off += offsetof(struct qdisc_skb_cb, data);
7589                 if (type == BPF_WRITE)
7590                         *insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
7591                                               si->src_reg, off);
7592                 else
7593                         *insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
7594                                               si->src_reg, off);
7595                 break;
7596
7597         case offsetof(struct __sk_buff, tc_classid):
7598                 BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, tc_classid) != 2);
7599
7600                 off  = si->off;
7601                 off -= offsetof(struct __sk_buff, tc_classid);
7602                 off += offsetof(struct sk_buff, cb);
7603                 off += offsetof(struct qdisc_skb_cb, tc_classid);
7604                 *target_size = 2;
7605                 if (type == BPF_WRITE)
7606                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg,
7607                                               si->src_reg, off);
7608                 else
7609                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
7610                                               si->src_reg, off);
7611                 break;
7612
7613         case offsetof(struct __sk_buff, data):
7614                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
7615                                       si->dst_reg, si->src_reg,
7616                                       offsetof(struct sk_buff, data));
7617                 break;
7618
7619         case offsetof(struct __sk_buff, data_meta):
7620                 off  = si->off;
7621                 off -= offsetof(struct __sk_buff, data_meta);
7622                 off += offsetof(struct sk_buff, cb);
7623                 off += offsetof(struct bpf_skb_data_end, data_meta);
7624                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7625                                       si->src_reg, off);
7626                 break;
7627
7628         case offsetof(struct __sk_buff, data_end):
7629                 off  = si->off;
7630                 off -= offsetof(struct __sk_buff, data_end);
7631                 off += offsetof(struct sk_buff, cb);
7632                 off += offsetof(struct bpf_skb_data_end, data_end);
7633                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7634                                       si->src_reg, off);
7635                 break;
7636
7637         case offsetof(struct __sk_buff, tc_index):
7638 #ifdef CONFIG_NET_SCHED
7639                 if (type == BPF_WRITE)
7640                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
7641                                               bpf_target_off(struct sk_buff, tc_index, 2,
7642                                                              target_size));
7643                 else
7644                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7645                                               bpf_target_off(struct sk_buff, tc_index, 2,
7646                                                              target_size));
7647 #else
7648                 *target_size = 2;
7649                 if (type == BPF_WRITE)
7650                         *insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
7651                 else
7652                         *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7653 #endif
7654                 break;
7655
7656         case offsetof(struct __sk_buff, napi_id):
7657 #if defined(CONFIG_NET_RX_BUSY_POLL)
7658                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7659                                       bpf_target_off(struct sk_buff, napi_id, 4,
7660                                                      target_size));
7661                 *insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
7662                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7663 #else
7664                 *target_size = 4;
7665                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7666 #endif
7667                 break;
7668         case offsetof(struct __sk_buff, family):
7669                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
7670
7671                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7672                                       si->dst_reg, si->src_reg,
7673                                       offsetof(struct sk_buff, sk));
7674                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7675                                       bpf_target_off(struct sock_common,
7676                                                      skc_family,
7677                                                      2, target_size));
7678                 break;
7679         case offsetof(struct __sk_buff, remote_ip4):
7680                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
7681
7682                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7683                                       si->dst_reg, si->src_reg,
7684                                       offsetof(struct sk_buff, sk));
7685                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7686                                       bpf_target_off(struct sock_common,
7687                                                      skc_daddr,
7688                                                      4, target_size));
7689                 break;
7690         case offsetof(struct __sk_buff, local_ip4):
7691                 BUILD_BUG_ON(sizeof_field(struct sock_common,
7692                                           skc_rcv_saddr) != 4);
7693
7694                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7695                                       si->dst_reg, si->src_reg,
7696                                       offsetof(struct sk_buff, sk));
7697                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7698                                       bpf_target_off(struct sock_common,
7699                                                      skc_rcv_saddr,
7700                                                      4, target_size));
7701                 break;
7702         case offsetof(struct __sk_buff, remote_ip6[0]) ...
7703              offsetof(struct __sk_buff, remote_ip6[3]):
7704 #if IS_ENABLED(CONFIG_IPV6)
7705                 BUILD_BUG_ON(sizeof_field(struct sock_common,
7706                                           skc_v6_daddr.s6_addr32[0]) != 4);
7707
7708                 off = si->off;
7709                 off -= offsetof(struct __sk_buff, remote_ip6[0]);
7710
7711                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7712                                       si->dst_reg, si->src_reg,
7713                                       offsetof(struct sk_buff, sk));
7714                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7715                                       offsetof(struct sock_common,
7716                                                skc_v6_daddr.s6_addr32[0]) +
7717                                       off);
7718 #else
7719                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7720 #endif
7721                 break;
7722         case offsetof(struct __sk_buff, local_ip6[0]) ...
7723              offsetof(struct __sk_buff, local_ip6[3]):
7724 #if IS_ENABLED(CONFIG_IPV6)
7725                 BUILD_BUG_ON(sizeof_field(struct sock_common,
7726                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
7727
7728                 off = si->off;
7729                 off -= offsetof(struct __sk_buff, local_ip6[0]);
7730
7731                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7732                                       si->dst_reg, si->src_reg,
7733                                       offsetof(struct sk_buff, sk));
7734                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7735                                       offsetof(struct sock_common,
7736                                                skc_v6_rcv_saddr.s6_addr32[0]) +
7737                                       off);
7738 #else
7739                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7740 #endif
7741                 break;
7742
7743         case offsetof(struct __sk_buff, remote_port):
7744                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
7745
7746                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7747                                       si->dst_reg, si->src_reg,
7748                                       offsetof(struct sk_buff, sk));
7749                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7750                                       bpf_target_off(struct sock_common,
7751                                                      skc_dport,
7752                                                      2, target_size));
7753 #ifndef __BIG_ENDIAN_BITFIELD
7754                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
7755 #endif
7756                 break;
7757
7758         case offsetof(struct __sk_buff, local_port):
7759                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
7760
7761                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7762                                       si->dst_reg, si->src_reg,
7763                                       offsetof(struct sk_buff, sk));
7764                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7765                                       bpf_target_off(struct sock_common,
7766                                                      skc_num, 2, target_size));
7767                 break;
7768
7769         case offsetof(struct __sk_buff, tstamp):
7770                 BUILD_BUG_ON(sizeof_field(struct sk_buff, tstamp) != 8);
7771
7772                 if (type == BPF_WRITE)
7773                         *insn++ = BPF_STX_MEM(BPF_DW,
7774                                               si->dst_reg, si->src_reg,
7775                                               bpf_target_off(struct sk_buff,
7776                                                              tstamp, 8,
7777                                                              target_size));
7778                 else
7779                         *insn++ = BPF_LDX_MEM(BPF_DW,
7780                                               si->dst_reg, si->src_reg,
7781                                               bpf_target_off(struct sk_buff,
7782                                                              tstamp, 8,
7783                                                              target_size));
7784                 break;
7785
7786         case offsetof(struct __sk_buff, gso_segs):
7787                 insn = bpf_convert_shinfo_access(si, insn);
7788                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_segs),
7789                                       si->dst_reg, si->dst_reg,
7790                                       bpf_target_off(struct skb_shared_info,
7791                                                      gso_segs, 2,
7792                                                      target_size));
7793                 break;
7794         case offsetof(struct __sk_buff, gso_size):
7795                 insn = bpf_convert_shinfo_access(si, insn);
7796                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_size),
7797                                       si->dst_reg, si->dst_reg,
7798                                       bpf_target_off(struct skb_shared_info,
7799                                                      gso_size, 2,
7800                                                      target_size));
7801                 break;
7802         case offsetof(struct __sk_buff, wire_len):
7803                 BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, pkt_len) != 4);
7804
7805                 off = si->off;
7806                 off -= offsetof(struct __sk_buff, wire_len);
7807                 off += offsetof(struct sk_buff, cb);
7808                 off += offsetof(struct qdisc_skb_cb, pkt_len);
7809                 *target_size = 4;
7810                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, off);
7811                 break;
7812
7813         case offsetof(struct __sk_buff, sk):
7814                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7815                                       si->dst_reg, si->src_reg,
7816                                       offsetof(struct sk_buff, sk));
7817                 break;
7818         }
7819
7820         return insn - insn_buf;
7821 }
7822
7823 u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
7824                                 const struct bpf_insn *si,
7825                                 struct bpf_insn *insn_buf,
7826                                 struct bpf_prog *prog, u32 *target_size)
7827 {
7828         struct bpf_insn *insn = insn_buf;
7829         int off;
7830
7831         switch (si->off) {
7832         case offsetof(struct bpf_sock, bound_dev_if):
7833                 BUILD_BUG_ON(sizeof_field(struct sock, sk_bound_dev_if) != 4);
7834
7835                 if (type == BPF_WRITE)
7836                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7837                                         offsetof(struct sock, sk_bound_dev_if));
7838                 else
7839                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7840                                       offsetof(struct sock, sk_bound_dev_if));
7841                 break;
7842
7843         case offsetof(struct bpf_sock, mark):
7844                 BUILD_BUG_ON(sizeof_field(struct sock, sk_mark) != 4);
7845
7846                 if (type == BPF_WRITE)
7847                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7848                                         offsetof(struct sock, sk_mark));
7849                 else
7850                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7851                                       offsetof(struct sock, sk_mark));
7852                 break;
7853
7854         case offsetof(struct bpf_sock, priority):
7855                 BUILD_BUG_ON(sizeof_field(struct sock, sk_priority) != 4);
7856
7857                 if (type == BPF_WRITE)
7858                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7859                                         offsetof(struct sock, sk_priority));
7860                 else
7861                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7862                                       offsetof(struct sock, sk_priority));
7863                 break;
7864
7865         case offsetof(struct bpf_sock, family):
7866                 *insn++ = BPF_LDX_MEM(
7867                         BPF_FIELD_SIZEOF(struct sock_common, skc_family),
7868                         si->dst_reg, si->src_reg,
7869                         bpf_target_off(struct sock_common,
7870                                        skc_family,
7871                                        sizeof_field(struct sock_common,
7872                                                     skc_family),
7873                                        target_size));
7874                 break;
7875
7876         case offsetof(struct bpf_sock, type):
7877                 *insn++ = BPF_LDX_MEM(
7878                         BPF_FIELD_SIZEOF(struct sock, sk_type),
7879                         si->dst_reg, si->src_reg,
7880                         bpf_target_off(struct sock, sk_type,
7881                                        sizeof_field(struct sock, sk_type),
7882                                        target_size));
7883                 break;
7884
7885         case offsetof(struct bpf_sock, protocol):
7886                 *insn++ = BPF_LDX_MEM(
7887                         BPF_FIELD_SIZEOF(struct sock, sk_protocol),
7888                         si->dst_reg, si->src_reg,
7889                         bpf_target_off(struct sock, sk_protocol,
7890                                        sizeof_field(struct sock, sk_protocol),
7891                                        target_size));
7892                 break;
7893
7894         case offsetof(struct bpf_sock, src_ip4):
7895                 *insn++ = BPF_LDX_MEM(
7896                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7897                         bpf_target_off(struct sock_common, skc_rcv_saddr,
7898                                        sizeof_field(struct sock_common,
7899                                                     skc_rcv_saddr),
7900                                        target_size));
7901                 break;
7902
7903         case offsetof(struct bpf_sock, dst_ip4):
7904                 *insn++ = BPF_LDX_MEM(
7905                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7906                         bpf_target_off(struct sock_common, skc_daddr,
7907                                        sizeof_field(struct sock_common,
7908                                                     skc_daddr),
7909                                        target_size));
7910                 break;
7911
7912         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
7913 #if IS_ENABLED(CONFIG_IPV6)
7914                 off = si->off;
7915                 off -= offsetof(struct bpf_sock, src_ip6[0]);
7916                 *insn++ = BPF_LDX_MEM(
7917                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7918                         bpf_target_off(
7919                                 struct sock_common,
7920                                 skc_v6_rcv_saddr.s6_addr32[0],
7921                                 sizeof_field(struct sock_common,
7922                                              skc_v6_rcv_saddr.s6_addr32[0]),
7923                                 target_size) + off);
7924 #else
7925                 (void)off;
7926                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7927 #endif
7928                 break;
7929
7930         case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
7931 #if IS_ENABLED(CONFIG_IPV6)
7932                 off = si->off;
7933                 off -= offsetof(struct bpf_sock, dst_ip6[0]);
7934                 *insn++ = BPF_LDX_MEM(
7935                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7936                         bpf_target_off(struct sock_common,
7937                                        skc_v6_daddr.s6_addr32[0],
7938                                        sizeof_field(struct sock_common,
7939                                                     skc_v6_daddr.s6_addr32[0]),
7940                                        target_size) + off);
7941 #else
7942                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7943                 *target_size = 4;
7944 #endif
7945                 break;
7946
7947         case offsetof(struct bpf_sock, src_port):
7948                 *insn++ = BPF_LDX_MEM(
7949                         BPF_FIELD_SIZEOF(struct sock_common, skc_num),
7950                         si->dst_reg, si->src_reg,
7951                         bpf_target_off(struct sock_common, skc_num,
7952                                        sizeof_field(struct sock_common,
7953                                                     skc_num),
7954                                        target_size));
7955                 break;
7956
7957         case offsetof(struct bpf_sock, dst_port):
7958                 *insn++ = BPF_LDX_MEM(
7959                         BPF_FIELD_SIZEOF(struct sock_common, skc_dport),
7960                         si->dst_reg, si->src_reg,
7961                         bpf_target_off(struct sock_common, skc_dport,
7962                                        sizeof_field(struct sock_common,
7963                                                     skc_dport),
7964                                        target_size));
7965                 break;
7966
7967         case offsetof(struct bpf_sock, state):
7968                 *insn++ = BPF_LDX_MEM(
7969                         BPF_FIELD_SIZEOF(struct sock_common, skc_state),
7970                         si->dst_reg, si->src_reg,
7971                         bpf_target_off(struct sock_common, skc_state,
7972                                        sizeof_field(struct sock_common,
7973                                                     skc_state),
7974                                        target_size));
7975                 break;
7976         case offsetof(struct bpf_sock, rx_queue_mapping):
7977 #ifdef CONFIG_XPS
7978                 *insn++ = BPF_LDX_MEM(
7979                         BPF_FIELD_SIZEOF(struct sock, sk_rx_queue_mapping),
7980                         si->dst_reg, si->src_reg,
7981                         bpf_target_off(struct sock, sk_rx_queue_mapping,
7982                                        sizeof_field(struct sock,
7983                                                     sk_rx_queue_mapping),
7984                                        target_size));
7985                 *insn++ = BPF_JMP_IMM(BPF_JNE, si->dst_reg, NO_QUEUE_MAPPING,
7986                                       1);
7987                 *insn++ = BPF_MOV64_IMM(si->dst_reg, -1);
7988 #else
7989                 *insn++ = BPF_MOV64_IMM(si->dst_reg, -1);
7990                 *target_size = 2;
7991 #endif
7992                 break;
7993         }
7994
7995         return insn - insn_buf;
7996 }
7997
7998 static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
7999                                          const struct bpf_insn *si,
8000                                          struct bpf_insn *insn_buf,
8001                                          struct bpf_prog *prog, u32 *target_size)
8002 {
8003         struct bpf_insn *insn = insn_buf;
8004
8005         switch (si->off) {
8006         case offsetof(struct __sk_buff, ifindex):
8007                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
8008                                       si->dst_reg, si->src_reg,
8009                                       offsetof(struct sk_buff, dev));
8010                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8011                                       bpf_target_off(struct net_device, ifindex, 4,
8012                                                      target_size));
8013                 break;
8014         default:
8015                 return bpf_convert_ctx_access(type, si, insn_buf, prog,
8016                                               target_size);
8017         }
8018
8019         return insn - insn_buf;
8020 }
8021
8022 static u32 xdp_convert_ctx_access(enum bpf_access_type type,
8023                                   const struct bpf_insn *si,
8024                                   struct bpf_insn *insn_buf,
8025                                   struct bpf_prog *prog, u32 *target_size)
8026 {
8027         struct bpf_insn *insn = insn_buf;
8028
8029         switch (si->off) {
8030         case offsetof(struct xdp_md, data):
8031                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
8032                                       si->dst_reg, si->src_reg,
8033                                       offsetof(struct xdp_buff, data));
8034                 break;
8035         case offsetof(struct xdp_md, data_meta):
8036                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta),
8037                                       si->dst_reg, si->src_reg,
8038                                       offsetof(struct xdp_buff, data_meta));
8039                 break;
8040         case offsetof(struct xdp_md, data_end):
8041                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
8042                                       si->dst_reg, si->src_reg,
8043                                       offsetof(struct xdp_buff, data_end));
8044                 break;
8045         case offsetof(struct xdp_md, ingress_ifindex):
8046                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
8047                                       si->dst_reg, si->src_reg,
8048                                       offsetof(struct xdp_buff, rxq));
8049                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev),
8050                                       si->dst_reg, si->dst_reg,
8051                                       offsetof(struct xdp_rxq_info, dev));
8052                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8053                                       offsetof(struct net_device, ifindex));
8054                 break;
8055         case offsetof(struct xdp_md, rx_queue_index):
8056                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
8057                                       si->dst_reg, si->src_reg,
8058                                       offsetof(struct xdp_buff, rxq));
8059                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8060                                       offsetof(struct xdp_rxq_info,
8061                                                queue_index));
8062                 break;
8063         case offsetof(struct xdp_md, egress_ifindex):
8064                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, txq),
8065                                       si->dst_reg, si->src_reg,
8066                                       offsetof(struct xdp_buff, txq));
8067                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_txq_info, dev),
8068                                       si->dst_reg, si->dst_reg,
8069                                       offsetof(struct xdp_txq_info, dev));
8070                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8071                                       offsetof(struct net_device, ifindex));
8072                 break;
8073         }
8074
8075         return insn - insn_buf;
8076 }
8077
8078 /* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of
8079  * context Structure, F is Field in context structure that contains a pointer
8080  * to Nested Structure of type NS that has the field NF.
8081  *
8082  * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make
8083  * sure that SIZE is not greater than actual size of S.F.NF.
8084  *
8085  * If offset OFF is provided, the load happens from that offset relative to
8086  * offset of NF.
8087  */
8088 #define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF)          \
8089         do {                                                                   \
8090                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg,     \
8091                                       si->src_reg, offsetof(S, F));            \
8092                 *insn++ = BPF_LDX_MEM(                                         \
8093                         SIZE, si->dst_reg, si->dst_reg,                        \
8094                         bpf_target_off(NS, NF, sizeof_field(NS, NF),           \
8095                                        target_size)                            \
8096                                 + OFF);                                        \
8097         } while (0)
8098
8099 #define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF)                              \
8100         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF,                     \
8101                                              BPF_FIELD_SIZEOF(NS, NF), 0)
8102
8103 /* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to
8104  * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation.
8105  *
8106  * In addition it uses Temporary Field TF (member of struct S) as the 3rd
8107  * "register" since two registers available in convert_ctx_access are not
8108  * enough: we can't override neither SRC, since it contains value to store, nor
8109  * DST since it contains pointer to context that may be used by later
8110  * instructions. But we need a temporary place to save pointer to nested
8111  * structure whose field we want to store to.
8112  */
8113 #define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE, OFF, TF)          \
8114         do {                                                                   \
8115                 int tmp_reg = BPF_REG_9;                                       \
8116                 if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
8117                         --tmp_reg;                                             \
8118                 if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
8119                         --tmp_reg;                                             \
8120                 *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg,            \
8121                                       offsetof(S, TF));                        \
8122                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg,         \
8123                                       si->dst_reg, offsetof(S, F));            \
8124                 *insn++ = BPF_STX_MEM(SIZE, tmp_reg, si->src_reg,              \
8125                         bpf_target_off(NS, NF, sizeof_field(NS, NF),           \
8126                                        target_size)                            \
8127                                 + OFF);                                        \
8128                 *insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg,            \
8129                                       offsetof(S, TF));                        \
8130         } while (0)
8131
8132 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \
8133                                                       TF)                      \
8134         do {                                                                   \
8135                 if (type == BPF_WRITE) {                                       \
8136                         SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE,   \
8137                                                          OFF, TF);             \
8138                 } else {                                                       \
8139                         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(                  \
8140                                 S, NS, F, NF, SIZE, OFF);  \
8141                 }                                                              \
8142         } while (0)
8143
8144 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(S, NS, F, NF, TF)                 \
8145         SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(                         \
8146                 S, NS, F, NF, BPF_FIELD_SIZEOF(NS, NF), 0, TF)
8147
8148 static u32 sock_addr_convert_ctx_access(enum bpf_access_type type,
8149                                         const struct bpf_insn *si,
8150                                         struct bpf_insn *insn_buf,
8151                                         struct bpf_prog *prog, u32 *target_size)
8152 {
8153         int off, port_size = sizeof_field(struct sockaddr_in6, sin6_port);
8154         struct bpf_insn *insn = insn_buf;
8155
8156         switch (si->off) {
8157         case offsetof(struct bpf_sock_addr, user_family):
8158                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
8159                                             struct sockaddr, uaddr, sa_family);
8160                 break;
8161
8162         case offsetof(struct bpf_sock_addr, user_ip4):
8163                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
8164                         struct bpf_sock_addr_kern, struct sockaddr_in, uaddr,
8165                         sin_addr, BPF_SIZE(si->code), 0, tmp_reg);
8166                 break;
8167
8168         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
8169                 off = si->off;
8170                 off -= offsetof(struct bpf_sock_addr, user_ip6[0]);
8171                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
8172                         struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
8173                         sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off,
8174                         tmp_reg);
8175                 break;
8176
8177         case offsetof(struct bpf_sock_addr, user_port):
8178                 /* To get port we need to know sa_family first and then treat
8179                  * sockaddr as either sockaddr_in or sockaddr_in6.
8180                  * Though we can simplify since port field has same offset and
8181                  * size in both structures.
8182                  * Here we check this invariant and use just one of the
8183                  * structures if it's true.
8184                  */
8185                 BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) !=
8186                              offsetof(struct sockaddr_in6, sin6_port));
8187                 BUILD_BUG_ON(sizeof_field(struct sockaddr_in, sin_port) !=
8188                              sizeof_field(struct sockaddr_in6, sin6_port));
8189                 /* Account for sin6_port being smaller than user_port. */
8190                 port_size = min(port_size, BPF_LDST_BYTES(si));
8191                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
8192                         struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
8193                         sin6_port, bytes_to_bpf_size(port_size), 0, tmp_reg);
8194                 break;
8195
8196         case offsetof(struct bpf_sock_addr, family):
8197                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
8198                                             struct sock, sk, sk_family);
8199                 break;
8200
8201         case offsetof(struct bpf_sock_addr, type):
8202                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
8203                                             struct sock, sk, sk_type);
8204                 break;
8205
8206         case offsetof(struct bpf_sock_addr, protocol):
8207                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
8208                                             struct sock, sk, sk_protocol);
8209                 break;
8210
8211         case offsetof(struct bpf_sock_addr, msg_src_ip4):
8212                 /* Treat t_ctx as struct in_addr for msg_src_ip4. */
8213                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
8214                         struct bpf_sock_addr_kern, struct in_addr, t_ctx,
8215                         s_addr, BPF_SIZE(si->code), 0, tmp_reg);
8216                 break;
8217
8218         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
8219                                 msg_src_ip6[3]):
8220                 off = si->off;
8221                 off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]);
8222                 /* Treat t_ctx as struct in6_addr for msg_src_ip6. */
8223                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
8224                         struct bpf_sock_addr_kern, struct in6_addr, t_ctx,
8225                         s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg);
8226                 break;
8227         case offsetof(struct bpf_sock_addr, sk):
8228                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_addr_kern, sk),
8229                                       si->dst_reg, si->src_reg,
8230                                       offsetof(struct bpf_sock_addr_kern, sk));
8231                 break;
8232         }
8233
8234         return insn - insn_buf;
8235 }
8236
8237 static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
8238                                        const struct bpf_insn *si,
8239                                        struct bpf_insn *insn_buf,
8240                                        struct bpf_prog *prog,
8241                                        u32 *target_size)
8242 {
8243         struct bpf_insn *insn = insn_buf;
8244         int off;
8245
8246 /* Helper macro for adding read access to tcp_sock or sock fields. */
8247 #define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
8248         do {                                                                  \
8249                 BUILD_BUG_ON(sizeof_field(OBJ, OBJ_FIELD) >                   \
8250                              sizeof_field(struct bpf_sock_ops, BPF_FIELD));   \
8251                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
8252                                                 struct bpf_sock_ops_kern,     \
8253                                                 is_fullsock),                 \
8254                                       si->dst_reg, si->src_reg,               \
8255                                       offsetof(struct bpf_sock_ops_kern,      \
8256                                                is_fullsock));                 \
8257                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 2);            \
8258                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
8259                                                 struct bpf_sock_ops_kern, sk),\
8260                                       si->dst_reg, si->src_reg,               \
8261                                       offsetof(struct bpf_sock_ops_kern, sk));\
8262                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ,                   \
8263                                                        OBJ_FIELD),            \
8264                                       si->dst_reg, si->dst_reg,               \
8265                                       offsetof(OBJ, OBJ_FIELD));              \
8266         } while (0)
8267
8268 #define SOCK_OPS_GET_TCP_SOCK_FIELD(FIELD) \
8269                 SOCK_OPS_GET_FIELD(FIELD, FIELD, struct tcp_sock)
8270
8271 /* Helper macro for adding write access to tcp_sock or sock fields.
8272  * The macro is called with two registers, dst_reg which contains a pointer
8273  * to ctx (context) and src_reg which contains the value that should be
8274  * stored. However, we need an additional register since we cannot overwrite
8275  * dst_reg because it may be used later in the program.
8276  * Instead we "borrow" one of the other register. We first save its value
8277  * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore
8278  * it at the end of the macro.
8279  */
8280 #define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
8281         do {                                                                  \
8282                 int reg = BPF_REG_9;                                          \
8283                 BUILD_BUG_ON(sizeof_field(OBJ, OBJ_FIELD) >                   \
8284                              sizeof_field(struct bpf_sock_ops, BPF_FIELD));   \
8285                 if (si->dst_reg == reg || si->src_reg == reg)                 \
8286                         reg--;                                                \
8287                 if (si->dst_reg == reg || si->src_reg == reg)                 \
8288                         reg--;                                                \
8289                 *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg,               \
8290                                       offsetof(struct bpf_sock_ops_kern,      \
8291                                                temp));                        \
8292                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
8293                                                 struct bpf_sock_ops_kern,     \
8294                                                 is_fullsock),                 \
8295                                       reg, si->dst_reg,                       \
8296                                       offsetof(struct bpf_sock_ops_kern,      \
8297                                                is_fullsock));                 \
8298                 *insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);                    \
8299                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
8300                                                 struct bpf_sock_ops_kern, sk),\
8301                                       reg, si->dst_reg,                       \
8302                                       offsetof(struct bpf_sock_ops_kern, sk));\
8303                 *insn++ = BPF_STX_MEM(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD),       \
8304                                       reg, si->src_reg,                       \
8305                                       offsetof(OBJ, OBJ_FIELD));              \
8306                 *insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg,               \
8307                                       offsetof(struct bpf_sock_ops_kern,      \
8308                                                temp));                        \
8309         } while (0)
8310
8311 #define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE)            \
8312         do {                                                                  \
8313                 if (TYPE == BPF_WRITE)                                        \
8314                         SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
8315                 else                                                          \
8316                         SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
8317         } while (0)
8318
8319         if (insn > insn_buf)
8320                 return insn - insn_buf;
8321
8322         switch (si->off) {
8323         case offsetof(struct bpf_sock_ops, op) ...
8324              offsetof(struct bpf_sock_ops, replylong[3]):
8325                 BUILD_BUG_ON(sizeof_field(struct bpf_sock_ops, op) !=
8326                              sizeof_field(struct bpf_sock_ops_kern, op));
8327                 BUILD_BUG_ON(sizeof_field(struct bpf_sock_ops, reply) !=
8328                              sizeof_field(struct bpf_sock_ops_kern, reply));
8329                 BUILD_BUG_ON(sizeof_field(struct bpf_sock_ops, replylong) !=
8330                              sizeof_field(struct bpf_sock_ops_kern, replylong));
8331                 off = si->off;
8332                 off -= offsetof(struct bpf_sock_ops, op);
8333                 off += offsetof(struct bpf_sock_ops_kern, op);
8334                 if (type == BPF_WRITE)
8335                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
8336                                               off);
8337                 else
8338                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
8339                                               off);
8340                 break;
8341
8342         case offsetof(struct bpf_sock_ops, family):
8343                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
8344
8345                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8346                                               struct bpf_sock_ops_kern, sk),
8347                                       si->dst_reg, si->src_reg,
8348                                       offsetof(struct bpf_sock_ops_kern, sk));
8349                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8350                                       offsetof(struct sock_common, skc_family));
8351                 break;
8352
8353         case offsetof(struct bpf_sock_ops, remote_ip4):
8354                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
8355
8356                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8357                                                 struct bpf_sock_ops_kern, sk),
8358                                       si->dst_reg, si->src_reg,
8359                                       offsetof(struct bpf_sock_ops_kern, sk));
8360                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8361                                       offsetof(struct sock_common, skc_daddr));
8362                 break;
8363
8364         case offsetof(struct bpf_sock_ops, local_ip4):
8365                 BUILD_BUG_ON(sizeof_field(struct sock_common,
8366                                           skc_rcv_saddr) != 4);
8367
8368                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8369                                               struct bpf_sock_ops_kern, sk),
8370                                       si->dst_reg, si->src_reg,
8371                                       offsetof(struct bpf_sock_ops_kern, sk));
8372                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8373                                       offsetof(struct sock_common,
8374                                                skc_rcv_saddr));
8375                 break;
8376
8377         case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
8378              offsetof(struct bpf_sock_ops, remote_ip6[3]):
8379 #if IS_ENABLED(CONFIG_IPV6)
8380                 BUILD_BUG_ON(sizeof_field(struct sock_common,
8381                                           skc_v6_daddr.s6_addr32[0]) != 4);
8382
8383                 off = si->off;
8384                 off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
8385                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8386                                                 struct bpf_sock_ops_kern, sk),
8387                                       si->dst_reg, si->src_reg,
8388                                       offsetof(struct bpf_sock_ops_kern, sk));
8389                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8390                                       offsetof(struct sock_common,
8391                                                skc_v6_daddr.s6_addr32[0]) +
8392                                       off);
8393 #else
8394                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8395 #endif
8396                 break;
8397
8398         case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
8399              offsetof(struct bpf_sock_ops, local_ip6[3]):
8400 #if IS_ENABLED(CONFIG_IPV6)
8401                 BUILD_BUG_ON(sizeof_field(struct sock_common,
8402                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
8403
8404                 off = si->off;
8405                 off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
8406                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8407                                                 struct bpf_sock_ops_kern, sk),
8408                                       si->dst_reg, si->src_reg,
8409                                       offsetof(struct bpf_sock_ops_kern, sk));
8410                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8411                                       offsetof(struct sock_common,
8412                                                skc_v6_rcv_saddr.s6_addr32[0]) +
8413                                       off);
8414 #else
8415                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8416 #endif
8417                 break;
8418
8419         case offsetof(struct bpf_sock_ops, remote_port):
8420                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
8421
8422                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8423                                                 struct bpf_sock_ops_kern, sk),
8424                                       si->dst_reg, si->src_reg,
8425                                       offsetof(struct bpf_sock_ops_kern, sk));
8426                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8427                                       offsetof(struct sock_common, skc_dport));
8428 #ifndef __BIG_ENDIAN_BITFIELD
8429                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
8430 #endif
8431                 break;
8432
8433         case offsetof(struct bpf_sock_ops, local_port):
8434                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
8435
8436                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8437                                                 struct bpf_sock_ops_kern, sk),
8438                                       si->dst_reg, si->src_reg,
8439                                       offsetof(struct bpf_sock_ops_kern, sk));
8440                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8441                                       offsetof(struct sock_common, skc_num));
8442                 break;
8443
8444         case offsetof(struct bpf_sock_ops, is_fullsock):
8445                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8446                                                 struct bpf_sock_ops_kern,
8447                                                 is_fullsock),
8448                                       si->dst_reg, si->src_reg,
8449                                       offsetof(struct bpf_sock_ops_kern,
8450                                                is_fullsock));
8451                 break;
8452
8453         case offsetof(struct bpf_sock_ops, state):
8454                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_state) != 1);
8455
8456                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8457                                                 struct bpf_sock_ops_kern, sk),
8458                                       si->dst_reg, si->src_reg,
8459                                       offsetof(struct bpf_sock_ops_kern, sk));
8460                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg,
8461                                       offsetof(struct sock_common, skc_state));
8462                 break;
8463
8464         case offsetof(struct bpf_sock_ops, rtt_min):
8465                 BUILD_BUG_ON(sizeof_field(struct tcp_sock, rtt_min) !=
8466                              sizeof(struct minmax));
8467                 BUILD_BUG_ON(sizeof(struct minmax) <
8468                              sizeof(struct minmax_sample));
8469
8470                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8471                                                 struct bpf_sock_ops_kern, sk),
8472                                       si->dst_reg, si->src_reg,
8473                                       offsetof(struct bpf_sock_ops_kern, sk));
8474                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8475                                       offsetof(struct tcp_sock, rtt_min) +
8476                                       sizeof_field(struct minmax_sample, t));
8477                 break;
8478
8479         case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags):
8480                 SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags,
8481                                    struct tcp_sock);
8482                 break;
8483
8484         case offsetof(struct bpf_sock_ops, sk_txhash):
8485                 SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash,
8486                                           struct sock, type);
8487                 break;
8488         case offsetof(struct bpf_sock_ops, snd_cwnd):
8489                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_cwnd);
8490                 break;
8491         case offsetof(struct bpf_sock_ops, srtt_us):
8492                 SOCK_OPS_GET_TCP_SOCK_FIELD(srtt_us);
8493                 break;
8494         case offsetof(struct bpf_sock_ops, snd_ssthresh):
8495                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_ssthresh);
8496                 break;
8497         case offsetof(struct bpf_sock_ops, rcv_nxt):
8498                 SOCK_OPS_GET_TCP_SOCK_FIELD(rcv_nxt);
8499                 break;
8500         case offsetof(struct bpf_sock_ops, snd_nxt):
8501                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_nxt);
8502                 break;
8503         case offsetof(struct bpf_sock_ops, snd_una):
8504                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_una);
8505                 break;
8506         case offsetof(struct bpf_sock_ops, mss_cache):
8507                 SOCK_OPS_GET_TCP_SOCK_FIELD(mss_cache);
8508                 break;
8509         case offsetof(struct bpf_sock_ops, ecn_flags):
8510                 SOCK_OPS_GET_TCP_SOCK_FIELD(ecn_flags);
8511                 break;
8512         case offsetof(struct bpf_sock_ops, rate_delivered):
8513                 SOCK_OPS_GET_TCP_SOCK_FIELD(rate_delivered);
8514                 break;
8515         case offsetof(struct bpf_sock_ops, rate_interval_us):
8516                 SOCK_OPS_GET_TCP_SOCK_FIELD(rate_interval_us);
8517                 break;
8518         case offsetof(struct bpf_sock_ops, packets_out):
8519                 SOCK_OPS_GET_TCP_SOCK_FIELD(packets_out);
8520                 break;
8521         case offsetof(struct bpf_sock_ops, retrans_out):
8522                 SOCK_OPS_GET_TCP_SOCK_FIELD(retrans_out);
8523                 break;
8524         case offsetof(struct bpf_sock_ops, total_retrans):
8525                 SOCK_OPS_GET_TCP_SOCK_FIELD(total_retrans);
8526                 break;
8527         case offsetof(struct bpf_sock_ops, segs_in):
8528                 SOCK_OPS_GET_TCP_SOCK_FIELD(segs_in);
8529                 break;
8530         case offsetof(struct bpf_sock_ops, data_segs_in):
8531                 SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_in);
8532                 break;
8533         case offsetof(struct bpf_sock_ops, segs_out):
8534                 SOCK_OPS_GET_TCP_SOCK_FIELD(segs_out);
8535                 break;
8536         case offsetof(struct bpf_sock_ops, data_segs_out):
8537                 SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_out);
8538                 break;
8539         case offsetof(struct bpf_sock_ops, lost_out):
8540                 SOCK_OPS_GET_TCP_SOCK_FIELD(lost_out);
8541                 break;
8542         case offsetof(struct bpf_sock_ops, sacked_out):
8543                 SOCK_OPS_GET_TCP_SOCK_FIELD(sacked_out);
8544                 break;
8545         case offsetof(struct bpf_sock_ops, bytes_received):
8546                 SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_received);
8547                 break;
8548         case offsetof(struct bpf_sock_ops, bytes_acked):
8549                 SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_acked);
8550                 break;
8551         case offsetof(struct bpf_sock_ops, sk):
8552                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8553                                                 struct bpf_sock_ops_kern,
8554                                                 is_fullsock),
8555                                       si->dst_reg, si->src_reg,
8556                                       offsetof(struct bpf_sock_ops_kern,
8557                                                is_fullsock));
8558                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
8559                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8560                                                 struct bpf_sock_ops_kern, sk),
8561                                       si->dst_reg, si->src_reg,
8562                                       offsetof(struct bpf_sock_ops_kern, sk));
8563                 break;
8564         }
8565         return insn - insn_buf;
8566 }
8567
8568 static u32 sk_skb_convert_ctx_access(enum bpf_access_type type,
8569                                      const struct bpf_insn *si,
8570                                      struct bpf_insn *insn_buf,
8571                                      struct bpf_prog *prog, u32 *target_size)
8572 {
8573         struct bpf_insn *insn = insn_buf;
8574         int off;
8575
8576         switch (si->off) {
8577         case offsetof(struct __sk_buff, data_end):
8578                 off  = si->off;
8579                 off -= offsetof(struct __sk_buff, data_end);
8580                 off += offsetof(struct sk_buff, cb);
8581                 off += offsetof(struct tcp_skb_cb, bpf.data_end);
8582                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
8583                                       si->src_reg, off);
8584                 break;
8585         default:
8586                 return bpf_convert_ctx_access(type, si, insn_buf, prog,
8587                                               target_size);
8588         }
8589
8590         return insn - insn_buf;
8591 }
8592
8593 static u32 sk_msg_convert_ctx_access(enum bpf_access_type type,
8594                                      const struct bpf_insn *si,
8595                                      struct bpf_insn *insn_buf,
8596                                      struct bpf_prog *prog, u32 *target_size)
8597 {
8598         struct bpf_insn *insn = insn_buf;
8599 #if IS_ENABLED(CONFIG_IPV6)
8600         int off;
8601 #endif
8602
8603         /* convert ctx uses the fact sg element is first in struct */
8604         BUILD_BUG_ON(offsetof(struct sk_msg, sg) != 0);
8605
8606         switch (si->off) {
8607         case offsetof(struct sk_msg_md, data):
8608                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data),
8609                                       si->dst_reg, si->src_reg,
8610                                       offsetof(struct sk_msg, data));
8611                 break;
8612         case offsetof(struct sk_msg_md, data_end):
8613                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data_end),
8614                                       si->dst_reg, si->src_reg,
8615                                       offsetof(struct sk_msg, data_end));
8616                 break;
8617         case offsetof(struct sk_msg_md, family):
8618                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
8619
8620                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8621                                               struct sk_msg, sk),
8622                                       si->dst_reg, si->src_reg,
8623                                       offsetof(struct sk_msg, sk));
8624                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8625                                       offsetof(struct sock_common, skc_family));
8626                 break;
8627
8628         case offsetof(struct sk_msg_md, remote_ip4):
8629                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
8630
8631                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8632                                                 struct sk_msg, sk),
8633                                       si->dst_reg, si->src_reg,
8634                                       offsetof(struct sk_msg, sk));
8635                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8636                                       offsetof(struct sock_common, skc_daddr));
8637                 break;
8638
8639         case offsetof(struct sk_msg_md, local_ip4):
8640                 BUILD_BUG_ON(sizeof_field(struct sock_common,
8641                                           skc_rcv_saddr) != 4);
8642
8643                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8644                                               struct sk_msg, sk),
8645                                       si->dst_reg, si->src_reg,
8646                                       offsetof(struct sk_msg, sk));
8647                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8648                                       offsetof(struct sock_common,
8649                                                skc_rcv_saddr));
8650                 break;
8651
8652         case offsetof(struct sk_msg_md, remote_ip6[0]) ...
8653              offsetof(struct sk_msg_md, remote_ip6[3]):
8654 #if IS_ENABLED(CONFIG_IPV6)
8655                 BUILD_BUG_ON(sizeof_field(struct sock_common,
8656                                           skc_v6_daddr.s6_addr32[0]) != 4);
8657
8658                 off = si->off;
8659                 off -= offsetof(struct sk_msg_md, remote_ip6[0]);
8660                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8661                                                 struct sk_msg, sk),
8662                                       si->dst_reg, si->src_reg,
8663                                       offsetof(struct sk_msg, sk));
8664                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8665                                       offsetof(struct sock_common,
8666                                                skc_v6_daddr.s6_addr32[0]) +
8667                                       off);
8668 #else
8669                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8670 #endif
8671                 break;
8672
8673         case offsetof(struct sk_msg_md, local_ip6[0]) ...
8674              offsetof(struct sk_msg_md, local_ip6[3]):
8675 #if IS_ENABLED(CONFIG_IPV6)
8676                 BUILD_BUG_ON(sizeof_field(struct sock_common,
8677                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
8678
8679                 off = si->off;
8680                 off -= offsetof(struct sk_msg_md, local_ip6[0]);
8681                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8682                                                 struct sk_msg, sk),
8683                                       si->dst_reg, si->src_reg,
8684                                       offsetof(struct sk_msg, sk));
8685                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8686                                       offsetof(struct sock_common,
8687                                                skc_v6_rcv_saddr.s6_addr32[0]) +
8688                                       off);
8689 #else
8690                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8691 #endif
8692                 break;
8693
8694         case offsetof(struct sk_msg_md, remote_port):
8695                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
8696
8697                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8698                                                 struct sk_msg, sk),
8699                                       si->dst_reg, si->src_reg,
8700                                       offsetof(struct sk_msg, sk));
8701                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8702                                       offsetof(struct sock_common, skc_dport));
8703 #ifndef __BIG_ENDIAN_BITFIELD
8704                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
8705 #endif
8706                 break;
8707
8708         case offsetof(struct sk_msg_md, local_port):
8709                 BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
8710
8711                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8712                                                 struct sk_msg, sk),
8713                                       si->dst_reg, si->src_reg,
8714                                       offsetof(struct sk_msg, sk));
8715                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8716                                       offsetof(struct sock_common, skc_num));
8717                 break;
8718
8719         case offsetof(struct sk_msg_md, size):
8720                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_sg, size),
8721                                       si->dst_reg, si->src_reg,
8722                                       offsetof(struct sk_msg_sg, size));
8723                 break;
8724
8725         case offsetof(struct sk_msg_md, sk):
8726                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, sk),
8727                                       si->dst_reg, si->src_reg,
8728                                       offsetof(struct sk_msg, sk));
8729                 break;
8730         }
8731
8732         return insn - insn_buf;
8733 }
8734
8735 const struct bpf_verifier_ops sk_filter_verifier_ops = {
8736         .get_func_proto         = sk_filter_func_proto,
8737         .is_valid_access        = sk_filter_is_valid_access,
8738         .convert_ctx_access     = bpf_convert_ctx_access,
8739         .gen_ld_abs             = bpf_gen_ld_abs,
8740 };
8741
8742 const struct bpf_prog_ops sk_filter_prog_ops = {
8743         .test_run               = bpf_prog_test_run_skb,
8744 };
8745
8746 const struct bpf_verifier_ops tc_cls_act_verifier_ops = {
8747         .get_func_proto         = tc_cls_act_func_proto,
8748         .is_valid_access        = tc_cls_act_is_valid_access,
8749         .convert_ctx_access     = tc_cls_act_convert_ctx_access,
8750         .gen_prologue           = tc_cls_act_prologue,
8751         .gen_ld_abs             = bpf_gen_ld_abs,
8752 };
8753
8754 const struct bpf_prog_ops tc_cls_act_prog_ops = {
8755         .test_run               = bpf_prog_test_run_skb,
8756 };
8757
8758 const struct bpf_verifier_ops xdp_verifier_ops = {
8759         .get_func_proto         = xdp_func_proto,
8760         .is_valid_access        = xdp_is_valid_access,
8761         .convert_ctx_access     = xdp_convert_ctx_access,
8762         .gen_prologue           = bpf_noop_prologue,
8763 };
8764
8765 const struct bpf_prog_ops xdp_prog_ops = {
8766         .test_run               = bpf_prog_test_run_xdp,
8767 };
8768
8769 const struct bpf_verifier_ops cg_skb_verifier_ops = {
8770         .get_func_proto         = cg_skb_func_proto,
8771         .is_valid_access        = cg_skb_is_valid_access,
8772         .convert_ctx_access     = bpf_convert_ctx_access,
8773 };
8774
8775 const struct bpf_prog_ops cg_skb_prog_ops = {
8776         .test_run               = bpf_prog_test_run_skb,
8777 };
8778
8779 const struct bpf_verifier_ops lwt_in_verifier_ops = {
8780         .get_func_proto         = lwt_in_func_proto,
8781         .is_valid_access        = lwt_is_valid_access,
8782         .convert_ctx_access     = bpf_convert_ctx_access,
8783 };
8784
8785 const struct bpf_prog_ops lwt_in_prog_ops = {
8786         .test_run               = bpf_prog_test_run_skb,
8787 };
8788
8789 const struct bpf_verifier_ops lwt_out_verifier_ops = {
8790         .get_func_proto         = lwt_out_func_proto,
8791         .is_valid_access        = lwt_is_valid_access,
8792         .convert_ctx_access     = bpf_convert_ctx_access,
8793 };
8794
8795 const struct bpf_prog_ops lwt_out_prog_ops = {
8796         .test_run               = bpf_prog_test_run_skb,
8797 };
8798
8799 const struct bpf_verifier_ops lwt_xmit_verifier_ops = {
8800         .get_func_proto         = lwt_xmit_func_proto,
8801         .is_valid_access        = lwt_is_valid_access,
8802         .convert_ctx_access     = bpf_convert_ctx_access,
8803         .gen_prologue           = tc_cls_act_prologue,
8804 };
8805
8806 const struct bpf_prog_ops lwt_xmit_prog_ops = {
8807         .test_run               = bpf_prog_test_run_skb,
8808 };
8809
8810 const struct bpf_verifier_ops lwt_seg6local_verifier_ops = {
8811         .get_func_proto         = lwt_seg6local_func_proto,
8812         .is_valid_access        = lwt_is_valid_access,
8813         .convert_ctx_access     = bpf_convert_ctx_access,
8814 };
8815
8816 const struct bpf_prog_ops lwt_seg6local_prog_ops = {
8817         .test_run               = bpf_prog_test_run_skb,
8818 };
8819
8820 const struct bpf_verifier_ops cg_sock_verifier_ops = {
8821         .get_func_proto         = sock_filter_func_proto,
8822         .is_valid_access        = sock_filter_is_valid_access,
8823         .convert_ctx_access     = bpf_sock_convert_ctx_access,
8824 };
8825
8826 const struct bpf_prog_ops cg_sock_prog_ops = {
8827 };
8828
8829 const struct bpf_verifier_ops cg_sock_addr_verifier_ops = {
8830         .get_func_proto         = sock_addr_func_proto,
8831         .is_valid_access        = sock_addr_is_valid_access,
8832         .convert_ctx_access     = sock_addr_convert_ctx_access,
8833 };
8834
8835 const struct bpf_prog_ops cg_sock_addr_prog_ops = {
8836 };
8837
8838 const struct bpf_verifier_ops sock_ops_verifier_ops = {
8839         .get_func_proto         = sock_ops_func_proto,
8840         .is_valid_access        = sock_ops_is_valid_access,
8841         .convert_ctx_access     = sock_ops_convert_ctx_access,
8842 };
8843
8844 const struct bpf_prog_ops sock_ops_prog_ops = {
8845 };
8846
8847 const struct bpf_verifier_ops sk_skb_verifier_ops = {
8848         .get_func_proto         = sk_skb_func_proto,
8849         .is_valid_access        = sk_skb_is_valid_access,
8850         .convert_ctx_access     = sk_skb_convert_ctx_access,
8851         .gen_prologue           = sk_skb_prologue,
8852 };
8853
8854 const struct bpf_prog_ops sk_skb_prog_ops = {
8855 };
8856
8857 const struct bpf_verifier_ops sk_msg_verifier_ops = {
8858         .get_func_proto         = sk_msg_func_proto,
8859         .is_valid_access        = sk_msg_is_valid_access,
8860         .convert_ctx_access     = sk_msg_convert_ctx_access,
8861         .gen_prologue           = bpf_noop_prologue,
8862 };
8863
8864 const struct bpf_prog_ops sk_msg_prog_ops = {
8865 };
8866
8867 const struct bpf_verifier_ops flow_dissector_verifier_ops = {
8868         .get_func_proto         = flow_dissector_func_proto,
8869         .is_valid_access        = flow_dissector_is_valid_access,
8870         .convert_ctx_access     = flow_dissector_convert_ctx_access,
8871 };
8872
8873 const struct bpf_prog_ops flow_dissector_prog_ops = {
8874         .test_run               = bpf_prog_test_run_flow_dissector,
8875 };
8876
8877 int sk_detach_filter(struct sock *sk)
8878 {
8879         int ret = -ENOENT;
8880         struct sk_filter *filter;
8881
8882         if (sock_flag(sk, SOCK_FILTER_LOCKED))
8883                 return -EPERM;
8884
8885         filter = rcu_dereference_protected(sk->sk_filter,
8886                                            lockdep_sock_is_held(sk));
8887         if (filter) {
8888                 RCU_INIT_POINTER(sk->sk_filter, NULL);
8889                 sk_filter_uncharge(sk, filter);
8890                 ret = 0;
8891         }
8892
8893         return ret;
8894 }
8895 EXPORT_SYMBOL_GPL(sk_detach_filter);
8896
8897 int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
8898                   unsigned int len)
8899 {
8900         struct sock_fprog_kern *fprog;
8901         struct sk_filter *filter;
8902         int ret = 0;
8903
8904         lock_sock(sk);
8905         filter = rcu_dereference_protected(sk->sk_filter,
8906                                            lockdep_sock_is_held(sk));
8907         if (!filter)
8908                 goto out;
8909
8910         /* We're copying the filter that has been originally attached,
8911          * so no conversion/decode needed anymore. eBPF programs that
8912          * have no original program cannot be dumped through this.
8913          */
8914         ret = -EACCES;
8915         fprog = filter->prog->orig_prog;
8916         if (!fprog)
8917                 goto out;
8918
8919         ret = fprog->len;
8920         if (!len)
8921                 /* User space only enquires number of filter blocks. */
8922                 goto out;
8923
8924         ret = -EINVAL;
8925         if (len < fprog->len)
8926                 goto out;
8927
8928         ret = -EFAULT;
8929         if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
8930                 goto out;
8931
8932         /* Instead of bytes, the API requests to return the number
8933          * of filter blocks.
8934          */
8935         ret = fprog->len;
8936 out:
8937         release_sock(sk);
8938         return ret;
8939 }
8940
8941 #ifdef CONFIG_INET
8942 static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,
8943                                     struct sock_reuseport *reuse,
8944                                     struct sock *sk, struct sk_buff *skb,
8945                                     u32 hash)
8946 {
8947         reuse_kern->skb = skb;
8948         reuse_kern->sk = sk;
8949         reuse_kern->selected_sk = NULL;
8950         reuse_kern->data_end = skb->data + skb_headlen(skb);
8951         reuse_kern->hash = hash;
8952         reuse_kern->reuseport_id = reuse->reuseport_id;
8953         reuse_kern->bind_inany = reuse->bind_inany;
8954 }
8955
8956 struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,
8957                                   struct bpf_prog *prog, struct sk_buff *skb,
8958                                   u32 hash)
8959 {
8960         struct sk_reuseport_kern reuse_kern;
8961         enum sk_action action;
8962
8963         bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, hash);
8964         action = BPF_PROG_RUN(prog, &reuse_kern);
8965
8966         if (action == SK_PASS)
8967                 return reuse_kern.selected_sk;
8968         else
8969                 return ERR_PTR(-ECONNREFUSED);
8970 }
8971
8972 BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern,
8973            struct bpf_map *, map, void *, key, u32, flags)
8974 {
8975         bool is_sockarray = map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY;
8976         struct sock_reuseport *reuse;
8977         struct sock *selected_sk;
8978
8979         selected_sk = map->ops->map_lookup_elem(map, key);
8980         if (!selected_sk)
8981                 return -ENOENT;
8982
8983         reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
8984         if (!reuse) {
8985                 /* Lookup in sock_map can return TCP ESTABLISHED sockets. */
8986                 if (sk_is_refcounted(selected_sk))
8987                         sock_put(selected_sk);
8988
8989                 /* reuseport_array has only sk with non NULL sk_reuseport_cb.
8990                  * The only (!reuse) case here is - the sk has already been
8991                  * unhashed (e.g. by close()), so treat it as -ENOENT.
8992                  *
8993                  * Other maps (e.g. sock_map) do not provide this guarantee and
8994                  * the sk may never be in the reuseport group to begin with.
8995                  */
8996                 return is_sockarray ? -ENOENT : -EINVAL;
8997         }
8998
8999         if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
9000                 struct sock *sk = reuse_kern->sk;
9001
9002                 if (sk->sk_protocol != selected_sk->sk_protocol)
9003                         return -EPROTOTYPE;
9004                 else if (sk->sk_family != selected_sk->sk_family)
9005                         return -EAFNOSUPPORT;
9006
9007                 /* Catch all. Likely bound to a different sockaddr. */
9008                 return -EBADFD;
9009         }
9010
9011         reuse_kern->selected_sk = selected_sk;
9012
9013         return 0;
9014 }
9015
9016 static const struct bpf_func_proto sk_select_reuseport_proto = {
9017         .func           = sk_select_reuseport,
9018         .gpl_only       = false,
9019         .ret_type       = RET_INTEGER,
9020         .arg1_type      = ARG_PTR_TO_CTX,
9021         .arg2_type      = ARG_CONST_MAP_PTR,
9022         .arg3_type      = ARG_PTR_TO_MAP_KEY,
9023         .arg4_type      = ARG_ANYTHING,
9024 };
9025
9026 BPF_CALL_4(sk_reuseport_load_bytes,
9027            const struct sk_reuseport_kern *, reuse_kern, u32, offset,
9028            void *, to, u32, len)
9029 {
9030         return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
9031 }
9032
9033 static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
9034         .func           = sk_reuseport_load_bytes,
9035         .gpl_only       = false,
9036         .ret_type       = RET_INTEGER,
9037         .arg1_type      = ARG_PTR_TO_CTX,
9038         .arg2_type      = ARG_ANYTHING,
9039         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
9040         .arg4_type      = ARG_CONST_SIZE,
9041 };
9042
9043 BPF_CALL_5(sk_reuseport_load_bytes_relative,
9044            const struct sk_reuseport_kern *, reuse_kern, u32, offset,
9045            void *, to, u32, len, u32, start_header)
9046 {
9047         return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
9048                                                len, start_header);
9049 }
9050
9051 static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
9052         .func           = sk_reuseport_load_bytes_relative,
9053         .gpl_only       = false,
9054         .ret_type       = RET_INTEGER,
9055         .arg1_type      = ARG_PTR_TO_CTX,
9056         .arg2_type      = ARG_ANYTHING,
9057         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
9058         .arg4_type      = ARG_CONST_SIZE,
9059         .arg5_type      = ARG_ANYTHING,
9060 };
9061
9062 static const struct bpf_func_proto *
9063 sk_reuseport_func_proto(enum bpf_func_id func_id,
9064                         const struct bpf_prog *prog)
9065 {
9066         switch (func_id) {
9067         case BPF_FUNC_sk_select_reuseport:
9068                 return &sk_select_reuseport_proto;
9069         case BPF_FUNC_skb_load_bytes:
9070                 return &sk_reuseport_load_bytes_proto;
9071         case BPF_FUNC_skb_load_bytes_relative:
9072                 return &sk_reuseport_load_bytes_relative_proto;
9073         default:
9074                 return bpf_base_func_proto(func_id);
9075         }
9076 }
9077
9078 static bool
9079 sk_reuseport_is_valid_access(int off, int size,
9080                              enum bpf_access_type type,
9081                              const struct bpf_prog *prog,
9082                              struct bpf_insn_access_aux *info)
9083 {
9084         const u32 size_default = sizeof(__u32);
9085
9086         if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
9087             off % size || type != BPF_READ)
9088                 return false;
9089
9090         switch (off) {
9091         case offsetof(struct sk_reuseport_md, data):
9092                 info->reg_type = PTR_TO_PACKET;
9093                 return size == sizeof(__u64);
9094
9095         case offsetof(struct sk_reuseport_md, data_end):
9096                 info->reg_type = PTR_TO_PACKET_END;
9097                 return size == sizeof(__u64);
9098
9099         case offsetof(struct sk_reuseport_md, hash):
9100                 return size == size_default;
9101
9102         /* Fields that allow narrowing */
9103         case bpf_ctx_range(struct sk_reuseport_md, eth_protocol):
9104                 if (size < sizeof_field(struct sk_buff, protocol))
9105                         return false;
9106                 /* fall through */
9107         case bpf_ctx_range(struct sk_reuseport_md, ip_protocol):
9108         case bpf_ctx_range(struct sk_reuseport_md, bind_inany):
9109         case bpf_ctx_range(struct sk_reuseport_md, len):
9110                 bpf_ctx_record_field_size(info, size_default);
9111                 return bpf_ctx_narrow_access_ok(off, size, size_default);
9112
9113         default:
9114                 return false;
9115         }
9116 }
9117
9118 #define SK_REUSEPORT_LOAD_FIELD(F) ({                                   \
9119         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
9120                               si->dst_reg, si->src_reg,                 \
9121                               bpf_target_off(struct sk_reuseport_kern, F, \
9122                                              sizeof_field(struct sk_reuseport_kern, F), \
9123                                              target_size));             \
9124         })
9125
9126 #define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)                          \
9127         SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,           \
9128                                     struct sk_buff,                     \
9129                                     skb,                                \
9130                                     SKB_FIELD)
9131
9132 #define SK_REUSEPORT_LOAD_SK_FIELD(SK_FIELD)                            \
9133         SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,           \
9134                                     struct sock,                        \
9135                                     sk,                                 \
9136                                     SK_FIELD)
9137
9138 static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
9139                                            const struct bpf_insn *si,
9140                                            struct bpf_insn *insn_buf,
9141                                            struct bpf_prog *prog,
9142                                            u32 *target_size)
9143 {
9144         struct bpf_insn *insn = insn_buf;
9145
9146         switch (si->off) {
9147         case offsetof(struct sk_reuseport_md, data):
9148                 SK_REUSEPORT_LOAD_SKB_FIELD(data);
9149                 break;
9150
9151         case offsetof(struct sk_reuseport_md, len):
9152                 SK_REUSEPORT_LOAD_SKB_FIELD(len);
9153                 break;
9154
9155         case offsetof(struct sk_reuseport_md, eth_protocol):
9156                 SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
9157                 break;
9158
9159         case offsetof(struct sk_reuseport_md, ip_protocol):
9160                 SK_REUSEPORT_LOAD_SK_FIELD(sk_protocol);
9161                 break;
9162
9163         case offsetof(struct sk_reuseport_md, data_end):
9164                 SK_REUSEPORT_LOAD_FIELD(data_end);
9165                 break;
9166
9167         case offsetof(struct sk_reuseport_md, hash):
9168                 SK_REUSEPORT_LOAD_FIELD(hash);
9169                 break;
9170
9171         case offsetof(struct sk_reuseport_md, bind_inany):
9172                 SK_REUSEPORT_LOAD_FIELD(bind_inany);
9173                 break;
9174         }
9175
9176         return insn - insn_buf;
9177 }
9178
9179 const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
9180         .get_func_proto         = sk_reuseport_func_proto,
9181         .is_valid_access        = sk_reuseport_is_valid_access,
9182         .convert_ctx_access     = sk_reuseport_convert_ctx_access,
9183 };
9184
9185 const struct bpf_prog_ops sk_reuseport_prog_ops = {
9186 };
9187 #endif /* CONFIG_INET */
9188
9189 DEFINE_BPF_DISPATCHER(xdp)
9190
9191 void bpf_prog_change_xdp(struct bpf_prog *prev_prog, struct bpf_prog *prog)
9192 {
9193         bpf_dispatcher_change_prog(BPF_DISPATCHER_PTR(xdp), prev_prog, prog);
9194 }