f2777dc0b6249cdaab6b0f736510f73d190ece96
[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_SOCK_CGROUP_DATA
5923         case BPF_FUNC_skb_cgroup_id:
5924                 return &bpf_skb_cgroup_id_proto;
5925 #endif
5926 #ifdef CONFIG_INET
5927         case BPF_FUNC_tcp_sock:
5928                 return &bpf_tcp_sock_proto;
5929         case BPF_FUNC_get_listener_sock:
5930                 return &bpf_get_listener_sock_proto;
5931         case BPF_FUNC_skb_ecn_set_ce:
5932                 return &bpf_skb_ecn_set_ce_proto;
5933 #endif
5934         default:
5935                 return sk_filter_func_proto(func_id, prog);
5936         }
5937 }
5938
5939 static const struct bpf_func_proto *
5940 tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5941 {
5942         switch (func_id) {
5943         case BPF_FUNC_skb_store_bytes:
5944                 return &bpf_skb_store_bytes_proto;
5945         case BPF_FUNC_skb_load_bytes:
5946                 return &bpf_skb_load_bytes_proto;
5947         case BPF_FUNC_skb_load_bytes_relative:
5948                 return &bpf_skb_load_bytes_relative_proto;
5949         case BPF_FUNC_skb_pull_data:
5950                 return &bpf_skb_pull_data_proto;
5951         case BPF_FUNC_csum_diff:
5952                 return &bpf_csum_diff_proto;
5953         case BPF_FUNC_csum_update:
5954                 return &bpf_csum_update_proto;
5955         case BPF_FUNC_l3_csum_replace:
5956                 return &bpf_l3_csum_replace_proto;
5957         case BPF_FUNC_l4_csum_replace:
5958                 return &bpf_l4_csum_replace_proto;
5959         case BPF_FUNC_clone_redirect:
5960                 return &bpf_clone_redirect_proto;
5961         case BPF_FUNC_get_cgroup_classid:
5962                 return &bpf_get_cgroup_classid_proto;
5963         case BPF_FUNC_skb_vlan_push:
5964                 return &bpf_skb_vlan_push_proto;
5965         case BPF_FUNC_skb_vlan_pop:
5966                 return &bpf_skb_vlan_pop_proto;
5967         case BPF_FUNC_skb_change_proto:
5968                 return &bpf_skb_change_proto_proto;
5969         case BPF_FUNC_skb_change_type:
5970                 return &bpf_skb_change_type_proto;
5971         case BPF_FUNC_skb_adjust_room:
5972                 return &bpf_skb_adjust_room_proto;
5973         case BPF_FUNC_skb_change_tail:
5974                 return &bpf_skb_change_tail_proto;
5975         case BPF_FUNC_skb_get_tunnel_key:
5976                 return &bpf_skb_get_tunnel_key_proto;
5977         case BPF_FUNC_skb_set_tunnel_key:
5978                 return bpf_get_skb_set_tunnel_proto(func_id);
5979         case BPF_FUNC_skb_get_tunnel_opt:
5980                 return &bpf_skb_get_tunnel_opt_proto;
5981         case BPF_FUNC_skb_set_tunnel_opt:
5982                 return bpf_get_skb_set_tunnel_proto(func_id);
5983         case BPF_FUNC_redirect:
5984                 return &bpf_redirect_proto;
5985         case BPF_FUNC_get_route_realm:
5986                 return &bpf_get_route_realm_proto;
5987         case BPF_FUNC_get_hash_recalc:
5988                 return &bpf_get_hash_recalc_proto;
5989         case BPF_FUNC_set_hash_invalid:
5990                 return &bpf_set_hash_invalid_proto;
5991         case BPF_FUNC_set_hash:
5992                 return &bpf_set_hash_proto;
5993         case BPF_FUNC_perf_event_output:
5994                 return &bpf_skb_event_output_proto;
5995         case BPF_FUNC_get_smp_processor_id:
5996                 return &bpf_get_smp_processor_id_proto;
5997         case BPF_FUNC_skb_under_cgroup:
5998                 return &bpf_skb_under_cgroup_proto;
5999         case BPF_FUNC_get_socket_cookie:
6000                 return &bpf_get_socket_cookie_proto;
6001         case BPF_FUNC_get_socket_uid:
6002                 return &bpf_get_socket_uid_proto;
6003         case BPF_FUNC_fib_lookup:
6004                 return &bpf_skb_fib_lookup_proto;
6005         case BPF_FUNC_sk_fullsock:
6006                 return &bpf_sk_fullsock_proto;
6007         case BPF_FUNC_sk_storage_get:
6008                 return &bpf_sk_storage_get_proto;
6009         case BPF_FUNC_sk_storage_delete:
6010                 return &bpf_sk_storage_delete_proto;
6011 #ifdef CONFIG_XFRM
6012         case BPF_FUNC_skb_get_xfrm_state:
6013                 return &bpf_skb_get_xfrm_state_proto;
6014 #endif
6015 #ifdef CONFIG_SOCK_CGROUP_DATA
6016         case BPF_FUNC_skb_cgroup_id:
6017                 return &bpf_skb_cgroup_id_proto;
6018         case BPF_FUNC_skb_ancestor_cgroup_id:
6019                 return &bpf_skb_ancestor_cgroup_id_proto;
6020 #endif
6021 #ifdef CONFIG_INET
6022         case BPF_FUNC_sk_lookup_tcp:
6023                 return &bpf_sk_lookup_tcp_proto;
6024         case BPF_FUNC_sk_lookup_udp:
6025                 return &bpf_sk_lookup_udp_proto;
6026         case BPF_FUNC_sk_release:
6027                 return &bpf_sk_release_proto;
6028         case BPF_FUNC_tcp_sock:
6029                 return &bpf_tcp_sock_proto;
6030         case BPF_FUNC_get_listener_sock:
6031                 return &bpf_get_listener_sock_proto;
6032         case BPF_FUNC_skc_lookup_tcp:
6033                 return &bpf_skc_lookup_tcp_proto;
6034         case BPF_FUNC_tcp_check_syncookie:
6035                 return &bpf_tcp_check_syncookie_proto;
6036         case BPF_FUNC_skb_ecn_set_ce:
6037                 return &bpf_skb_ecn_set_ce_proto;
6038 #endif
6039         default:
6040                 return bpf_base_func_proto(func_id);
6041         }
6042 }
6043
6044 static const struct bpf_func_proto *
6045 xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6046 {
6047         switch (func_id) {
6048         case BPF_FUNC_perf_event_output:
6049                 return &bpf_xdp_event_output_proto;
6050         case BPF_FUNC_get_smp_processor_id:
6051                 return &bpf_get_smp_processor_id_proto;
6052         case BPF_FUNC_csum_diff:
6053                 return &bpf_csum_diff_proto;
6054         case BPF_FUNC_xdp_adjust_head:
6055                 return &bpf_xdp_adjust_head_proto;
6056         case BPF_FUNC_xdp_adjust_meta:
6057                 return &bpf_xdp_adjust_meta_proto;
6058         case BPF_FUNC_redirect:
6059                 return &bpf_xdp_redirect_proto;
6060         case BPF_FUNC_redirect_map:
6061                 return &bpf_xdp_redirect_map_proto;
6062         case BPF_FUNC_xdp_adjust_tail:
6063                 return &bpf_xdp_adjust_tail_proto;
6064         case BPF_FUNC_fib_lookup:
6065                 return &bpf_xdp_fib_lookup_proto;
6066 #ifdef CONFIG_INET
6067         case BPF_FUNC_sk_lookup_udp:
6068                 return &bpf_xdp_sk_lookup_udp_proto;
6069         case BPF_FUNC_sk_lookup_tcp:
6070                 return &bpf_xdp_sk_lookup_tcp_proto;
6071         case BPF_FUNC_sk_release:
6072                 return &bpf_sk_release_proto;
6073         case BPF_FUNC_skc_lookup_tcp:
6074                 return &bpf_xdp_skc_lookup_tcp_proto;
6075         case BPF_FUNC_tcp_check_syncookie:
6076                 return &bpf_tcp_check_syncookie_proto;
6077 #endif
6078         default:
6079                 return bpf_base_func_proto(func_id);
6080         }
6081 }
6082
6083 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
6084 const struct bpf_func_proto bpf_sock_hash_update_proto __weak;
6085
6086 static const struct bpf_func_proto *
6087 sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6088 {
6089         switch (func_id) {
6090         case BPF_FUNC_setsockopt:
6091                 return &bpf_setsockopt_proto;
6092         case BPF_FUNC_getsockopt:
6093                 return &bpf_getsockopt_proto;
6094         case BPF_FUNC_sock_ops_cb_flags_set:
6095                 return &bpf_sock_ops_cb_flags_set_proto;
6096         case BPF_FUNC_sock_map_update:
6097                 return &bpf_sock_map_update_proto;
6098         case BPF_FUNC_sock_hash_update:
6099                 return &bpf_sock_hash_update_proto;
6100         case BPF_FUNC_get_socket_cookie:
6101                 return &bpf_get_socket_cookie_sock_ops_proto;
6102         case BPF_FUNC_get_local_storage:
6103                 return &bpf_get_local_storage_proto;
6104         case BPF_FUNC_perf_event_output:
6105                 return &bpf_sockopt_event_output_proto;
6106         default:
6107                 return bpf_base_func_proto(func_id);
6108         }
6109 }
6110
6111 const struct bpf_func_proto bpf_msg_redirect_map_proto __weak;
6112 const struct bpf_func_proto bpf_msg_redirect_hash_proto __weak;
6113
6114 static const struct bpf_func_proto *
6115 sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6116 {
6117         switch (func_id) {
6118         case BPF_FUNC_msg_redirect_map:
6119                 return &bpf_msg_redirect_map_proto;
6120         case BPF_FUNC_msg_redirect_hash:
6121                 return &bpf_msg_redirect_hash_proto;
6122         case BPF_FUNC_msg_apply_bytes:
6123                 return &bpf_msg_apply_bytes_proto;
6124         case BPF_FUNC_msg_cork_bytes:
6125                 return &bpf_msg_cork_bytes_proto;
6126         case BPF_FUNC_msg_pull_data:
6127                 return &bpf_msg_pull_data_proto;
6128         case BPF_FUNC_msg_push_data:
6129                 return &bpf_msg_push_data_proto;
6130         case BPF_FUNC_msg_pop_data:
6131                 return &bpf_msg_pop_data_proto;
6132         default:
6133                 return bpf_base_func_proto(func_id);
6134         }
6135 }
6136
6137 const struct bpf_func_proto bpf_sk_redirect_map_proto __weak;
6138 const struct bpf_func_proto bpf_sk_redirect_hash_proto __weak;
6139
6140 static const struct bpf_func_proto *
6141 sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6142 {
6143         switch (func_id) {
6144         case BPF_FUNC_skb_store_bytes:
6145                 return &bpf_skb_store_bytes_proto;
6146         case BPF_FUNC_skb_load_bytes:
6147                 return &bpf_skb_load_bytes_proto;
6148         case BPF_FUNC_skb_pull_data:
6149                 return &sk_skb_pull_data_proto;
6150         case BPF_FUNC_skb_change_tail:
6151                 return &sk_skb_change_tail_proto;
6152         case BPF_FUNC_skb_change_head:
6153                 return &sk_skb_change_head_proto;
6154         case BPF_FUNC_get_socket_cookie:
6155                 return &bpf_get_socket_cookie_proto;
6156         case BPF_FUNC_get_socket_uid:
6157                 return &bpf_get_socket_uid_proto;
6158         case BPF_FUNC_sk_redirect_map:
6159                 return &bpf_sk_redirect_map_proto;
6160         case BPF_FUNC_sk_redirect_hash:
6161                 return &bpf_sk_redirect_hash_proto;
6162 #ifdef CONFIG_INET
6163         case BPF_FUNC_sk_lookup_tcp:
6164                 return &bpf_sk_lookup_tcp_proto;
6165         case BPF_FUNC_sk_lookup_udp:
6166                 return &bpf_sk_lookup_udp_proto;
6167         case BPF_FUNC_sk_release:
6168                 return &bpf_sk_release_proto;
6169         case BPF_FUNC_skc_lookup_tcp:
6170                 return &bpf_skc_lookup_tcp_proto;
6171 #endif
6172         default:
6173                 return bpf_base_func_proto(func_id);
6174         }
6175 }
6176
6177 static const struct bpf_func_proto *
6178 flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6179 {
6180         switch (func_id) {
6181         case BPF_FUNC_skb_load_bytes:
6182                 return &bpf_flow_dissector_load_bytes_proto;
6183         default:
6184                 return bpf_base_func_proto(func_id);
6185         }
6186 }
6187
6188 static const struct bpf_func_proto *
6189 lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6190 {
6191         switch (func_id) {
6192         case BPF_FUNC_skb_load_bytes:
6193                 return &bpf_skb_load_bytes_proto;
6194         case BPF_FUNC_skb_pull_data:
6195                 return &bpf_skb_pull_data_proto;
6196         case BPF_FUNC_csum_diff:
6197                 return &bpf_csum_diff_proto;
6198         case BPF_FUNC_get_cgroup_classid:
6199                 return &bpf_get_cgroup_classid_proto;
6200         case BPF_FUNC_get_route_realm:
6201                 return &bpf_get_route_realm_proto;
6202         case BPF_FUNC_get_hash_recalc:
6203                 return &bpf_get_hash_recalc_proto;
6204         case BPF_FUNC_perf_event_output:
6205                 return &bpf_skb_event_output_proto;
6206         case BPF_FUNC_get_smp_processor_id:
6207                 return &bpf_get_smp_processor_id_proto;
6208         case BPF_FUNC_skb_under_cgroup:
6209                 return &bpf_skb_under_cgroup_proto;
6210         default:
6211                 return bpf_base_func_proto(func_id);
6212         }
6213 }
6214
6215 static const struct bpf_func_proto *
6216 lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6217 {
6218         switch (func_id) {
6219         case BPF_FUNC_lwt_push_encap:
6220                 return &bpf_lwt_in_push_encap_proto;
6221         default:
6222                 return lwt_out_func_proto(func_id, prog);
6223         }
6224 }
6225
6226 static const struct bpf_func_proto *
6227 lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6228 {
6229         switch (func_id) {
6230         case BPF_FUNC_skb_get_tunnel_key:
6231                 return &bpf_skb_get_tunnel_key_proto;
6232         case BPF_FUNC_skb_set_tunnel_key:
6233                 return bpf_get_skb_set_tunnel_proto(func_id);
6234         case BPF_FUNC_skb_get_tunnel_opt:
6235                 return &bpf_skb_get_tunnel_opt_proto;
6236         case BPF_FUNC_skb_set_tunnel_opt:
6237                 return bpf_get_skb_set_tunnel_proto(func_id);
6238         case BPF_FUNC_redirect:
6239                 return &bpf_redirect_proto;
6240         case BPF_FUNC_clone_redirect:
6241                 return &bpf_clone_redirect_proto;
6242         case BPF_FUNC_skb_change_tail:
6243                 return &bpf_skb_change_tail_proto;
6244         case BPF_FUNC_skb_change_head:
6245                 return &bpf_skb_change_head_proto;
6246         case BPF_FUNC_skb_store_bytes:
6247                 return &bpf_skb_store_bytes_proto;
6248         case BPF_FUNC_csum_update:
6249                 return &bpf_csum_update_proto;
6250         case BPF_FUNC_l3_csum_replace:
6251                 return &bpf_l3_csum_replace_proto;
6252         case BPF_FUNC_l4_csum_replace:
6253                 return &bpf_l4_csum_replace_proto;
6254         case BPF_FUNC_set_hash_invalid:
6255                 return &bpf_set_hash_invalid_proto;
6256         case BPF_FUNC_lwt_push_encap:
6257                 return &bpf_lwt_xmit_push_encap_proto;
6258         default:
6259                 return lwt_out_func_proto(func_id, prog);
6260         }
6261 }
6262
6263 static const struct bpf_func_proto *
6264 lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6265 {
6266         switch (func_id) {
6267 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6268         case BPF_FUNC_lwt_seg6_store_bytes:
6269                 return &bpf_lwt_seg6_store_bytes_proto;
6270         case BPF_FUNC_lwt_seg6_action:
6271                 return &bpf_lwt_seg6_action_proto;
6272         case BPF_FUNC_lwt_seg6_adjust_srh:
6273                 return &bpf_lwt_seg6_adjust_srh_proto;
6274 #endif
6275         default:
6276                 return lwt_out_func_proto(func_id, prog);
6277         }
6278 }
6279
6280 static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
6281                                     const struct bpf_prog *prog,
6282                                     struct bpf_insn_access_aux *info)
6283 {
6284         const int size_default = sizeof(__u32);
6285
6286         if (off < 0 || off >= sizeof(struct __sk_buff))
6287                 return false;
6288
6289         /* The verifier guarantees that size > 0. */
6290         if (off % size != 0)
6291                 return false;
6292
6293         switch (off) {
6294         case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6295                 if (off + size > offsetofend(struct __sk_buff, cb[4]))
6296                         return false;
6297                 break;
6298         case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
6299         case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
6300         case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
6301         case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
6302         case bpf_ctx_range(struct __sk_buff, data):
6303         case bpf_ctx_range(struct __sk_buff, data_meta):
6304         case bpf_ctx_range(struct __sk_buff, data_end):
6305                 if (size != size_default)
6306                         return false;
6307                 break;
6308         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6309                 return false;
6310         case bpf_ctx_range(struct __sk_buff, tstamp):
6311                 if (size != sizeof(__u64))
6312                         return false;
6313                 break;
6314         case offsetof(struct __sk_buff, sk):
6315                 if (type == BPF_WRITE || size != sizeof(__u64))
6316                         return false;
6317                 info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
6318                 break;
6319         default:
6320                 /* Only narrow read access allowed for now. */
6321                 if (type == BPF_WRITE) {
6322                         if (size != size_default)
6323                                 return false;
6324                 } else {
6325                         bpf_ctx_record_field_size(info, size_default);
6326                         if (!bpf_ctx_narrow_access_ok(off, size, size_default))
6327                                 return false;
6328                 }
6329         }
6330
6331         return true;
6332 }
6333
6334 static bool sk_filter_is_valid_access(int off, int size,
6335                                       enum bpf_access_type type,
6336                                       const struct bpf_prog *prog,
6337                                       struct bpf_insn_access_aux *info)
6338 {
6339         switch (off) {
6340         case bpf_ctx_range(struct __sk_buff, tc_classid):
6341         case bpf_ctx_range(struct __sk_buff, data):
6342         case bpf_ctx_range(struct __sk_buff, data_meta):
6343         case bpf_ctx_range(struct __sk_buff, data_end):
6344         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6345         case bpf_ctx_range(struct __sk_buff, tstamp):
6346         case bpf_ctx_range(struct __sk_buff, wire_len):
6347                 return false;
6348         }
6349
6350         if (type == BPF_WRITE) {
6351                 switch (off) {
6352                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6353                         break;
6354                 default:
6355                         return false;
6356                 }
6357         }
6358
6359         return bpf_skb_is_valid_access(off, size, type, prog, info);
6360 }
6361
6362 static bool cg_skb_is_valid_access(int off, int size,
6363                                    enum bpf_access_type type,
6364                                    const struct bpf_prog *prog,
6365                                    struct bpf_insn_access_aux *info)
6366 {
6367         switch (off) {
6368         case bpf_ctx_range(struct __sk_buff, tc_classid):
6369         case bpf_ctx_range(struct __sk_buff, data_meta):
6370         case bpf_ctx_range(struct __sk_buff, wire_len):
6371                 return false;
6372         case bpf_ctx_range(struct __sk_buff, data):
6373         case bpf_ctx_range(struct __sk_buff, data_end):
6374                 if (!capable(CAP_SYS_ADMIN))
6375                         return false;
6376                 break;
6377         }
6378
6379         if (type == BPF_WRITE) {
6380                 switch (off) {
6381                 case bpf_ctx_range(struct __sk_buff, mark):
6382                 case bpf_ctx_range(struct __sk_buff, priority):
6383                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6384                         break;
6385                 case bpf_ctx_range(struct __sk_buff, tstamp):
6386                         if (!capable(CAP_SYS_ADMIN))
6387                                 return false;
6388                         break;
6389                 default:
6390                         return false;
6391                 }
6392         }
6393
6394         switch (off) {
6395         case bpf_ctx_range(struct __sk_buff, data):
6396                 info->reg_type = PTR_TO_PACKET;
6397                 break;
6398         case bpf_ctx_range(struct __sk_buff, data_end):
6399                 info->reg_type = PTR_TO_PACKET_END;
6400                 break;
6401         }
6402
6403         return bpf_skb_is_valid_access(off, size, type, prog, info);
6404 }
6405
6406 static bool lwt_is_valid_access(int off, int size,
6407                                 enum bpf_access_type type,
6408                                 const struct bpf_prog *prog,
6409                                 struct bpf_insn_access_aux *info)
6410 {
6411         switch (off) {
6412         case bpf_ctx_range(struct __sk_buff, tc_classid):
6413         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6414         case bpf_ctx_range(struct __sk_buff, data_meta):
6415         case bpf_ctx_range(struct __sk_buff, tstamp):
6416         case bpf_ctx_range(struct __sk_buff, wire_len):
6417                 return false;
6418         }
6419
6420         if (type == BPF_WRITE) {
6421                 switch (off) {
6422                 case bpf_ctx_range(struct __sk_buff, mark):
6423                 case bpf_ctx_range(struct __sk_buff, priority):
6424                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6425                         break;
6426                 default:
6427                         return false;
6428                 }
6429         }
6430
6431         switch (off) {
6432         case bpf_ctx_range(struct __sk_buff, data):
6433                 info->reg_type = PTR_TO_PACKET;
6434                 break;
6435         case bpf_ctx_range(struct __sk_buff, data_end):
6436                 info->reg_type = PTR_TO_PACKET_END;
6437                 break;
6438         }
6439
6440         return bpf_skb_is_valid_access(off, size, type, prog, info);
6441 }
6442
6443 /* Attach type specific accesses */
6444 static bool __sock_filter_check_attach_type(int off,
6445                                             enum bpf_access_type access_type,
6446                                             enum bpf_attach_type attach_type)
6447 {
6448         switch (off) {
6449         case offsetof(struct bpf_sock, bound_dev_if):
6450         case offsetof(struct bpf_sock, mark):
6451         case offsetof(struct bpf_sock, priority):
6452                 switch (attach_type) {
6453                 case BPF_CGROUP_INET_SOCK_CREATE:
6454                         goto full_access;
6455                 default:
6456                         return false;
6457                 }
6458         case bpf_ctx_range(struct bpf_sock, src_ip4):
6459                 switch (attach_type) {
6460                 case BPF_CGROUP_INET4_POST_BIND:
6461                         goto read_only;
6462                 default:
6463                         return false;
6464                 }
6465         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6466                 switch (attach_type) {
6467                 case BPF_CGROUP_INET6_POST_BIND:
6468                         goto read_only;
6469                 default:
6470                         return false;
6471                 }
6472         case bpf_ctx_range(struct bpf_sock, src_port):
6473                 switch (attach_type) {
6474                 case BPF_CGROUP_INET4_POST_BIND:
6475                 case BPF_CGROUP_INET6_POST_BIND:
6476                         goto read_only;
6477                 default:
6478                         return false;
6479                 }
6480         }
6481 read_only:
6482         return access_type == BPF_READ;
6483 full_access:
6484         return true;
6485 }
6486
6487 bool bpf_sock_common_is_valid_access(int off, int size,
6488                                      enum bpf_access_type type,
6489                                      struct bpf_insn_access_aux *info)
6490 {
6491         switch (off) {
6492         case bpf_ctx_range_till(struct bpf_sock, type, priority):
6493                 return false;
6494         default:
6495                 return bpf_sock_is_valid_access(off, size, type, info);
6496         }
6497 }
6498
6499 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
6500                               struct bpf_insn_access_aux *info)
6501 {
6502         const int size_default = sizeof(__u32);
6503
6504         if (off < 0 || off >= sizeof(struct bpf_sock))
6505                 return false;
6506         if (off % size != 0)
6507                 return false;
6508
6509         switch (off) {
6510         case offsetof(struct bpf_sock, state):
6511         case offsetof(struct bpf_sock, family):
6512         case offsetof(struct bpf_sock, type):
6513         case offsetof(struct bpf_sock, protocol):
6514         case offsetof(struct bpf_sock, dst_port):
6515         case offsetof(struct bpf_sock, src_port):
6516         case bpf_ctx_range(struct bpf_sock, src_ip4):
6517         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6518         case bpf_ctx_range(struct bpf_sock, dst_ip4):
6519         case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
6520                 bpf_ctx_record_field_size(info, size_default);
6521                 return bpf_ctx_narrow_access_ok(off, size, size_default);
6522         }
6523
6524         return size == size_default;
6525 }
6526
6527 static bool sock_filter_is_valid_access(int off, int size,
6528                                         enum bpf_access_type type,
6529                                         const struct bpf_prog *prog,
6530                                         struct bpf_insn_access_aux *info)
6531 {
6532         if (!bpf_sock_is_valid_access(off, size, type, info))
6533                 return false;
6534         return __sock_filter_check_attach_type(off, type,
6535                                                prog->expected_attach_type);
6536 }
6537
6538 static int bpf_noop_prologue(struct bpf_insn *insn_buf, bool direct_write,
6539                              const struct bpf_prog *prog)
6540 {
6541         /* Neither direct read nor direct write requires any preliminary
6542          * action.
6543          */
6544         return 0;
6545 }
6546
6547 static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
6548                                 const struct bpf_prog *prog, int drop_verdict)
6549 {
6550         struct bpf_insn *insn = insn_buf;
6551
6552         if (!direct_write)
6553                 return 0;
6554
6555         /* if (!skb->cloned)
6556          *       goto start;
6557          *
6558          * (Fast-path, otherwise approximation that we might be
6559          *  a clone, do the rest in helper.)
6560          */
6561         *insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET());
6562         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
6563         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
6564
6565         /* ret = bpf_skb_pull_data(skb, 0); */
6566         *insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
6567         *insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
6568         *insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
6569                                BPF_FUNC_skb_pull_data);
6570         /* if (!ret)
6571          *      goto restore;
6572          * return TC_ACT_SHOT;
6573          */
6574         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
6575         *insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
6576         *insn++ = BPF_EXIT_INSN();
6577
6578         /* restore: */
6579         *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
6580         /* start: */
6581         *insn++ = prog->insnsi[0];
6582
6583         return insn - insn_buf;
6584 }
6585
6586 static int bpf_gen_ld_abs(const struct bpf_insn *orig,
6587                           struct bpf_insn *insn_buf)
6588 {
6589         bool indirect = BPF_MODE(orig->code) == BPF_IND;
6590         struct bpf_insn *insn = insn_buf;
6591
6592         /* We're guaranteed here that CTX is in R6. */
6593         *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
6594         if (!indirect) {
6595                 *insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
6596         } else {
6597                 *insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
6598                 if (orig->imm)
6599                         *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
6600         }
6601
6602         switch (BPF_SIZE(orig->code)) {
6603         case BPF_B:
6604                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
6605                 break;
6606         case BPF_H:
6607                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
6608                 break;
6609         case BPF_W:
6610                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
6611                 break;
6612         }
6613
6614         *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
6615         *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
6616         *insn++ = BPF_EXIT_INSN();
6617
6618         return insn - insn_buf;
6619 }
6620
6621 static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
6622                                const struct bpf_prog *prog)
6623 {
6624         return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
6625 }
6626
6627 static bool tc_cls_act_is_valid_access(int off, int size,
6628                                        enum bpf_access_type type,
6629                                        const struct bpf_prog *prog,
6630                                        struct bpf_insn_access_aux *info)
6631 {
6632         if (type == BPF_WRITE) {
6633                 switch (off) {
6634                 case bpf_ctx_range(struct __sk_buff, mark):
6635                 case bpf_ctx_range(struct __sk_buff, tc_index):
6636                 case bpf_ctx_range(struct __sk_buff, priority):
6637                 case bpf_ctx_range(struct __sk_buff, tc_classid):
6638                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6639                 case bpf_ctx_range(struct __sk_buff, tstamp):
6640                 case bpf_ctx_range(struct __sk_buff, queue_mapping):
6641                         break;
6642                 default:
6643                         return false;
6644                 }
6645         }
6646
6647         switch (off) {
6648         case bpf_ctx_range(struct __sk_buff, data):
6649                 info->reg_type = PTR_TO_PACKET;
6650                 break;
6651         case bpf_ctx_range(struct __sk_buff, data_meta):
6652                 info->reg_type = PTR_TO_PACKET_META;
6653                 break;
6654         case bpf_ctx_range(struct __sk_buff, data_end):
6655                 info->reg_type = PTR_TO_PACKET_END;
6656                 break;
6657         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6658                 return false;
6659         }
6660
6661         return bpf_skb_is_valid_access(off, size, type, prog, info);
6662 }
6663
6664 static bool __is_valid_xdp_access(int off, int size)
6665 {
6666         if (off < 0 || off >= sizeof(struct xdp_md))
6667                 return false;
6668         if (off % size != 0)
6669                 return false;
6670         if (size != sizeof(__u32))
6671                 return false;
6672
6673         return true;
6674 }
6675
6676 static bool xdp_is_valid_access(int off, int size,
6677                                 enum bpf_access_type type,
6678                                 const struct bpf_prog *prog,
6679                                 struct bpf_insn_access_aux *info)
6680 {
6681         if (type == BPF_WRITE) {
6682                 if (bpf_prog_is_dev_bound(prog->aux)) {
6683                         switch (off) {
6684                         case offsetof(struct xdp_md, rx_queue_index):
6685                                 return __is_valid_xdp_access(off, size);
6686                         }
6687                 }
6688                 return false;
6689         }
6690
6691         switch (off) {
6692         case offsetof(struct xdp_md, data):
6693                 info->reg_type = PTR_TO_PACKET;
6694                 break;
6695         case offsetof(struct xdp_md, data_meta):
6696                 info->reg_type = PTR_TO_PACKET_META;
6697                 break;
6698         case offsetof(struct xdp_md, data_end):
6699                 info->reg_type = PTR_TO_PACKET_END;
6700                 break;
6701         }
6702
6703         return __is_valid_xdp_access(off, size);
6704 }
6705
6706 void bpf_warn_invalid_xdp_action(u32 act)
6707 {
6708         const u32 act_max = XDP_REDIRECT;
6709
6710         WARN_ONCE(1, "%s XDP return value %u, expect packet loss!\n",
6711                   act > act_max ? "Illegal" : "Driver unsupported",
6712                   act);
6713 }
6714 EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
6715
6716 static bool sock_addr_is_valid_access(int off, int size,
6717                                       enum bpf_access_type type,
6718                                       const struct bpf_prog *prog,
6719                                       struct bpf_insn_access_aux *info)
6720 {
6721         const int size_default = sizeof(__u32);
6722
6723         if (off < 0 || off >= sizeof(struct bpf_sock_addr))
6724                 return false;
6725         if (off % size != 0)
6726                 return false;
6727
6728         /* Disallow access to IPv6 fields from IPv4 contex and vise
6729          * versa.
6730          */
6731         switch (off) {
6732         case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
6733                 switch (prog->expected_attach_type) {
6734                 case BPF_CGROUP_INET4_BIND:
6735                 case BPF_CGROUP_INET4_CONNECT:
6736                 case BPF_CGROUP_UDP4_SENDMSG:
6737                         break;
6738                 default:
6739                         return false;
6740                 }
6741                 break;
6742         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
6743                 switch (prog->expected_attach_type) {
6744                 case BPF_CGROUP_INET6_BIND:
6745                 case BPF_CGROUP_INET6_CONNECT:
6746                 case BPF_CGROUP_UDP6_SENDMSG:
6747                         break;
6748                 default:
6749                         return false;
6750                 }
6751                 break;
6752         case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
6753                 switch (prog->expected_attach_type) {
6754                 case BPF_CGROUP_UDP4_SENDMSG:
6755                         break;
6756                 default:
6757                         return false;
6758                 }
6759                 break;
6760         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
6761                                 msg_src_ip6[3]):
6762                 switch (prog->expected_attach_type) {
6763                 case BPF_CGROUP_UDP6_SENDMSG:
6764                         break;
6765                 default:
6766                         return false;
6767                 }
6768                 break;
6769         }
6770
6771         switch (off) {
6772         case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
6773         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
6774         case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
6775         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
6776                                 msg_src_ip6[3]):
6777                 /* Only narrow read access allowed for now. */
6778                 if (type == BPF_READ) {
6779                         bpf_ctx_record_field_size(info, size_default);
6780                         if (!bpf_ctx_narrow_access_ok(off, size, size_default))
6781                                 return false;
6782                 } else {
6783                         if (size != size_default)
6784                                 return false;
6785                 }
6786                 break;
6787         case bpf_ctx_range(struct bpf_sock_addr, user_port):
6788                 if (size != size_default)
6789                         return false;
6790                 break;
6791         default:
6792                 if (type == BPF_READ) {
6793                         if (size != size_default)
6794                                 return false;
6795                 } else {
6796                         return false;
6797                 }
6798         }
6799
6800         return true;
6801 }
6802
6803 static bool sock_ops_is_valid_access(int off, int size,
6804                                      enum bpf_access_type type,
6805                                      const struct bpf_prog *prog,
6806                                      struct bpf_insn_access_aux *info)
6807 {
6808         const int size_default = sizeof(__u32);
6809
6810         if (off < 0 || off >= sizeof(struct bpf_sock_ops))
6811                 return false;
6812
6813         /* The verifier guarantees that size > 0. */
6814         if (off % size != 0)
6815                 return false;
6816
6817         if (type == BPF_WRITE) {
6818                 switch (off) {
6819                 case offsetof(struct bpf_sock_ops, reply):
6820                 case offsetof(struct bpf_sock_ops, sk_txhash):
6821                         if (size != size_default)
6822                                 return false;
6823                         break;
6824                 default:
6825                         return false;
6826                 }
6827         } else {
6828                 switch (off) {
6829                 case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received,
6830                                         bytes_acked):
6831                         if (size != sizeof(__u64))
6832                                 return false;
6833                         break;
6834                 default:
6835                         if (size != size_default)
6836                                 return false;
6837                         break;
6838                 }
6839         }
6840
6841         return true;
6842 }
6843
6844 static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
6845                            const struct bpf_prog *prog)
6846 {
6847         return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
6848 }
6849
6850 static bool sk_skb_is_valid_access(int off, int size,
6851                                    enum bpf_access_type type,
6852                                    const struct bpf_prog *prog,
6853                                    struct bpf_insn_access_aux *info)
6854 {
6855         switch (off) {
6856         case bpf_ctx_range(struct __sk_buff, tc_classid):
6857         case bpf_ctx_range(struct __sk_buff, data_meta):
6858         case bpf_ctx_range(struct __sk_buff, tstamp):
6859         case bpf_ctx_range(struct __sk_buff, wire_len):
6860                 return false;
6861         }
6862
6863         if (type == BPF_WRITE) {
6864                 switch (off) {
6865                 case bpf_ctx_range(struct __sk_buff, tc_index):
6866                 case bpf_ctx_range(struct __sk_buff, priority):
6867                         break;
6868                 default:
6869                         return false;
6870                 }
6871         }
6872
6873         switch (off) {
6874         case bpf_ctx_range(struct __sk_buff, mark):
6875                 return false;
6876         case bpf_ctx_range(struct __sk_buff, data):
6877                 info->reg_type = PTR_TO_PACKET;
6878                 break;
6879         case bpf_ctx_range(struct __sk_buff, data_end):
6880                 info->reg_type = PTR_TO_PACKET_END;
6881                 break;
6882         }
6883
6884         return bpf_skb_is_valid_access(off, size, type, prog, info);
6885 }
6886
6887 static bool sk_msg_is_valid_access(int off, int size,
6888                                    enum bpf_access_type type,
6889                                    const struct bpf_prog *prog,
6890                                    struct bpf_insn_access_aux *info)
6891 {
6892         if (type == BPF_WRITE)
6893                 return false;
6894
6895         if (off % size != 0)
6896                 return false;
6897
6898         switch (off) {
6899         case offsetof(struct sk_msg_md, data):
6900                 info->reg_type = PTR_TO_PACKET;
6901                 if (size != sizeof(__u64))
6902                         return false;
6903                 break;
6904         case offsetof(struct sk_msg_md, data_end):
6905                 info->reg_type = PTR_TO_PACKET_END;
6906                 if (size != sizeof(__u64))
6907                         return false;
6908                 break;
6909         case bpf_ctx_range(struct sk_msg_md, family):
6910         case bpf_ctx_range(struct sk_msg_md, remote_ip4):
6911         case bpf_ctx_range(struct sk_msg_md, local_ip4):
6912         case bpf_ctx_range_till(struct sk_msg_md, remote_ip6[0], remote_ip6[3]):
6913         case bpf_ctx_range_till(struct sk_msg_md, local_ip6[0], local_ip6[3]):
6914         case bpf_ctx_range(struct sk_msg_md, remote_port):
6915         case bpf_ctx_range(struct sk_msg_md, local_port):
6916         case bpf_ctx_range(struct sk_msg_md, size):
6917                 if (size != sizeof(__u32))
6918                         return false;
6919                 break;
6920         default:
6921                 return false;
6922         }
6923         return true;
6924 }
6925
6926 static bool flow_dissector_is_valid_access(int off, int size,
6927                                            enum bpf_access_type type,
6928                                            const struct bpf_prog *prog,
6929                                            struct bpf_insn_access_aux *info)
6930 {
6931         const int size_default = sizeof(__u32);
6932
6933         if (off < 0 || off >= sizeof(struct __sk_buff))
6934                 return false;
6935
6936         if (type == BPF_WRITE)
6937                 return false;
6938
6939         switch (off) {
6940         case bpf_ctx_range(struct __sk_buff, data):
6941                 if (size != size_default)
6942                         return false;
6943                 info->reg_type = PTR_TO_PACKET;
6944                 return true;
6945         case bpf_ctx_range(struct __sk_buff, data_end):
6946                 if (size != size_default)
6947                         return false;
6948                 info->reg_type = PTR_TO_PACKET_END;
6949                 return true;
6950         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6951                 if (size != sizeof(__u64))
6952                         return false;
6953                 info->reg_type = PTR_TO_FLOW_KEYS;
6954                 return true;
6955         default:
6956                 return false;
6957         }
6958 }
6959
6960 static u32 flow_dissector_convert_ctx_access(enum bpf_access_type type,
6961                                              const struct bpf_insn *si,
6962                                              struct bpf_insn *insn_buf,
6963                                              struct bpf_prog *prog,
6964                                              u32 *target_size)
6965
6966 {
6967         struct bpf_insn *insn = insn_buf;
6968
6969         switch (si->off) {
6970         case offsetof(struct __sk_buff, data):
6971                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data),
6972                                       si->dst_reg, si->src_reg,
6973                                       offsetof(struct bpf_flow_dissector, data));
6974                 break;
6975
6976         case offsetof(struct __sk_buff, data_end):
6977                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data_end),
6978                                       si->dst_reg, si->src_reg,
6979                                       offsetof(struct bpf_flow_dissector, data_end));
6980                 break;
6981
6982         case offsetof(struct __sk_buff, flow_keys):
6983                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, flow_keys),
6984                                       si->dst_reg, si->src_reg,
6985                                       offsetof(struct bpf_flow_dissector, flow_keys));
6986                 break;
6987         }
6988
6989         return insn - insn_buf;
6990 }
6991
6992 static u32 bpf_convert_ctx_access(enum bpf_access_type type,
6993                                   const struct bpf_insn *si,
6994                                   struct bpf_insn *insn_buf,
6995                                   struct bpf_prog *prog, u32 *target_size)
6996 {
6997         struct bpf_insn *insn = insn_buf;
6998         int off;
6999
7000         switch (si->off) {
7001         case offsetof(struct __sk_buff, len):
7002                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7003                                       bpf_target_off(struct sk_buff, len, 4,
7004                                                      target_size));
7005                 break;
7006
7007         case offsetof(struct __sk_buff, protocol):
7008                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7009                                       bpf_target_off(struct sk_buff, protocol, 2,
7010                                                      target_size));
7011                 break;
7012
7013         case offsetof(struct __sk_buff, vlan_proto):
7014                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7015                                       bpf_target_off(struct sk_buff, vlan_proto, 2,
7016                                                      target_size));
7017                 break;
7018
7019         case offsetof(struct __sk_buff, priority):
7020                 if (type == BPF_WRITE)
7021                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7022                                               bpf_target_off(struct sk_buff, priority, 4,
7023                                                              target_size));
7024                 else
7025                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7026                                               bpf_target_off(struct sk_buff, priority, 4,
7027                                                              target_size));
7028                 break;
7029
7030         case offsetof(struct __sk_buff, ingress_ifindex):
7031                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7032                                       bpf_target_off(struct sk_buff, skb_iif, 4,
7033                                                      target_size));
7034                 break;
7035
7036         case offsetof(struct __sk_buff, ifindex):
7037                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
7038                                       si->dst_reg, si->src_reg,
7039                                       offsetof(struct sk_buff, dev));
7040                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
7041                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7042                                       bpf_target_off(struct net_device, ifindex, 4,
7043                                                      target_size));
7044                 break;
7045
7046         case offsetof(struct __sk_buff, hash):
7047                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7048                                       bpf_target_off(struct sk_buff, hash, 4,
7049                                                      target_size));
7050                 break;
7051
7052         case offsetof(struct __sk_buff, mark):
7053                 if (type == BPF_WRITE)
7054                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7055                                               bpf_target_off(struct sk_buff, mark, 4,
7056                                                              target_size));
7057                 else
7058                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7059                                               bpf_target_off(struct sk_buff, mark, 4,
7060                                                              target_size));
7061                 break;
7062
7063         case offsetof(struct __sk_buff, pkt_type):
7064                 *target_size = 1;
7065                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
7066                                       PKT_TYPE_OFFSET());
7067                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
7068 #ifdef __BIG_ENDIAN_BITFIELD
7069                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
7070 #endif
7071                 break;
7072
7073         case offsetof(struct __sk_buff, queue_mapping):
7074                 if (type == BPF_WRITE) {
7075                         *insn++ = BPF_JMP_IMM(BPF_JGE, si->src_reg, NO_QUEUE_MAPPING, 1);
7076                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
7077                                               bpf_target_off(struct sk_buff,
7078                                                              queue_mapping,
7079                                                              2, target_size));
7080                 } else {
7081                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7082                                               bpf_target_off(struct sk_buff,
7083                                                              queue_mapping,
7084                                                              2, target_size));
7085                 }
7086                 break;
7087
7088         case offsetof(struct __sk_buff, vlan_present):
7089                 *target_size = 1;
7090                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
7091                                       PKT_VLAN_PRESENT_OFFSET());
7092                 if (PKT_VLAN_PRESENT_BIT)
7093                         *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, PKT_VLAN_PRESENT_BIT);
7094                 if (PKT_VLAN_PRESENT_BIT < 7)
7095                         *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1);
7096                 break;
7097
7098         case offsetof(struct __sk_buff, vlan_tci):
7099                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7100                                       bpf_target_off(struct sk_buff, vlan_tci, 2,
7101                                                      target_size));
7102                 break;
7103
7104         case offsetof(struct __sk_buff, cb[0]) ...
7105              offsetofend(struct __sk_buff, cb[4]) - 1:
7106                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);
7107                 BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
7108                               offsetof(struct qdisc_skb_cb, data)) %
7109                              sizeof(__u64));
7110
7111                 prog->cb_access = 1;
7112                 off  = si->off;
7113                 off -= offsetof(struct __sk_buff, cb[0]);
7114                 off += offsetof(struct sk_buff, cb);
7115                 off += offsetof(struct qdisc_skb_cb, data);
7116                 if (type == BPF_WRITE)
7117                         *insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
7118                                               si->src_reg, off);
7119                 else
7120                         *insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
7121                                               si->src_reg, off);
7122                 break;
7123
7124         case offsetof(struct __sk_buff, tc_classid):
7125                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, tc_classid) != 2);
7126
7127                 off  = si->off;
7128                 off -= offsetof(struct __sk_buff, tc_classid);
7129                 off += offsetof(struct sk_buff, cb);
7130                 off += offsetof(struct qdisc_skb_cb, tc_classid);
7131                 *target_size = 2;
7132                 if (type == BPF_WRITE)
7133                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg,
7134                                               si->src_reg, off);
7135                 else
7136                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
7137                                               si->src_reg, off);
7138                 break;
7139
7140         case offsetof(struct __sk_buff, data):
7141                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
7142                                       si->dst_reg, si->src_reg,
7143                                       offsetof(struct sk_buff, data));
7144                 break;
7145
7146         case offsetof(struct __sk_buff, data_meta):
7147                 off  = si->off;
7148                 off -= offsetof(struct __sk_buff, data_meta);
7149                 off += offsetof(struct sk_buff, cb);
7150                 off += offsetof(struct bpf_skb_data_end, data_meta);
7151                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7152                                       si->src_reg, off);
7153                 break;
7154
7155         case offsetof(struct __sk_buff, data_end):
7156                 off  = si->off;
7157                 off -= offsetof(struct __sk_buff, data_end);
7158                 off += offsetof(struct sk_buff, cb);
7159                 off += offsetof(struct bpf_skb_data_end, data_end);
7160                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7161                                       si->src_reg, off);
7162                 break;
7163
7164         case offsetof(struct __sk_buff, tc_index):
7165 #ifdef CONFIG_NET_SCHED
7166                 if (type == BPF_WRITE)
7167                         *insn++ = BPF_STX_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                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7172                                               bpf_target_off(struct sk_buff, tc_index, 2,
7173                                                              target_size));
7174 #else
7175                 *target_size = 2;
7176                 if (type == BPF_WRITE)
7177                         *insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
7178                 else
7179                         *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7180 #endif
7181                 break;
7182
7183         case offsetof(struct __sk_buff, napi_id):
7184 #if defined(CONFIG_NET_RX_BUSY_POLL)
7185                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7186                                       bpf_target_off(struct sk_buff, napi_id, 4,
7187                                                      target_size));
7188                 *insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
7189                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7190 #else
7191                 *target_size = 4;
7192                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7193 #endif
7194                 break;
7195         case offsetof(struct __sk_buff, family):
7196                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
7197
7198                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7199                                       si->dst_reg, si->src_reg,
7200                                       offsetof(struct sk_buff, sk));
7201                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7202                                       bpf_target_off(struct sock_common,
7203                                                      skc_family,
7204                                                      2, target_size));
7205                 break;
7206         case offsetof(struct __sk_buff, remote_ip4):
7207                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
7208
7209                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7210                                       si->dst_reg, si->src_reg,
7211                                       offsetof(struct sk_buff, sk));
7212                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7213                                       bpf_target_off(struct sock_common,
7214                                                      skc_daddr,
7215                                                      4, target_size));
7216                 break;
7217         case offsetof(struct __sk_buff, local_ip4):
7218                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7219                                           skc_rcv_saddr) != 4);
7220
7221                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7222                                       si->dst_reg, si->src_reg,
7223                                       offsetof(struct sk_buff, sk));
7224                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7225                                       bpf_target_off(struct sock_common,
7226                                                      skc_rcv_saddr,
7227                                                      4, target_size));
7228                 break;
7229         case offsetof(struct __sk_buff, remote_ip6[0]) ...
7230              offsetof(struct __sk_buff, remote_ip6[3]):
7231 #if IS_ENABLED(CONFIG_IPV6)
7232                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7233                                           skc_v6_daddr.s6_addr32[0]) != 4);
7234
7235                 off = si->off;
7236                 off -= offsetof(struct __sk_buff, remote_ip6[0]);
7237
7238                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7239                                       si->dst_reg, si->src_reg,
7240                                       offsetof(struct sk_buff, sk));
7241                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7242                                       offsetof(struct sock_common,
7243                                                skc_v6_daddr.s6_addr32[0]) +
7244                                       off);
7245 #else
7246                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7247 #endif
7248                 break;
7249         case offsetof(struct __sk_buff, local_ip6[0]) ...
7250              offsetof(struct __sk_buff, local_ip6[3]):
7251 #if IS_ENABLED(CONFIG_IPV6)
7252                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7253                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
7254
7255                 off = si->off;
7256                 off -= offsetof(struct __sk_buff, local_ip6[0]);
7257
7258                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7259                                       si->dst_reg, si->src_reg,
7260                                       offsetof(struct sk_buff, sk));
7261                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7262                                       offsetof(struct sock_common,
7263                                                skc_v6_rcv_saddr.s6_addr32[0]) +
7264                                       off);
7265 #else
7266                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7267 #endif
7268                 break;
7269
7270         case offsetof(struct __sk_buff, remote_port):
7271                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
7272
7273                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7274                                       si->dst_reg, si->src_reg,
7275                                       offsetof(struct sk_buff, sk));
7276                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7277                                       bpf_target_off(struct sock_common,
7278                                                      skc_dport,
7279                                                      2, target_size));
7280 #ifndef __BIG_ENDIAN_BITFIELD
7281                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
7282 #endif
7283                 break;
7284
7285         case offsetof(struct __sk_buff, local_port):
7286                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
7287
7288                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7289                                       si->dst_reg, si->src_reg,
7290                                       offsetof(struct sk_buff, sk));
7291                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7292                                       bpf_target_off(struct sock_common,
7293                                                      skc_num, 2, target_size));
7294                 break;
7295
7296         case offsetof(struct __sk_buff, tstamp):
7297                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, tstamp) != 8);
7298
7299                 if (type == BPF_WRITE)
7300                         *insn++ = BPF_STX_MEM(BPF_DW,
7301                                               si->dst_reg, si->src_reg,
7302                                               bpf_target_off(struct sk_buff,
7303                                                              tstamp, 8,
7304                                                              target_size));
7305                 else
7306                         *insn++ = BPF_LDX_MEM(BPF_DW,
7307                                               si->dst_reg, si->src_reg,
7308                                               bpf_target_off(struct sk_buff,
7309                                                              tstamp, 8,
7310                                                              target_size));
7311                 break;
7312
7313         case offsetof(struct __sk_buff, gso_segs):
7314                 /* si->dst_reg = skb_shinfo(SKB); */
7315 #ifdef NET_SKBUFF_DATA_USES_OFFSET
7316                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, head),
7317                                       si->dst_reg, si->src_reg,
7318                                       offsetof(struct sk_buff, head));
7319                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
7320                                       BPF_REG_AX, si->src_reg,
7321                                       offsetof(struct sk_buff, end));
7322                 *insn++ = BPF_ALU64_REG(BPF_ADD, si->dst_reg, BPF_REG_AX);
7323 #else
7324                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
7325                                       si->dst_reg, si->src_reg,
7326                                       offsetof(struct sk_buff, end));
7327 #endif
7328                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_segs),
7329                                       si->dst_reg, si->dst_reg,
7330                                       bpf_target_off(struct skb_shared_info,
7331                                                      gso_segs, 2,
7332                                                      target_size));
7333                 break;
7334         case offsetof(struct __sk_buff, wire_len):
7335                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, pkt_len) != 4);
7336
7337                 off = si->off;
7338                 off -= offsetof(struct __sk_buff, wire_len);
7339                 off += offsetof(struct sk_buff, cb);
7340                 off += offsetof(struct qdisc_skb_cb, pkt_len);
7341                 *target_size = 4;
7342                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, off);
7343                 break;
7344
7345         case offsetof(struct __sk_buff, sk):
7346                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7347                                       si->dst_reg, si->src_reg,
7348                                       offsetof(struct sk_buff, sk));
7349                 break;
7350         }
7351
7352         return insn - insn_buf;
7353 }
7354
7355 u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
7356                                 const struct bpf_insn *si,
7357                                 struct bpf_insn *insn_buf,
7358                                 struct bpf_prog *prog, u32 *target_size)
7359 {
7360         struct bpf_insn *insn = insn_buf;
7361         int off;
7362
7363         switch (si->off) {
7364         case offsetof(struct bpf_sock, bound_dev_if):
7365                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_bound_dev_if) != 4);
7366
7367                 if (type == BPF_WRITE)
7368                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7369                                         offsetof(struct sock, sk_bound_dev_if));
7370                 else
7371                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7372                                       offsetof(struct sock, sk_bound_dev_if));
7373                 break;
7374
7375         case offsetof(struct bpf_sock, mark):
7376                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_mark) != 4);
7377
7378                 if (type == BPF_WRITE)
7379                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7380                                         offsetof(struct sock, sk_mark));
7381                 else
7382                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7383                                       offsetof(struct sock, sk_mark));
7384                 break;
7385
7386         case offsetof(struct bpf_sock, priority):
7387                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_priority) != 4);
7388
7389                 if (type == BPF_WRITE)
7390                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7391                                         offsetof(struct sock, sk_priority));
7392                 else
7393                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7394                                       offsetof(struct sock, sk_priority));
7395                 break;
7396
7397         case offsetof(struct bpf_sock, family):
7398                 *insn++ = BPF_LDX_MEM(
7399                         BPF_FIELD_SIZEOF(struct sock_common, skc_family),
7400                         si->dst_reg, si->src_reg,
7401                         bpf_target_off(struct sock_common,
7402                                        skc_family,
7403                                        FIELD_SIZEOF(struct sock_common,
7404                                                     skc_family),
7405                                        target_size));
7406                 break;
7407
7408         case offsetof(struct bpf_sock, type):
7409                 BUILD_BUG_ON(HWEIGHT32(SK_FL_TYPE_MASK) != BITS_PER_BYTE * 2);
7410                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7411                                       offsetof(struct sock, __sk_flags_offset));
7412                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
7413                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
7414                 *target_size = 2;
7415                 break;
7416
7417         case offsetof(struct bpf_sock, protocol):
7418                 BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE);
7419                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7420                                       offsetof(struct sock, __sk_flags_offset));
7421                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
7422                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT);
7423                 *target_size = 1;
7424                 break;
7425
7426         case offsetof(struct bpf_sock, src_ip4):
7427                 *insn++ = BPF_LDX_MEM(
7428                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7429                         bpf_target_off(struct sock_common, skc_rcv_saddr,
7430                                        FIELD_SIZEOF(struct sock_common,
7431                                                     skc_rcv_saddr),
7432                                        target_size));
7433                 break;
7434
7435         case offsetof(struct bpf_sock, dst_ip4):
7436                 *insn++ = BPF_LDX_MEM(
7437                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7438                         bpf_target_off(struct sock_common, skc_daddr,
7439                                        FIELD_SIZEOF(struct sock_common,
7440                                                     skc_daddr),
7441                                        target_size));
7442                 break;
7443
7444         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
7445 #if IS_ENABLED(CONFIG_IPV6)
7446                 off = si->off;
7447                 off -= offsetof(struct bpf_sock, src_ip6[0]);
7448                 *insn++ = BPF_LDX_MEM(
7449                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7450                         bpf_target_off(
7451                                 struct sock_common,
7452                                 skc_v6_rcv_saddr.s6_addr32[0],
7453                                 FIELD_SIZEOF(struct sock_common,
7454                                              skc_v6_rcv_saddr.s6_addr32[0]),
7455                                 target_size) + off);
7456 #else
7457                 (void)off;
7458                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7459 #endif
7460                 break;
7461
7462         case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
7463 #if IS_ENABLED(CONFIG_IPV6)
7464                 off = si->off;
7465                 off -= offsetof(struct bpf_sock, dst_ip6[0]);
7466                 *insn++ = BPF_LDX_MEM(
7467                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7468                         bpf_target_off(struct sock_common,
7469                                        skc_v6_daddr.s6_addr32[0],
7470                                        FIELD_SIZEOF(struct sock_common,
7471                                                     skc_v6_daddr.s6_addr32[0]),
7472                                        target_size) + off);
7473 #else
7474                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7475                 *target_size = 4;
7476 #endif
7477                 break;
7478
7479         case offsetof(struct bpf_sock, src_port):
7480                 *insn++ = BPF_LDX_MEM(
7481                         BPF_FIELD_SIZEOF(struct sock_common, skc_num),
7482                         si->dst_reg, si->src_reg,
7483                         bpf_target_off(struct sock_common, skc_num,
7484                                        FIELD_SIZEOF(struct sock_common,
7485                                                     skc_num),
7486                                        target_size));
7487                 break;
7488
7489         case offsetof(struct bpf_sock, dst_port):
7490                 *insn++ = BPF_LDX_MEM(
7491                         BPF_FIELD_SIZEOF(struct sock_common, skc_dport),
7492                         si->dst_reg, si->src_reg,
7493                         bpf_target_off(struct sock_common, skc_dport,
7494                                        FIELD_SIZEOF(struct sock_common,
7495                                                     skc_dport),
7496                                        target_size));
7497                 break;
7498
7499         case offsetof(struct bpf_sock, state):
7500                 *insn++ = BPF_LDX_MEM(
7501                         BPF_FIELD_SIZEOF(struct sock_common, skc_state),
7502                         si->dst_reg, si->src_reg,
7503                         bpf_target_off(struct sock_common, skc_state,
7504                                        FIELD_SIZEOF(struct sock_common,
7505                                                     skc_state),
7506                                        target_size));
7507                 break;
7508         }
7509
7510         return insn - insn_buf;
7511 }
7512
7513 static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
7514                                          const struct bpf_insn *si,
7515                                          struct bpf_insn *insn_buf,
7516                                          struct bpf_prog *prog, u32 *target_size)
7517 {
7518         struct bpf_insn *insn = insn_buf;
7519
7520         switch (si->off) {
7521         case offsetof(struct __sk_buff, ifindex):
7522                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
7523                                       si->dst_reg, si->src_reg,
7524                                       offsetof(struct sk_buff, dev));
7525                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7526                                       bpf_target_off(struct net_device, ifindex, 4,
7527                                                      target_size));
7528                 break;
7529         default:
7530                 return bpf_convert_ctx_access(type, si, insn_buf, prog,
7531                                               target_size);
7532         }
7533
7534         return insn - insn_buf;
7535 }
7536
7537 static u32 xdp_convert_ctx_access(enum bpf_access_type type,
7538                                   const struct bpf_insn *si,
7539                                   struct bpf_insn *insn_buf,
7540                                   struct bpf_prog *prog, u32 *target_size)
7541 {
7542         struct bpf_insn *insn = insn_buf;
7543
7544         switch (si->off) {
7545         case offsetof(struct xdp_md, data):
7546                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
7547                                       si->dst_reg, si->src_reg,
7548                                       offsetof(struct xdp_buff, data));
7549                 break;
7550         case offsetof(struct xdp_md, data_meta):
7551                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta),
7552                                       si->dst_reg, si->src_reg,
7553                                       offsetof(struct xdp_buff, data_meta));
7554                 break;
7555         case offsetof(struct xdp_md, data_end):
7556                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
7557                                       si->dst_reg, si->src_reg,
7558                                       offsetof(struct xdp_buff, data_end));
7559                 break;
7560         case offsetof(struct xdp_md, ingress_ifindex):
7561                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
7562                                       si->dst_reg, si->src_reg,
7563                                       offsetof(struct xdp_buff, rxq));
7564                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev),
7565                                       si->dst_reg, si->dst_reg,
7566                                       offsetof(struct xdp_rxq_info, dev));
7567                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7568                                       offsetof(struct net_device, ifindex));
7569                 break;
7570         case offsetof(struct xdp_md, rx_queue_index):
7571                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
7572                                       si->dst_reg, si->src_reg,
7573                                       offsetof(struct xdp_buff, rxq));
7574                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7575                                       offsetof(struct xdp_rxq_info,
7576                                                queue_index));
7577                 break;
7578         }
7579
7580         return insn - insn_buf;
7581 }
7582
7583 /* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of
7584  * context Structure, F is Field in context structure that contains a pointer
7585  * to Nested Structure of type NS that has the field NF.
7586  *
7587  * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make
7588  * sure that SIZE is not greater than actual size of S.F.NF.
7589  *
7590  * If offset OFF is provided, the load happens from that offset relative to
7591  * offset of NF.
7592  */
7593 #define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF)          \
7594         do {                                                                   \
7595                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg,     \
7596                                       si->src_reg, offsetof(S, F));            \
7597                 *insn++ = BPF_LDX_MEM(                                         \
7598                         SIZE, si->dst_reg, si->dst_reg,                        \
7599                         bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),           \
7600                                        target_size)                            \
7601                                 + OFF);                                        \
7602         } while (0)
7603
7604 #define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF)                              \
7605         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF,                     \
7606                                              BPF_FIELD_SIZEOF(NS, NF), 0)
7607
7608 /* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to
7609  * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation.
7610  *
7611  * It doesn't support SIZE argument though since narrow stores are not
7612  * supported for now.
7613  *
7614  * In addition it uses Temporary Field TF (member of struct S) as the 3rd
7615  * "register" since two registers available in convert_ctx_access are not
7616  * enough: we can't override neither SRC, since it contains value to store, nor
7617  * DST since it contains pointer to context that may be used by later
7618  * instructions. But we need a temporary place to save pointer to nested
7619  * structure whose field we want to store to.
7620  */
7621 #define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF, TF)                \
7622         do {                                                                   \
7623                 int tmp_reg = BPF_REG_9;                                       \
7624                 if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
7625                         --tmp_reg;                                             \
7626                 if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
7627                         --tmp_reg;                                             \
7628                 *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg,            \
7629                                       offsetof(S, TF));                        \
7630                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg,         \
7631                                       si->dst_reg, offsetof(S, F));            \
7632                 *insn++ = BPF_STX_MEM(                                         \
7633                         BPF_FIELD_SIZEOF(NS, NF), tmp_reg, si->src_reg,        \
7634                         bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),           \
7635                                        target_size)                            \
7636                                 + OFF);                                        \
7637                 *insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg,            \
7638                                       offsetof(S, TF));                        \
7639         } while (0)
7640
7641 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \
7642                                                       TF)                      \
7643         do {                                                                   \
7644                 if (type == BPF_WRITE) {                                       \
7645                         SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF,    \
7646                                                          TF);                  \
7647                 } else {                                                       \
7648                         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(                  \
7649                                 S, NS, F, NF, SIZE, OFF);  \
7650                 }                                                              \
7651         } while (0)
7652
7653 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(S, NS, F, NF, TF)                 \
7654         SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(                         \
7655                 S, NS, F, NF, BPF_FIELD_SIZEOF(NS, NF), 0, TF)
7656
7657 static u32 sock_addr_convert_ctx_access(enum bpf_access_type type,
7658                                         const struct bpf_insn *si,
7659                                         struct bpf_insn *insn_buf,
7660                                         struct bpf_prog *prog, u32 *target_size)
7661 {
7662         struct bpf_insn *insn = insn_buf;
7663         int off;
7664
7665         switch (si->off) {
7666         case offsetof(struct bpf_sock_addr, user_family):
7667                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
7668                                             struct sockaddr, uaddr, sa_family);
7669                 break;
7670
7671         case offsetof(struct bpf_sock_addr, user_ip4):
7672                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7673                         struct bpf_sock_addr_kern, struct sockaddr_in, uaddr,
7674                         sin_addr, BPF_SIZE(si->code), 0, tmp_reg);
7675                 break;
7676
7677         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
7678                 off = si->off;
7679                 off -= offsetof(struct bpf_sock_addr, user_ip6[0]);
7680                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7681                         struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
7682                         sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off,
7683                         tmp_reg);
7684                 break;
7685
7686         case offsetof(struct bpf_sock_addr, user_port):
7687                 /* To get port we need to know sa_family first and then treat
7688                  * sockaddr as either sockaddr_in or sockaddr_in6.
7689                  * Though we can simplify since port field has same offset and
7690                  * size in both structures.
7691                  * Here we check this invariant and use just one of the
7692                  * structures if it's true.
7693                  */
7694                 BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) !=
7695                              offsetof(struct sockaddr_in6, sin6_port));
7696                 BUILD_BUG_ON(FIELD_SIZEOF(struct sockaddr_in, sin_port) !=
7697                              FIELD_SIZEOF(struct sockaddr_in6, sin6_port));
7698                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(struct bpf_sock_addr_kern,
7699                                                      struct sockaddr_in6, uaddr,
7700                                                      sin6_port, tmp_reg);
7701                 break;
7702
7703         case offsetof(struct bpf_sock_addr, family):
7704                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
7705                                             struct sock, sk, sk_family);
7706                 break;
7707
7708         case offsetof(struct bpf_sock_addr, type):
7709                 SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
7710                         struct bpf_sock_addr_kern, struct sock, sk,
7711                         __sk_flags_offset, BPF_W, 0);
7712                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
7713                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
7714                 break;
7715
7716         case offsetof(struct bpf_sock_addr, protocol):
7717                 SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
7718                         struct bpf_sock_addr_kern, struct sock, sk,
7719                         __sk_flags_offset, BPF_W, 0);
7720                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
7721                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
7722                                         SK_FL_PROTO_SHIFT);
7723                 break;
7724
7725         case offsetof(struct bpf_sock_addr, msg_src_ip4):
7726                 /* Treat t_ctx as struct in_addr for msg_src_ip4. */
7727                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7728                         struct bpf_sock_addr_kern, struct in_addr, t_ctx,
7729                         s_addr, BPF_SIZE(si->code), 0, tmp_reg);
7730                 break;
7731
7732         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
7733                                 msg_src_ip6[3]):
7734                 off = si->off;
7735                 off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]);
7736                 /* Treat t_ctx as struct in6_addr for msg_src_ip6. */
7737                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7738                         struct bpf_sock_addr_kern, struct in6_addr, t_ctx,
7739                         s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg);
7740                 break;
7741         }
7742
7743         return insn - insn_buf;
7744 }
7745
7746 static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
7747                                        const struct bpf_insn *si,
7748                                        struct bpf_insn *insn_buf,
7749                                        struct bpf_prog *prog,
7750                                        u32 *target_size)
7751 {
7752         struct bpf_insn *insn = insn_buf;
7753         int off;
7754
7755 /* Helper macro for adding read access to tcp_sock or sock fields. */
7756 #define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
7757         do {                                                                  \
7758                 BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >                   \
7759                              FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
7760                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
7761                                                 struct bpf_sock_ops_kern,     \
7762                                                 is_fullsock),                 \
7763                                       si->dst_reg, si->src_reg,               \
7764                                       offsetof(struct bpf_sock_ops_kern,      \
7765                                                is_fullsock));                 \
7766                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 2);            \
7767                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
7768                                                 struct bpf_sock_ops_kern, sk),\
7769                                       si->dst_reg, si->src_reg,               \
7770                                       offsetof(struct bpf_sock_ops_kern, sk));\
7771                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ,                   \
7772                                                        OBJ_FIELD),            \
7773                                       si->dst_reg, si->dst_reg,               \
7774                                       offsetof(OBJ, OBJ_FIELD));              \
7775         } while (0)
7776
7777 #define SOCK_OPS_GET_TCP_SOCK_FIELD(FIELD) \
7778                 SOCK_OPS_GET_FIELD(FIELD, FIELD, struct tcp_sock)
7779
7780 /* Helper macro for adding write access to tcp_sock or sock fields.
7781  * The macro is called with two registers, dst_reg which contains a pointer
7782  * to ctx (context) and src_reg which contains the value that should be
7783  * stored. However, we need an additional register since we cannot overwrite
7784  * dst_reg because it may be used later in the program.
7785  * Instead we "borrow" one of the other register. We first save its value
7786  * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore
7787  * it at the end of the macro.
7788  */
7789 #define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
7790         do {                                                                  \
7791                 int reg = BPF_REG_9;                                          \
7792                 BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >                   \
7793                              FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
7794                 if (si->dst_reg == reg || si->src_reg == reg)                 \
7795                         reg--;                                                \
7796                 if (si->dst_reg == reg || si->src_reg == reg)                 \
7797                         reg--;                                                \
7798                 *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg,               \
7799                                       offsetof(struct bpf_sock_ops_kern,      \
7800                                                temp));                        \
7801                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
7802                                                 struct bpf_sock_ops_kern,     \
7803                                                 is_fullsock),                 \
7804                                       reg, si->dst_reg,                       \
7805                                       offsetof(struct bpf_sock_ops_kern,      \
7806                                                is_fullsock));                 \
7807                 *insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);                    \
7808                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
7809                                                 struct bpf_sock_ops_kern, sk),\
7810                                       reg, si->dst_reg,                       \
7811                                       offsetof(struct bpf_sock_ops_kern, sk));\
7812                 *insn++ = BPF_STX_MEM(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD),       \
7813                                       reg, si->src_reg,                       \
7814                                       offsetof(OBJ, OBJ_FIELD));              \
7815                 *insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg,               \
7816                                       offsetof(struct bpf_sock_ops_kern,      \
7817                                                temp));                        \
7818         } while (0)
7819
7820 #define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE)            \
7821         do {                                                                  \
7822                 if (TYPE == BPF_WRITE)                                        \
7823                         SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
7824                 else                                                          \
7825                         SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
7826         } while (0)
7827
7828         CONVERT_COMMON_TCP_SOCK_FIELDS(struct bpf_sock_ops,
7829                                        SOCK_OPS_GET_TCP_SOCK_FIELD);
7830
7831         if (insn > insn_buf)
7832                 return insn - insn_buf;
7833
7834         switch (si->off) {
7835         case offsetof(struct bpf_sock_ops, op) ...
7836              offsetof(struct bpf_sock_ops, replylong[3]):
7837                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, op) !=
7838                              FIELD_SIZEOF(struct bpf_sock_ops_kern, op));
7839                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, reply) !=
7840                              FIELD_SIZEOF(struct bpf_sock_ops_kern, reply));
7841                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, replylong) !=
7842                              FIELD_SIZEOF(struct bpf_sock_ops_kern, replylong));
7843                 off = si->off;
7844                 off -= offsetof(struct bpf_sock_ops, op);
7845                 off += offsetof(struct bpf_sock_ops_kern, op);
7846                 if (type == BPF_WRITE)
7847                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7848                                               off);
7849                 else
7850                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7851                                               off);
7852                 break;
7853
7854         case offsetof(struct bpf_sock_ops, family):
7855                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
7856
7857                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7858                                               struct bpf_sock_ops_kern, sk),
7859                                       si->dst_reg, si->src_reg,
7860                                       offsetof(struct bpf_sock_ops_kern, sk));
7861                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7862                                       offsetof(struct sock_common, skc_family));
7863                 break;
7864
7865         case offsetof(struct bpf_sock_ops, remote_ip4):
7866                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
7867
7868                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7869                                                 struct bpf_sock_ops_kern, sk),
7870                                       si->dst_reg, si->src_reg,
7871                                       offsetof(struct bpf_sock_ops_kern, sk));
7872                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7873                                       offsetof(struct sock_common, skc_daddr));
7874                 break;
7875
7876         case offsetof(struct bpf_sock_ops, local_ip4):
7877                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7878                                           skc_rcv_saddr) != 4);
7879
7880                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7881                                               struct bpf_sock_ops_kern, sk),
7882                                       si->dst_reg, si->src_reg,
7883                                       offsetof(struct bpf_sock_ops_kern, sk));
7884                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7885                                       offsetof(struct sock_common,
7886                                                skc_rcv_saddr));
7887                 break;
7888
7889         case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
7890              offsetof(struct bpf_sock_ops, remote_ip6[3]):
7891 #if IS_ENABLED(CONFIG_IPV6)
7892                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7893                                           skc_v6_daddr.s6_addr32[0]) != 4);
7894
7895                 off = si->off;
7896                 off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
7897                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7898                                                 struct bpf_sock_ops_kern, sk),
7899                                       si->dst_reg, si->src_reg,
7900                                       offsetof(struct bpf_sock_ops_kern, sk));
7901                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7902                                       offsetof(struct sock_common,
7903                                                skc_v6_daddr.s6_addr32[0]) +
7904                                       off);
7905 #else
7906                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7907 #endif
7908                 break;
7909
7910         case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
7911              offsetof(struct bpf_sock_ops, local_ip6[3]):
7912 #if IS_ENABLED(CONFIG_IPV6)
7913                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7914                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
7915
7916                 off = si->off;
7917                 off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
7918                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7919                                                 struct bpf_sock_ops_kern, sk),
7920                                       si->dst_reg, si->src_reg,
7921                                       offsetof(struct bpf_sock_ops_kern, sk));
7922                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7923                                       offsetof(struct sock_common,
7924                                                skc_v6_rcv_saddr.s6_addr32[0]) +
7925                                       off);
7926 #else
7927                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7928 #endif
7929                 break;
7930
7931         case offsetof(struct bpf_sock_ops, remote_port):
7932                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
7933
7934                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7935                                                 struct bpf_sock_ops_kern, sk),
7936                                       si->dst_reg, si->src_reg,
7937                                       offsetof(struct bpf_sock_ops_kern, sk));
7938                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7939                                       offsetof(struct sock_common, skc_dport));
7940 #ifndef __BIG_ENDIAN_BITFIELD
7941                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
7942 #endif
7943                 break;
7944
7945         case offsetof(struct bpf_sock_ops, local_port):
7946                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
7947
7948                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7949                                                 struct bpf_sock_ops_kern, sk),
7950                                       si->dst_reg, si->src_reg,
7951                                       offsetof(struct bpf_sock_ops_kern, sk));
7952                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7953                                       offsetof(struct sock_common, skc_num));
7954                 break;
7955
7956         case offsetof(struct bpf_sock_ops, is_fullsock):
7957                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7958                                                 struct bpf_sock_ops_kern,
7959                                                 is_fullsock),
7960                                       si->dst_reg, si->src_reg,
7961                                       offsetof(struct bpf_sock_ops_kern,
7962                                                is_fullsock));
7963                 break;
7964
7965         case offsetof(struct bpf_sock_ops, state):
7966                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_state) != 1);
7967
7968                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7969                                                 struct bpf_sock_ops_kern, sk),
7970                                       si->dst_reg, si->src_reg,
7971                                       offsetof(struct bpf_sock_ops_kern, sk));
7972                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg,
7973                                       offsetof(struct sock_common, skc_state));
7974                 break;
7975
7976         case offsetof(struct bpf_sock_ops, rtt_min):
7977                 BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) !=
7978                              sizeof(struct minmax));
7979                 BUILD_BUG_ON(sizeof(struct minmax) <
7980                              sizeof(struct minmax_sample));
7981
7982                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7983                                                 struct bpf_sock_ops_kern, sk),
7984                                       si->dst_reg, si->src_reg,
7985                                       offsetof(struct bpf_sock_ops_kern, sk));
7986                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7987                                       offsetof(struct tcp_sock, rtt_min) +
7988                                       FIELD_SIZEOF(struct minmax_sample, t));
7989                 break;
7990
7991         case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags):
7992                 SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags,
7993                                    struct tcp_sock);
7994                 break;
7995
7996         case offsetof(struct bpf_sock_ops, sk_txhash):
7997                 SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash,
7998                                           struct sock, type);
7999                 break;
8000         }
8001         return insn - insn_buf;
8002 }
8003
8004 static u32 sk_skb_convert_ctx_access(enum bpf_access_type type,
8005                                      const struct bpf_insn *si,
8006                                      struct bpf_insn *insn_buf,
8007                                      struct bpf_prog *prog, u32 *target_size)
8008 {
8009         struct bpf_insn *insn = insn_buf;
8010         int off;
8011
8012         switch (si->off) {
8013         case offsetof(struct __sk_buff, data_end):
8014                 off  = si->off;
8015                 off -= offsetof(struct __sk_buff, data_end);
8016                 off += offsetof(struct sk_buff, cb);
8017                 off += offsetof(struct tcp_skb_cb, bpf.data_end);
8018                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
8019                                       si->src_reg, off);
8020                 break;
8021         default:
8022                 return bpf_convert_ctx_access(type, si, insn_buf, prog,
8023                                               target_size);
8024         }
8025
8026         return insn - insn_buf;
8027 }
8028
8029 static u32 sk_msg_convert_ctx_access(enum bpf_access_type type,
8030                                      const struct bpf_insn *si,
8031                                      struct bpf_insn *insn_buf,
8032                                      struct bpf_prog *prog, u32 *target_size)
8033 {
8034         struct bpf_insn *insn = insn_buf;
8035 #if IS_ENABLED(CONFIG_IPV6)
8036         int off;
8037 #endif
8038
8039         /* convert ctx uses the fact sg element is first in struct */
8040         BUILD_BUG_ON(offsetof(struct sk_msg, sg) != 0);
8041
8042         switch (si->off) {
8043         case offsetof(struct sk_msg_md, data):
8044                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data),
8045                                       si->dst_reg, si->src_reg,
8046                                       offsetof(struct sk_msg, data));
8047                 break;
8048         case offsetof(struct sk_msg_md, data_end):
8049                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data_end),
8050                                       si->dst_reg, si->src_reg,
8051                                       offsetof(struct sk_msg, data_end));
8052                 break;
8053         case offsetof(struct sk_msg_md, family):
8054                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
8055
8056                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8057                                               struct sk_msg, sk),
8058                                       si->dst_reg, si->src_reg,
8059                                       offsetof(struct sk_msg, sk));
8060                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8061                                       offsetof(struct sock_common, skc_family));
8062                 break;
8063
8064         case offsetof(struct sk_msg_md, remote_ip4):
8065                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
8066
8067                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8068                                                 struct sk_msg, sk),
8069                                       si->dst_reg, si->src_reg,
8070                                       offsetof(struct sk_msg, sk));
8071                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8072                                       offsetof(struct sock_common, skc_daddr));
8073                 break;
8074
8075         case offsetof(struct sk_msg_md, local_ip4):
8076                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8077                                           skc_rcv_saddr) != 4);
8078
8079                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8080                                               struct sk_msg, sk),
8081                                       si->dst_reg, si->src_reg,
8082                                       offsetof(struct sk_msg, sk));
8083                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8084                                       offsetof(struct sock_common,
8085                                                skc_rcv_saddr));
8086                 break;
8087
8088         case offsetof(struct sk_msg_md, remote_ip6[0]) ...
8089              offsetof(struct sk_msg_md, remote_ip6[3]):
8090 #if IS_ENABLED(CONFIG_IPV6)
8091                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8092                                           skc_v6_daddr.s6_addr32[0]) != 4);
8093
8094                 off = si->off;
8095                 off -= offsetof(struct sk_msg_md, remote_ip6[0]);
8096                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8097                                                 struct sk_msg, sk),
8098                                       si->dst_reg, si->src_reg,
8099                                       offsetof(struct sk_msg, sk));
8100                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8101                                       offsetof(struct sock_common,
8102                                                skc_v6_daddr.s6_addr32[0]) +
8103                                       off);
8104 #else
8105                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8106 #endif
8107                 break;
8108
8109         case offsetof(struct sk_msg_md, local_ip6[0]) ...
8110              offsetof(struct sk_msg_md, local_ip6[3]):
8111 #if IS_ENABLED(CONFIG_IPV6)
8112                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8113                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
8114
8115                 off = si->off;
8116                 off -= offsetof(struct sk_msg_md, local_ip6[0]);
8117                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8118                                                 struct sk_msg, sk),
8119                                       si->dst_reg, si->src_reg,
8120                                       offsetof(struct sk_msg, sk));
8121                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8122                                       offsetof(struct sock_common,
8123                                                skc_v6_rcv_saddr.s6_addr32[0]) +
8124                                       off);
8125 #else
8126                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8127 #endif
8128                 break;
8129
8130         case offsetof(struct sk_msg_md, remote_port):
8131                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
8132
8133                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8134                                                 struct sk_msg, sk),
8135                                       si->dst_reg, si->src_reg,
8136                                       offsetof(struct sk_msg, sk));
8137                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8138                                       offsetof(struct sock_common, skc_dport));
8139 #ifndef __BIG_ENDIAN_BITFIELD
8140                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
8141 #endif
8142                 break;
8143
8144         case offsetof(struct sk_msg_md, local_port):
8145                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
8146
8147                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8148                                                 struct sk_msg, sk),
8149                                       si->dst_reg, si->src_reg,
8150                                       offsetof(struct sk_msg, sk));
8151                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8152                                       offsetof(struct sock_common, skc_num));
8153                 break;
8154
8155         case offsetof(struct sk_msg_md, size):
8156                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_sg, size),
8157                                       si->dst_reg, si->src_reg,
8158                                       offsetof(struct sk_msg_sg, size));
8159                 break;
8160         }
8161
8162         return insn - insn_buf;
8163 }
8164
8165 const struct bpf_verifier_ops sk_filter_verifier_ops = {
8166         .get_func_proto         = sk_filter_func_proto,
8167         .is_valid_access        = sk_filter_is_valid_access,
8168         .convert_ctx_access     = bpf_convert_ctx_access,
8169         .gen_ld_abs             = bpf_gen_ld_abs,
8170 };
8171
8172 const struct bpf_prog_ops sk_filter_prog_ops = {
8173         .test_run               = bpf_prog_test_run_skb,
8174 };
8175
8176 const struct bpf_verifier_ops tc_cls_act_verifier_ops = {
8177         .get_func_proto         = tc_cls_act_func_proto,
8178         .is_valid_access        = tc_cls_act_is_valid_access,
8179         .convert_ctx_access     = tc_cls_act_convert_ctx_access,
8180         .gen_prologue           = tc_cls_act_prologue,
8181         .gen_ld_abs             = bpf_gen_ld_abs,
8182 };
8183
8184 const struct bpf_prog_ops tc_cls_act_prog_ops = {
8185         .test_run               = bpf_prog_test_run_skb,
8186 };
8187
8188 const struct bpf_verifier_ops xdp_verifier_ops = {
8189         .get_func_proto         = xdp_func_proto,
8190         .is_valid_access        = xdp_is_valid_access,
8191         .convert_ctx_access     = xdp_convert_ctx_access,
8192         .gen_prologue           = bpf_noop_prologue,
8193 };
8194
8195 const struct bpf_prog_ops xdp_prog_ops = {
8196         .test_run               = bpf_prog_test_run_xdp,
8197 };
8198
8199 const struct bpf_verifier_ops cg_skb_verifier_ops = {
8200         .get_func_proto         = cg_skb_func_proto,
8201         .is_valid_access        = cg_skb_is_valid_access,
8202         .convert_ctx_access     = bpf_convert_ctx_access,
8203 };
8204
8205 const struct bpf_prog_ops cg_skb_prog_ops = {
8206         .test_run               = bpf_prog_test_run_skb,
8207 };
8208
8209 const struct bpf_verifier_ops lwt_in_verifier_ops = {
8210         .get_func_proto         = lwt_in_func_proto,
8211         .is_valid_access        = lwt_is_valid_access,
8212         .convert_ctx_access     = bpf_convert_ctx_access,
8213 };
8214
8215 const struct bpf_prog_ops lwt_in_prog_ops = {
8216         .test_run               = bpf_prog_test_run_skb,
8217 };
8218
8219 const struct bpf_verifier_ops lwt_out_verifier_ops = {
8220         .get_func_proto         = lwt_out_func_proto,
8221         .is_valid_access        = lwt_is_valid_access,
8222         .convert_ctx_access     = bpf_convert_ctx_access,
8223 };
8224
8225 const struct bpf_prog_ops lwt_out_prog_ops = {
8226         .test_run               = bpf_prog_test_run_skb,
8227 };
8228
8229 const struct bpf_verifier_ops lwt_xmit_verifier_ops = {
8230         .get_func_proto         = lwt_xmit_func_proto,
8231         .is_valid_access        = lwt_is_valid_access,
8232         .convert_ctx_access     = bpf_convert_ctx_access,
8233         .gen_prologue           = tc_cls_act_prologue,
8234 };
8235
8236 const struct bpf_prog_ops lwt_xmit_prog_ops = {
8237         .test_run               = bpf_prog_test_run_skb,
8238 };
8239
8240 const struct bpf_verifier_ops lwt_seg6local_verifier_ops = {
8241         .get_func_proto         = lwt_seg6local_func_proto,
8242         .is_valid_access        = lwt_is_valid_access,
8243         .convert_ctx_access     = bpf_convert_ctx_access,
8244 };
8245
8246 const struct bpf_prog_ops lwt_seg6local_prog_ops = {
8247         .test_run               = bpf_prog_test_run_skb,
8248 };
8249
8250 const struct bpf_verifier_ops cg_sock_verifier_ops = {
8251         .get_func_proto         = sock_filter_func_proto,
8252         .is_valid_access        = sock_filter_is_valid_access,
8253         .convert_ctx_access     = bpf_sock_convert_ctx_access,
8254 };
8255
8256 const struct bpf_prog_ops cg_sock_prog_ops = {
8257 };
8258
8259 const struct bpf_verifier_ops cg_sock_addr_verifier_ops = {
8260         .get_func_proto         = sock_addr_func_proto,
8261         .is_valid_access        = sock_addr_is_valid_access,
8262         .convert_ctx_access     = sock_addr_convert_ctx_access,
8263 };
8264
8265 const struct bpf_prog_ops cg_sock_addr_prog_ops = {
8266 };
8267
8268 const struct bpf_verifier_ops sock_ops_verifier_ops = {
8269         .get_func_proto         = sock_ops_func_proto,
8270         .is_valid_access        = sock_ops_is_valid_access,
8271         .convert_ctx_access     = sock_ops_convert_ctx_access,
8272 };
8273
8274 const struct bpf_prog_ops sock_ops_prog_ops = {
8275 };
8276
8277 const struct bpf_verifier_ops sk_skb_verifier_ops = {
8278         .get_func_proto         = sk_skb_func_proto,
8279         .is_valid_access        = sk_skb_is_valid_access,
8280         .convert_ctx_access     = sk_skb_convert_ctx_access,
8281         .gen_prologue           = sk_skb_prologue,
8282 };
8283
8284 const struct bpf_prog_ops sk_skb_prog_ops = {
8285 };
8286
8287 const struct bpf_verifier_ops sk_msg_verifier_ops = {
8288         .get_func_proto         = sk_msg_func_proto,
8289         .is_valid_access        = sk_msg_is_valid_access,
8290         .convert_ctx_access     = sk_msg_convert_ctx_access,
8291         .gen_prologue           = bpf_noop_prologue,
8292 };
8293
8294 const struct bpf_prog_ops sk_msg_prog_ops = {
8295 };
8296
8297 const struct bpf_verifier_ops flow_dissector_verifier_ops = {
8298         .get_func_proto         = flow_dissector_func_proto,
8299         .is_valid_access        = flow_dissector_is_valid_access,
8300         .convert_ctx_access     = flow_dissector_convert_ctx_access,
8301 };
8302
8303 const struct bpf_prog_ops flow_dissector_prog_ops = {
8304         .test_run               = bpf_prog_test_run_flow_dissector,
8305 };
8306
8307 int sk_detach_filter(struct sock *sk)
8308 {
8309         int ret = -ENOENT;
8310         struct sk_filter *filter;
8311
8312         if (sock_flag(sk, SOCK_FILTER_LOCKED))
8313                 return -EPERM;
8314
8315         filter = rcu_dereference_protected(sk->sk_filter,
8316                                            lockdep_sock_is_held(sk));
8317         if (filter) {
8318                 RCU_INIT_POINTER(sk->sk_filter, NULL);
8319                 sk_filter_uncharge(sk, filter);
8320                 ret = 0;
8321         }
8322
8323         return ret;
8324 }
8325 EXPORT_SYMBOL_GPL(sk_detach_filter);
8326
8327 int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
8328                   unsigned int len)
8329 {
8330         struct sock_fprog_kern *fprog;
8331         struct sk_filter *filter;
8332         int ret = 0;
8333
8334         lock_sock(sk);
8335         filter = rcu_dereference_protected(sk->sk_filter,
8336                                            lockdep_sock_is_held(sk));
8337         if (!filter)
8338                 goto out;
8339
8340         /* We're copying the filter that has been originally attached,
8341          * so no conversion/decode needed anymore. eBPF programs that
8342          * have no original program cannot be dumped through this.
8343          */
8344         ret = -EACCES;
8345         fprog = filter->prog->orig_prog;
8346         if (!fprog)
8347                 goto out;
8348
8349         ret = fprog->len;
8350         if (!len)
8351                 /* User space only enquires number of filter blocks. */
8352                 goto out;
8353
8354         ret = -EINVAL;
8355         if (len < fprog->len)
8356                 goto out;
8357
8358         ret = -EFAULT;
8359         if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
8360                 goto out;
8361
8362         /* Instead of bytes, the API requests to return the number
8363          * of filter blocks.
8364          */
8365         ret = fprog->len;
8366 out:
8367         release_sock(sk);
8368         return ret;
8369 }
8370
8371 #ifdef CONFIG_INET
8372 struct sk_reuseport_kern {
8373         struct sk_buff *skb;
8374         struct sock *sk;
8375         struct sock *selected_sk;
8376         void *data_end;
8377         u32 hash;
8378         u32 reuseport_id;
8379         bool bind_inany;
8380 };
8381
8382 static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,
8383                                     struct sock_reuseport *reuse,
8384                                     struct sock *sk, struct sk_buff *skb,
8385                                     u32 hash)
8386 {
8387         reuse_kern->skb = skb;
8388         reuse_kern->sk = sk;
8389         reuse_kern->selected_sk = NULL;
8390         reuse_kern->data_end = skb->data + skb_headlen(skb);
8391         reuse_kern->hash = hash;
8392         reuse_kern->reuseport_id = reuse->reuseport_id;
8393         reuse_kern->bind_inany = reuse->bind_inany;
8394 }
8395
8396 struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,
8397                                   struct bpf_prog *prog, struct sk_buff *skb,
8398                                   u32 hash)
8399 {
8400         struct sk_reuseport_kern reuse_kern;
8401         enum sk_action action;
8402
8403         bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, hash);
8404         action = BPF_PROG_RUN(prog, &reuse_kern);
8405
8406         if (action == SK_PASS)
8407                 return reuse_kern.selected_sk;
8408         else
8409                 return ERR_PTR(-ECONNREFUSED);
8410 }
8411
8412 BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern,
8413            struct bpf_map *, map, void *, key, u32, flags)
8414 {
8415         struct sock_reuseport *reuse;
8416         struct sock *selected_sk;
8417
8418         selected_sk = map->ops->map_lookup_elem(map, key);
8419         if (!selected_sk)
8420                 return -ENOENT;
8421
8422         reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
8423         if (!reuse)
8424                 /* selected_sk is unhashed (e.g. by close()) after the
8425                  * above map_lookup_elem().  Treat selected_sk has already
8426                  * been removed from the map.
8427                  */
8428                 return -ENOENT;
8429
8430         if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
8431                 struct sock *sk;
8432
8433                 if (unlikely(!reuse_kern->reuseport_id))
8434                         /* There is a small race between adding the
8435                          * sk to the map and setting the
8436                          * reuse_kern->reuseport_id.
8437                          * Treat it as the sk has not been added to
8438                          * the bpf map yet.
8439                          */
8440                         return -ENOENT;
8441
8442                 sk = reuse_kern->sk;
8443                 if (sk->sk_protocol != selected_sk->sk_protocol)
8444                         return -EPROTOTYPE;
8445                 else if (sk->sk_family != selected_sk->sk_family)
8446                         return -EAFNOSUPPORT;
8447
8448                 /* Catch all. Likely bound to a different sockaddr. */
8449                 return -EBADFD;
8450         }
8451
8452         reuse_kern->selected_sk = selected_sk;
8453
8454         return 0;
8455 }
8456
8457 static const struct bpf_func_proto sk_select_reuseport_proto = {
8458         .func           = sk_select_reuseport,
8459         .gpl_only       = false,
8460         .ret_type       = RET_INTEGER,
8461         .arg1_type      = ARG_PTR_TO_CTX,
8462         .arg2_type      = ARG_CONST_MAP_PTR,
8463         .arg3_type      = ARG_PTR_TO_MAP_KEY,
8464         .arg4_type      = ARG_ANYTHING,
8465 };
8466
8467 BPF_CALL_4(sk_reuseport_load_bytes,
8468            const struct sk_reuseport_kern *, reuse_kern, u32, offset,
8469            void *, to, u32, len)
8470 {
8471         return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
8472 }
8473
8474 static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
8475         .func           = sk_reuseport_load_bytes,
8476         .gpl_only       = false,
8477         .ret_type       = RET_INTEGER,
8478         .arg1_type      = ARG_PTR_TO_CTX,
8479         .arg2_type      = ARG_ANYTHING,
8480         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
8481         .arg4_type      = ARG_CONST_SIZE,
8482 };
8483
8484 BPF_CALL_5(sk_reuseport_load_bytes_relative,
8485            const struct sk_reuseport_kern *, reuse_kern, u32, offset,
8486            void *, to, u32, len, u32, start_header)
8487 {
8488         return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
8489                                                len, start_header);
8490 }
8491
8492 static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
8493         .func           = sk_reuseport_load_bytes_relative,
8494         .gpl_only       = false,
8495         .ret_type       = RET_INTEGER,
8496         .arg1_type      = ARG_PTR_TO_CTX,
8497         .arg2_type      = ARG_ANYTHING,
8498         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
8499         .arg4_type      = ARG_CONST_SIZE,
8500         .arg5_type      = ARG_ANYTHING,
8501 };
8502
8503 static const struct bpf_func_proto *
8504 sk_reuseport_func_proto(enum bpf_func_id func_id,
8505                         const struct bpf_prog *prog)
8506 {
8507         switch (func_id) {
8508         case BPF_FUNC_sk_select_reuseport:
8509                 return &sk_select_reuseport_proto;
8510         case BPF_FUNC_skb_load_bytes:
8511                 return &sk_reuseport_load_bytes_proto;
8512         case BPF_FUNC_skb_load_bytes_relative:
8513                 return &sk_reuseport_load_bytes_relative_proto;
8514         default:
8515                 return bpf_base_func_proto(func_id);
8516         }
8517 }
8518
8519 static bool
8520 sk_reuseport_is_valid_access(int off, int size,
8521                              enum bpf_access_type type,
8522                              const struct bpf_prog *prog,
8523                              struct bpf_insn_access_aux *info)
8524 {
8525         const u32 size_default = sizeof(__u32);
8526
8527         if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
8528             off % size || type != BPF_READ)
8529                 return false;
8530
8531         switch (off) {
8532         case offsetof(struct sk_reuseport_md, data):
8533                 info->reg_type = PTR_TO_PACKET;
8534                 return size == sizeof(__u64);
8535
8536         case offsetof(struct sk_reuseport_md, data_end):
8537                 info->reg_type = PTR_TO_PACKET_END;
8538                 return size == sizeof(__u64);
8539
8540         case offsetof(struct sk_reuseport_md, hash):
8541                 return size == size_default;
8542
8543         /* Fields that allow narrowing */
8544         case offsetof(struct sk_reuseport_md, eth_protocol):
8545                 if (size < FIELD_SIZEOF(struct sk_buff, protocol))
8546                         return false;
8547                 /* fall through */
8548         case offsetof(struct sk_reuseport_md, ip_protocol):
8549         case offsetof(struct sk_reuseport_md, bind_inany):
8550         case offsetof(struct sk_reuseport_md, len):
8551                 bpf_ctx_record_field_size(info, size_default);
8552                 return bpf_ctx_narrow_access_ok(off, size, size_default);
8553
8554         default:
8555                 return false;
8556         }
8557 }
8558
8559 #define SK_REUSEPORT_LOAD_FIELD(F) ({                                   \
8560         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
8561                               si->dst_reg, si->src_reg,                 \
8562                               bpf_target_off(struct sk_reuseport_kern, F, \
8563                                              FIELD_SIZEOF(struct sk_reuseport_kern, F), \
8564                                              target_size));             \
8565         })
8566
8567 #define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)                          \
8568         SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,           \
8569                                     struct sk_buff,                     \
8570                                     skb,                                \
8571                                     SKB_FIELD)
8572
8573 #define SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(SK_FIELD, BPF_SIZE, EXTRA_OFF) \
8574         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(struct sk_reuseport_kern,  \
8575                                              struct sock,               \
8576                                              sk,                        \
8577                                              SK_FIELD, BPF_SIZE, EXTRA_OFF)
8578
8579 static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
8580                                            const struct bpf_insn *si,
8581                                            struct bpf_insn *insn_buf,
8582                                            struct bpf_prog *prog,
8583                                            u32 *target_size)
8584 {
8585         struct bpf_insn *insn = insn_buf;
8586
8587         switch (si->off) {
8588         case offsetof(struct sk_reuseport_md, data):
8589                 SK_REUSEPORT_LOAD_SKB_FIELD(data);
8590                 break;
8591
8592         case offsetof(struct sk_reuseport_md, len):
8593                 SK_REUSEPORT_LOAD_SKB_FIELD(len);
8594                 break;
8595
8596         case offsetof(struct sk_reuseport_md, eth_protocol):
8597                 SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
8598                 break;
8599
8600         case offsetof(struct sk_reuseport_md, ip_protocol):
8601                 BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE);
8602                 SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(__sk_flags_offset,
8603                                                     BPF_W, 0);
8604                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
8605                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
8606                                         SK_FL_PROTO_SHIFT);
8607                 /* SK_FL_PROTO_MASK and SK_FL_PROTO_SHIFT are endian
8608                  * aware.  No further narrowing or masking is needed.
8609                  */
8610                 *target_size = 1;
8611                 break;
8612
8613         case offsetof(struct sk_reuseport_md, data_end):
8614                 SK_REUSEPORT_LOAD_FIELD(data_end);
8615                 break;
8616
8617         case offsetof(struct sk_reuseport_md, hash):
8618                 SK_REUSEPORT_LOAD_FIELD(hash);
8619                 break;
8620
8621         case offsetof(struct sk_reuseport_md, bind_inany):
8622                 SK_REUSEPORT_LOAD_FIELD(bind_inany);
8623                 break;
8624         }
8625
8626         return insn - insn_buf;
8627 }
8628
8629 const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
8630         .get_func_proto         = sk_reuseport_func_proto,
8631         .is_valid_access        = sk_reuseport_is_valid_access,
8632         .convert_ctx_access     = sk_reuseport_convert_ctx_access,
8633 };
8634
8635 const struct bpf_prog_ops sk_reuseport_prog_ops = {
8636 };
8637 #endif /* CONFIG_INET */