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