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