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