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