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