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