bpf: reserve flags in bpf_skb_net_shrink
[linux-2.6-microblaze.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 (flags & ~BPF_F_ADJ_ROOM_FIXED_GSO)
3073                 return -EINVAL;
3074
3075         if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3076                 /* udp gso_size delineates datagrams, only allow if fixed */
3077                 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3078                     !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3079                         return -ENOTSUPP;
3080         }
3081
3082         ret = skb_unclone(skb, GFP_ATOMIC);
3083         if (unlikely(ret < 0))
3084                 return ret;
3085
3086         ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
3087         if (unlikely(ret < 0))
3088                 return ret;
3089
3090         if (skb_is_gso(skb)) {
3091                 struct skb_shared_info *shinfo = skb_shinfo(skb);
3092
3093                 /* Due to header shrink, MSS can be upgraded. */
3094                 if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3095                         skb_increase_gso_size(shinfo, len_diff);
3096
3097                 /* Header must be checked, and gso_segs recomputed. */
3098                 shinfo->gso_type |= SKB_GSO_DODGY;
3099                 shinfo->gso_segs = 0;
3100         }
3101
3102         return 0;
3103 }
3104
3105 static u32 __bpf_skb_max_len(const struct sk_buff *skb)
3106 {
3107         return skb->dev ? skb->dev->mtu + skb->dev->hard_header_len :
3108                           SKB_MAX_ALLOC;
3109 }
3110
3111 BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
3112            u32, mode, u64, flags)
3113 {
3114         u32 len_cur, len_diff_abs = abs(len_diff);
3115         u32 len_min = bpf_skb_net_base_len(skb);
3116         u32 len_max = __bpf_skb_max_len(skb);
3117         __be16 proto = skb->protocol;
3118         bool shrink = len_diff < 0;
3119         u32 off;
3120         int ret;
3121
3122         if (unlikely(flags & ~BPF_F_ADJ_ROOM_MASK))
3123                 return -EINVAL;
3124         if (unlikely(len_diff_abs > 0xfffU))
3125                 return -EFAULT;
3126         if (unlikely(proto != htons(ETH_P_IP) &&
3127                      proto != htons(ETH_P_IPV6)))
3128                 return -ENOTSUPP;
3129
3130         off = skb_mac_header_len(skb);
3131         switch (mode) {
3132         case BPF_ADJ_ROOM_NET:
3133                 off += bpf_skb_net_base_len(skb);
3134                 break;
3135         case BPF_ADJ_ROOM_MAC:
3136                 break;
3137         default:
3138                 return -ENOTSUPP;
3139         }
3140
3141         len_cur = skb->len - skb_network_offset(skb);
3142         if ((shrink && (len_diff_abs >= len_cur ||
3143                         len_cur - len_diff_abs < len_min)) ||
3144             (!shrink && (skb->len + len_diff_abs > len_max &&
3145                          !skb_is_gso(skb))))
3146                 return -ENOTSUPP;
3147
3148         ret = shrink ? bpf_skb_net_shrink(skb, off, len_diff_abs, flags) :
3149                        bpf_skb_net_grow(skb, off, len_diff_abs, flags);
3150
3151         bpf_compute_data_pointers(skb);
3152         return ret;
3153 }
3154
3155 static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
3156         .func           = bpf_skb_adjust_room,
3157         .gpl_only       = false,
3158         .ret_type       = RET_INTEGER,
3159         .arg1_type      = ARG_PTR_TO_CTX,
3160         .arg2_type      = ARG_ANYTHING,
3161         .arg3_type      = ARG_ANYTHING,
3162         .arg4_type      = ARG_ANYTHING,
3163 };
3164
3165 static u32 __bpf_skb_min_len(const struct sk_buff *skb)
3166 {
3167         u32 min_len = skb_network_offset(skb);
3168
3169         if (skb_transport_header_was_set(skb))
3170                 min_len = skb_transport_offset(skb);
3171         if (skb->ip_summed == CHECKSUM_PARTIAL)
3172                 min_len = skb_checksum_start_offset(skb) +
3173                           skb->csum_offset + sizeof(__sum16);
3174         return min_len;
3175 }
3176
3177 static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
3178 {
3179         unsigned int old_len = skb->len;
3180         int ret;
3181
3182         ret = __skb_grow_rcsum(skb, new_len);
3183         if (!ret)
3184                 memset(skb->data + old_len, 0, new_len - old_len);
3185         return ret;
3186 }
3187
3188 static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
3189 {
3190         return __skb_trim_rcsum(skb, new_len);
3191 }
3192
3193 static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len,
3194                                         u64 flags)
3195 {
3196         u32 max_len = __bpf_skb_max_len(skb);
3197         u32 min_len = __bpf_skb_min_len(skb);
3198         int ret;
3199
3200         if (unlikely(flags || new_len > max_len || new_len < min_len))
3201                 return -EINVAL;
3202         if (skb->encapsulation)
3203                 return -ENOTSUPP;
3204
3205         /* The basic idea of this helper is that it's performing the
3206          * needed work to either grow or trim an skb, and eBPF program
3207          * rewrites the rest via helpers like bpf_skb_store_bytes(),
3208          * bpf_lX_csum_replace() and others rather than passing a raw
3209          * buffer here. This one is a slow path helper and intended
3210          * for replies with control messages.
3211          *
3212          * Like in bpf_skb_change_proto(), we want to keep this rather
3213          * minimal and without protocol specifics so that we are able
3214          * to separate concerns as in bpf_skb_store_bytes() should only
3215          * be the one responsible for writing buffers.
3216          *
3217          * It's really expected to be a slow path operation here for
3218          * control message replies, so we're implicitly linearizing,
3219          * uncloning and drop offloads from the skb by this.
3220          */
3221         ret = __bpf_try_make_writable(skb, skb->len);
3222         if (!ret) {
3223                 if (new_len > skb->len)
3224                         ret = bpf_skb_grow_rcsum(skb, new_len);
3225                 else if (new_len < skb->len)
3226                         ret = bpf_skb_trim_rcsum(skb, new_len);
3227                 if (!ret && skb_is_gso(skb))
3228                         skb_gso_reset(skb);
3229         }
3230         return ret;
3231 }
3232
3233 BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3234            u64, flags)
3235 {
3236         int ret = __bpf_skb_change_tail(skb, new_len, flags);
3237
3238         bpf_compute_data_pointers(skb);
3239         return ret;
3240 }
3241
3242 static const struct bpf_func_proto bpf_skb_change_tail_proto = {
3243         .func           = bpf_skb_change_tail,
3244         .gpl_only       = false,
3245         .ret_type       = RET_INTEGER,
3246         .arg1_type      = ARG_PTR_TO_CTX,
3247         .arg2_type      = ARG_ANYTHING,
3248         .arg3_type      = ARG_ANYTHING,
3249 };
3250
3251 BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3252            u64, flags)
3253 {
3254         int ret = __bpf_skb_change_tail(skb, new_len, flags);
3255
3256         bpf_compute_data_end_sk_skb(skb);
3257         return ret;
3258 }
3259
3260 static const struct bpf_func_proto sk_skb_change_tail_proto = {
3261         .func           = sk_skb_change_tail,
3262         .gpl_only       = false,
3263         .ret_type       = RET_INTEGER,
3264         .arg1_type      = ARG_PTR_TO_CTX,
3265         .arg2_type      = ARG_ANYTHING,
3266         .arg3_type      = ARG_ANYTHING,
3267 };
3268
3269 static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room,
3270                                         u64 flags)
3271 {
3272         u32 max_len = __bpf_skb_max_len(skb);
3273         u32 new_len = skb->len + head_room;
3274         int ret;
3275
3276         if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
3277                      new_len < skb->len))
3278                 return -EINVAL;
3279
3280         ret = skb_cow(skb, head_room);
3281         if (likely(!ret)) {
3282                 /* Idea for this helper is that we currently only
3283                  * allow to expand on mac header. This means that
3284                  * skb->protocol network header, etc, stay as is.
3285                  * Compared to bpf_skb_change_tail(), we're more
3286                  * flexible due to not needing to linearize or
3287                  * reset GSO. Intention for this helper is to be
3288                  * used by an L3 skb that needs to push mac header
3289                  * for redirection into L2 device.
3290                  */
3291                 __skb_push(skb, head_room);
3292                 memset(skb->data, 0, head_room);
3293                 skb_reset_mac_header(skb);
3294         }
3295
3296         return ret;
3297 }
3298
3299 BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
3300            u64, flags)
3301 {
3302         int ret = __bpf_skb_change_head(skb, head_room, flags);
3303
3304         bpf_compute_data_pointers(skb);
3305         return ret;
3306 }
3307
3308 static const struct bpf_func_proto bpf_skb_change_head_proto = {
3309         .func           = bpf_skb_change_head,
3310         .gpl_only       = false,
3311         .ret_type       = RET_INTEGER,
3312         .arg1_type      = ARG_PTR_TO_CTX,
3313         .arg2_type      = ARG_ANYTHING,
3314         .arg3_type      = ARG_ANYTHING,
3315 };
3316
3317 BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room,
3318            u64, flags)
3319 {
3320         int ret = __bpf_skb_change_head(skb, head_room, flags);
3321
3322         bpf_compute_data_end_sk_skb(skb);
3323         return ret;
3324 }
3325
3326 static const struct bpf_func_proto sk_skb_change_head_proto = {
3327         .func           = sk_skb_change_head,
3328         .gpl_only       = false,
3329         .ret_type       = RET_INTEGER,
3330         .arg1_type      = ARG_PTR_TO_CTX,
3331         .arg2_type      = ARG_ANYTHING,
3332         .arg3_type      = ARG_ANYTHING,
3333 };
3334 static unsigned long xdp_get_metalen(const struct xdp_buff *xdp)
3335 {
3336         return xdp_data_meta_unsupported(xdp) ? 0 :
3337                xdp->data - xdp->data_meta;
3338 }
3339
3340 BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
3341 {
3342         void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3343         unsigned long metalen = xdp_get_metalen(xdp);
3344         void *data_start = xdp_frame_end + metalen;
3345         void *data = xdp->data + offset;
3346
3347         if (unlikely(data < data_start ||
3348                      data > xdp->data_end - ETH_HLEN))
3349                 return -EINVAL;
3350
3351         if (metalen)
3352                 memmove(xdp->data_meta + offset,
3353                         xdp->data_meta, metalen);
3354         xdp->data_meta += offset;
3355         xdp->data = data;
3356
3357         return 0;
3358 }
3359
3360 static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
3361         .func           = bpf_xdp_adjust_head,
3362         .gpl_only       = false,
3363         .ret_type       = RET_INTEGER,
3364         .arg1_type      = ARG_PTR_TO_CTX,
3365         .arg2_type      = ARG_ANYTHING,
3366 };
3367
3368 BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
3369 {
3370         void *data_end = xdp->data_end + offset;
3371
3372         /* only shrinking is allowed for now. */
3373         if (unlikely(offset >= 0))
3374                 return -EINVAL;
3375
3376         if (unlikely(data_end < xdp->data + ETH_HLEN))
3377                 return -EINVAL;
3378
3379         xdp->data_end = data_end;
3380
3381         return 0;
3382 }
3383
3384 static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
3385         .func           = bpf_xdp_adjust_tail,
3386         .gpl_only       = false,
3387         .ret_type       = RET_INTEGER,
3388         .arg1_type      = ARG_PTR_TO_CTX,
3389         .arg2_type      = ARG_ANYTHING,
3390 };
3391
3392 BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
3393 {
3394         void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3395         void *meta = xdp->data_meta + offset;
3396         unsigned long metalen = xdp->data - meta;
3397
3398         if (xdp_data_meta_unsupported(xdp))
3399                 return -ENOTSUPP;
3400         if (unlikely(meta < xdp_frame_end ||
3401                      meta > xdp->data))
3402                 return -EINVAL;
3403         if (unlikely((metalen & (sizeof(__u32) - 1)) ||
3404                      (metalen > 32)))
3405                 return -EACCES;
3406
3407         xdp->data_meta = meta;
3408
3409         return 0;
3410 }
3411
3412 static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
3413         .func           = bpf_xdp_adjust_meta,
3414         .gpl_only       = false,
3415         .ret_type       = RET_INTEGER,
3416         .arg1_type      = ARG_PTR_TO_CTX,
3417         .arg2_type      = ARG_ANYTHING,
3418 };
3419
3420 static int __bpf_tx_xdp(struct net_device *dev,
3421                         struct bpf_map *map,
3422                         struct xdp_buff *xdp,
3423                         u32 index)
3424 {
3425         struct xdp_frame *xdpf;
3426         int err, sent;
3427
3428         if (!dev->netdev_ops->ndo_xdp_xmit) {
3429                 return -EOPNOTSUPP;
3430         }
3431
3432         err = xdp_ok_fwd_dev(dev, xdp->data_end - xdp->data);
3433         if (unlikely(err))
3434                 return err;
3435
3436         xdpf = convert_to_xdp_frame(xdp);
3437         if (unlikely(!xdpf))
3438                 return -EOVERFLOW;
3439
3440         sent = dev->netdev_ops->ndo_xdp_xmit(dev, 1, &xdpf, XDP_XMIT_FLUSH);
3441         if (sent <= 0)
3442                 return sent;
3443         return 0;
3444 }
3445
3446 static noinline int
3447 xdp_do_redirect_slow(struct net_device *dev, struct xdp_buff *xdp,
3448                      struct bpf_prog *xdp_prog, struct bpf_redirect_info *ri)
3449 {
3450         struct net_device *fwd;
3451         u32 index = ri->ifindex;
3452         int err;
3453
3454         fwd = dev_get_by_index_rcu(dev_net(dev), index);
3455         ri->ifindex = 0;
3456         if (unlikely(!fwd)) {
3457                 err = -EINVAL;
3458                 goto err;
3459         }
3460
3461         err = __bpf_tx_xdp(fwd, NULL, xdp, 0);
3462         if (unlikely(err))
3463                 goto err;
3464
3465         _trace_xdp_redirect(dev, xdp_prog, index);
3466         return 0;
3467 err:
3468         _trace_xdp_redirect_err(dev, xdp_prog, index, err);
3469         return err;
3470 }
3471
3472 static int __bpf_tx_xdp_map(struct net_device *dev_rx, void *fwd,
3473                             struct bpf_map *map,
3474                             struct xdp_buff *xdp,
3475                             u32 index)
3476 {
3477         int err;
3478
3479         switch (map->map_type) {
3480         case BPF_MAP_TYPE_DEVMAP: {
3481                 struct bpf_dtab_netdev *dst = fwd;
3482
3483                 err = dev_map_enqueue(dst, xdp, dev_rx);
3484                 if (unlikely(err))
3485                         return err;
3486                 __dev_map_insert_ctx(map, index);
3487                 break;
3488         }
3489         case BPF_MAP_TYPE_CPUMAP: {
3490                 struct bpf_cpu_map_entry *rcpu = fwd;
3491
3492                 err = cpu_map_enqueue(rcpu, xdp, dev_rx);
3493                 if (unlikely(err))
3494                         return err;
3495                 __cpu_map_insert_ctx(map, index);
3496                 break;
3497         }
3498         case BPF_MAP_TYPE_XSKMAP: {
3499                 struct xdp_sock *xs = fwd;
3500
3501                 err = __xsk_map_redirect(map, xdp, xs);
3502                 return err;
3503         }
3504         default:
3505                 break;
3506         }
3507         return 0;
3508 }
3509
3510 void xdp_do_flush_map(void)
3511 {
3512         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3513         struct bpf_map *map = ri->map_to_flush;
3514
3515         ri->map_to_flush = NULL;
3516         if (map) {
3517                 switch (map->map_type) {
3518                 case BPF_MAP_TYPE_DEVMAP:
3519                         __dev_map_flush(map);
3520                         break;
3521                 case BPF_MAP_TYPE_CPUMAP:
3522                         __cpu_map_flush(map);
3523                         break;
3524                 case BPF_MAP_TYPE_XSKMAP:
3525                         __xsk_map_flush(map);
3526                         break;
3527                 default:
3528                         break;
3529                 }
3530         }
3531 }
3532 EXPORT_SYMBOL_GPL(xdp_do_flush_map);
3533
3534 static inline void *__xdp_map_lookup_elem(struct bpf_map *map, u32 index)
3535 {
3536         switch (map->map_type) {
3537         case BPF_MAP_TYPE_DEVMAP:
3538                 return __dev_map_lookup_elem(map, index);
3539         case BPF_MAP_TYPE_CPUMAP:
3540                 return __cpu_map_lookup_elem(map, index);
3541         case BPF_MAP_TYPE_XSKMAP:
3542                 return __xsk_map_lookup_elem(map, index);
3543         default:
3544                 return NULL;
3545         }
3546 }
3547
3548 void bpf_clear_redirect_map(struct bpf_map *map)
3549 {
3550         struct bpf_redirect_info *ri;
3551         int cpu;
3552
3553         for_each_possible_cpu(cpu) {
3554                 ri = per_cpu_ptr(&bpf_redirect_info, cpu);
3555                 /* Avoid polluting remote cacheline due to writes if
3556                  * not needed. Once we pass this test, we need the
3557                  * cmpxchg() to make sure it hasn't been changed in
3558                  * the meantime by remote CPU.
3559                  */
3560                 if (unlikely(READ_ONCE(ri->map) == map))
3561                         cmpxchg(&ri->map, map, NULL);
3562         }
3563 }
3564
3565 static int xdp_do_redirect_map(struct net_device *dev, struct xdp_buff *xdp,
3566                                struct bpf_prog *xdp_prog, struct bpf_map *map,
3567                                struct bpf_redirect_info *ri)
3568 {
3569         u32 index = ri->ifindex;
3570         void *fwd = NULL;
3571         int err;
3572
3573         ri->ifindex = 0;
3574         WRITE_ONCE(ri->map, NULL);
3575
3576         fwd = __xdp_map_lookup_elem(map, index);
3577         if (unlikely(!fwd)) {
3578                 err = -EINVAL;
3579                 goto err;
3580         }
3581         if (ri->map_to_flush && unlikely(ri->map_to_flush != map))
3582                 xdp_do_flush_map();
3583
3584         err = __bpf_tx_xdp_map(dev, fwd, map, xdp, index);
3585         if (unlikely(err))
3586                 goto err;
3587
3588         ri->map_to_flush = map;
3589         _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3590         return 0;
3591 err:
3592         _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3593         return err;
3594 }
3595
3596 int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
3597                     struct bpf_prog *xdp_prog)
3598 {
3599         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3600         struct bpf_map *map = READ_ONCE(ri->map);
3601
3602         if (likely(map))
3603                 return xdp_do_redirect_map(dev, xdp, xdp_prog, map, ri);
3604
3605         return xdp_do_redirect_slow(dev, xdp, xdp_prog, ri);
3606 }
3607 EXPORT_SYMBOL_GPL(xdp_do_redirect);
3608
3609 static int xdp_do_generic_redirect_map(struct net_device *dev,
3610                                        struct sk_buff *skb,
3611                                        struct xdp_buff *xdp,
3612                                        struct bpf_prog *xdp_prog,
3613                                        struct bpf_map *map)
3614 {
3615         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3616         u32 index = ri->ifindex;
3617         void *fwd = NULL;
3618         int err = 0;
3619
3620         ri->ifindex = 0;
3621         WRITE_ONCE(ri->map, NULL);
3622
3623         fwd = __xdp_map_lookup_elem(map, index);
3624         if (unlikely(!fwd)) {
3625                 err = -EINVAL;
3626                 goto err;
3627         }
3628
3629         if (map->map_type == BPF_MAP_TYPE_DEVMAP) {
3630                 struct bpf_dtab_netdev *dst = fwd;
3631
3632                 err = dev_map_generic_redirect(dst, skb, xdp_prog);
3633                 if (unlikely(err))
3634                         goto err;
3635         } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
3636                 struct xdp_sock *xs = fwd;
3637
3638                 err = xsk_generic_rcv(xs, xdp);
3639                 if (err)
3640                         goto err;
3641                 consume_skb(skb);
3642         } else {
3643                 /* TODO: Handle BPF_MAP_TYPE_CPUMAP */
3644                 err = -EBADRQC;
3645                 goto err;
3646         }
3647
3648         _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3649         return 0;
3650 err:
3651         _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3652         return err;
3653 }
3654
3655 int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
3656                             struct xdp_buff *xdp, struct bpf_prog *xdp_prog)
3657 {
3658         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3659         struct bpf_map *map = READ_ONCE(ri->map);
3660         u32 index = ri->ifindex;
3661         struct net_device *fwd;
3662         int err = 0;
3663
3664         if (map)
3665                 return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog,
3666                                                    map);
3667         ri->ifindex = 0;
3668         fwd = dev_get_by_index_rcu(dev_net(dev), index);
3669         if (unlikely(!fwd)) {
3670                 err = -EINVAL;
3671                 goto err;
3672         }
3673
3674         err = xdp_ok_fwd_dev(fwd, skb->len);
3675         if (unlikely(err))
3676                 goto err;
3677
3678         skb->dev = fwd;
3679         _trace_xdp_redirect(dev, xdp_prog, index);
3680         generic_xdp_tx(skb, xdp_prog);
3681         return 0;
3682 err:
3683         _trace_xdp_redirect_err(dev, xdp_prog, index, err);
3684         return err;
3685 }
3686 EXPORT_SYMBOL_GPL(xdp_do_generic_redirect);
3687
3688 BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
3689 {
3690         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3691
3692         if (unlikely(flags))
3693                 return XDP_ABORTED;
3694
3695         ri->ifindex = ifindex;
3696         ri->flags = flags;
3697         WRITE_ONCE(ri->map, NULL);
3698
3699         return XDP_REDIRECT;
3700 }
3701
3702 static const struct bpf_func_proto bpf_xdp_redirect_proto = {
3703         .func           = bpf_xdp_redirect,
3704         .gpl_only       = false,
3705         .ret_type       = RET_INTEGER,
3706         .arg1_type      = ARG_ANYTHING,
3707         .arg2_type      = ARG_ANYTHING,
3708 };
3709
3710 BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u32, ifindex,
3711            u64, flags)
3712 {
3713         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3714
3715         if (unlikely(flags))
3716                 return XDP_ABORTED;
3717
3718         ri->ifindex = ifindex;
3719         ri->flags = flags;
3720         WRITE_ONCE(ri->map, map);
3721
3722         return XDP_REDIRECT;
3723 }
3724
3725 static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
3726         .func           = bpf_xdp_redirect_map,
3727         .gpl_only       = false,
3728         .ret_type       = RET_INTEGER,
3729         .arg1_type      = ARG_CONST_MAP_PTR,
3730         .arg2_type      = ARG_ANYTHING,
3731         .arg3_type      = ARG_ANYTHING,
3732 };
3733
3734 static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
3735                                   unsigned long off, unsigned long len)
3736 {
3737         void *ptr = skb_header_pointer(skb, off, len, dst_buff);
3738
3739         if (unlikely(!ptr))
3740                 return len;
3741         if (ptr != dst_buff)
3742                 memcpy(dst_buff, ptr, len);
3743
3744         return 0;
3745 }
3746
3747 BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
3748            u64, flags, void *, meta, u64, meta_size)
3749 {
3750         u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
3751
3752         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
3753                 return -EINVAL;
3754         if (unlikely(skb_size > skb->len))
3755                 return -EFAULT;
3756
3757         return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
3758                                 bpf_skb_copy);
3759 }
3760
3761 static const struct bpf_func_proto bpf_skb_event_output_proto = {
3762         .func           = bpf_skb_event_output,
3763         .gpl_only       = true,
3764         .ret_type       = RET_INTEGER,
3765         .arg1_type      = ARG_PTR_TO_CTX,
3766         .arg2_type      = ARG_CONST_MAP_PTR,
3767         .arg3_type      = ARG_ANYTHING,
3768         .arg4_type      = ARG_PTR_TO_MEM,
3769         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
3770 };
3771
3772 static unsigned short bpf_tunnel_key_af(u64 flags)
3773 {
3774         return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
3775 }
3776
3777 BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
3778            u32, size, u64, flags)
3779 {
3780         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3781         u8 compat[sizeof(struct bpf_tunnel_key)];
3782         void *to_orig = to;
3783         int err;
3784
3785         if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) {
3786                 err = -EINVAL;
3787                 goto err_clear;
3788         }
3789         if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
3790                 err = -EPROTO;
3791                 goto err_clear;
3792         }
3793         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3794                 err = -EINVAL;
3795                 switch (size) {
3796                 case offsetof(struct bpf_tunnel_key, tunnel_label):
3797                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
3798                         goto set_compat;
3799                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3800                         /* Fixup deprecated structure layouts here, so we have
3801                          * a common path later on.
3802                          */
3803                         if (ip_tunnel_info_af(info) != AF_INET)
3804                                 goto err_clear;
3805 set_compat:
3806                         to = (struct bpf_tunnel_key *)compat;
3807                         break;
3808                 default:
3809                         goto err_clear;
3810                 }
3811         }
3812
3813         to->tunnel_id = be64_to_cpu(info->key.tun_id);
3814         to->tunnel_tos = info->key.tos;
3815         to->tunnel_ttl = info->key.ttl;
3816         to->tunnel_ext = 0;
3817
3818         if (flags & BPF_F_TUNINFO_IPV6) {
3819                 memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
3820                        sizeof(to->remote_ipv6));
3821                 to->tunnel_label = be32_to_cpu(info->key.label);
3822         } else {
3823                 to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
3824                 memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
3825                 to->tunnel_label = 0;
3826         }
3827
3828         if (unlikely(size != sizeof(struct bpf_tunnel_key)))
3829                 memcpy(to_orig, to, size);
3830
3831         return 0;
3832 err_clear:
3833         memset(to_orig, 0, size);
3834         return err;
3835 }
3836
3837 static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
3838         .func           = bpf_skb_get_tunnel_key,
3839         .gpl_only       = false,
3840         .ret_type       = RET_INTEGER,
3841         .arg1_type      = ARG_PTR_TO_CTX,
3842         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
3843         .arg3_type      = ARG_CONST_SIZE,
3844         .arg4_type      = ARG_ANYTHING,
3845 };
3846
3847 BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
3848 {
3849         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3850         int err;
3851
3852         if (unlikely(!info ||
3853                      !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
3854                 err = -ENOENT;
3855                 goto err_clear;
3856         }
3857         if (unlikely(size < info->options_len)) {
3858                 err = -ENOMEM;
3859                 goto err_clear;
3860         }
3861
3862         ip_tunnel_info_opts_get(to, info);
3863         if (size > info->options_len)
3864                 memset(to + info->options_len, 0, size - info->options_len);
3865
3866         return info->options_len;
3867 err_clear:
3868         memset(to, 0, size);
3869         return err;
3870 }
3871
3872 static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
3873         .func           = bpf_skb_get_tunnel_opt,
3874         .gpl_only       = false,
3875         .ret_type       = RET_INTEGER,
3876         .arg1_type      = ARG_PTR_TO_CTX,
3877         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
3878         .arg3_type      = ARG_CONST_SIZE,
3879 };
3880
3881 static struct metadata_dst __percpu *md_dst;
3882
3883 BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
3884            const struct bpf_tunnel_key *, from, u32, size, u64, flags)
3885 {
3886         struct metadata_dst *md = this_cpu_ptr(md_dst);
3887         u8 compat[sizeof(struct bpf_tunnel_key)];
3888         struct ip_tunnel_info *info;
3889
3890         if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
3891                                BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER)))
3892                 return -EINVAL;
3893         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3894                 switch (size) {
3895                 case offsetof(struct bpf_tunnel_key, tunnel_label):
3896                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
3897                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3898                         /* Fixup deprecated structure layouts here, so we have
3899                          * a common path later on.
3900                          */
3901                         memcpy(compat, from, size);
3902                         memset(compat + size, 0, sizeof(compat) - size);
3903                         from = (const struct bpf_tunnel_key *) compat;
3904                         break;
3905                 default:
3906                         return -EINVAL;
3907                 }
3908         }
3909         if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
3910                      from->tunnel_ext))
3911                 return -EINVAL;
3912
3913         skb_dst_drop(skb);
3914         dst_hold((struct dst_entry *) md);
3915         skb_dst_set(skb, (struct dst_entry *) md);
3916
3917         info = &md->u.tun_info;
3918         memset(info, 0, sizeof(*info));
3919         info->mode = IP_TUNNEL_INFO_TX;
3920
3921         info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
3922         if (flags & BPF_F_DONT_FRAGMENT)
3923                 info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;
3924         if (flags & BPF_F_ZERO_CSUM_TX)
3925                 info->key.tun_flags &= ~TUNNEL_CSUM;
3926         if (flags & BPF_F_SEQ_NUMBER)
3927                 info->key.tun_flags |= TUNNEL_SEQ;
3928
3929         info->key.tun_id = cpu_to_be64(from->tunnel_id);
3930         info->key.tos = from->tunnel_tos;
3931         info->key.ttl = from->tunnel_ttl;
3932
3933         if (flags & BPF_F_TUNINFO_IPV6) {
3934                 info->mode |= IP_TUNNEL_INFO_IPV6;
3935                 memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
3936                        sizeof(from->remote_ipv6));
3937                 info->key.label = cpu_to_be32(from->tunnel_label) &
3938                                   IPV6_FLOWLABEL_MASK;
3939         } else {
3940                 info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
3941         }
3942
3943         return 0;
3944 }
3945
3946 static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
3947         .func           = bpf_skb_set_tunnel_key,
3948         .gpl_only       = false,
3949         .ret_type       = RET_INTEGER,
3950         .arg1_type      = ARG_PTR_TO_CTX,
3951         .arg2_type      = ARG_PTR_TO_MEM,
3952         .arg3_type      = ARG_CONST_SIZE,
3953         .arg4_type      = ARG_ANYTHING,
3954 };
3955
3956 BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
3957            const u8 *, from, u32, size)
3958 {
3959         struct ip_tunnel_info *info = skb_tunnel_info(skb);
3960         const struct metadata_dst *md = this_cpu_ptr(md_dst);
3961
3962         if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
3963                 return -EINVAL;
3964         if (unlikely(size > IP_TUNNEL_OPTS_MAX))
3965                 return -ENOMEM;
3966
3967         ip_tunnel_info_opts_set(info, from, size, TUNNEL_OPTIONS_PRESENT);
3968
3969         return 0;
3970 }
3971
3972 static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
3973         .func           = bpf_skb_set_tunnel_opt,
3974         .gpl_only       = false,
3975         .ret_type       = RET_INTEGER,
3976         .arg1_type      = ARG_PTR_TO_CTX,
3977         .arg2_type      = ARG_PTR_TO_MEM,
3978         .arg3_type      = ARG_CONST_SIZE,
3979 };
3980
3981 static const struct bpf_func_proto *
3982 bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
3983 {
3984         if (!md_dst) {
3985                 struct metadata_dst __percpu *tmp;
3986
3987                 tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
3988                                                 METADATA_IP_TUNNEL,
3989                                                 GFP_KERNEL);
3990                 if (!tmp)
3991                         return NULL;
3992                 if (cmpxchg(&md_dst, NULL, tmp))
3993                         metadata_dst_free_percpu(tmp);
3994         }
3995
3996         switch (which) {
3997         case BPF_FUNC_skb_set_tunnel_key:
3998                 return &bpf_skb_set_tunnel_key_proto;
3999         case BPF_FUNC_skb_set_tunnel_opt:
4000                 return &bpf_skb_set_tunnel_opt_proto;
4001         default:
4002                 return NULL;
4003         }
4004 }
4005
4006 BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
4007            u32, idx)
4008 {
4009         struct bpf_array *array = container_of(map, struct bpf_array, map);
4010         struct cgroup *cgrp;
4011         struct sock *sk;
4012
4013         sk = skb_to_full_sk(skb);
4014         if (!sk || !sk_fullsock(sk))
4015                 return -ENOENT;
4016         if (unlikely(idx >= array->map.max_entries))
4017                 return -E2BIG;
4018
4019         cgrp = READ_ONCE(array->ptrs[idx]);
4020         if (unlikely(!cgrp))
4021                 return -EAGAIN;
4022
4023         return sk_under_cgroup_hierarchy(sk, cgrp);
4024 }
4025
4026 static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
4027         .func           = bpf_skb_under_cgroup,
4028         .gpl_only       = false,
4029         .ret_type       = RET_INTEGER,
4030         .arg1_type      = ARG_PTR_TO_CTX,
4031         .arg2_type      = ARG_CONST_MAP_PTR,
4032         .arg3_type      = ARG_ANYTHING,
4033 };
4034
4035 #ifdef CONFIG_SOCK_CGROUP_DATA
4036 BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
4037 {
4038         struct sock *sk = skb_to_full_sk(skb);
4039         struct cgroup *cgrp;
4040
4041         if (!sk || !sk_fullsock(sk))
4042                 return 0;
4043
4044         cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4045         return cgrp->kn->id.id;
4046 }
4047
4048 static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
4049         .func           = bpf_skb_cgroup_id,
4050         .gpl_only       = false,
4051         .ret_type       = RET_INTEGER,
4052         .arg1_type      = ARG_PTR_TO_CTX,
4053 };
4054
4055 BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
4056            ancestor_level)
4057 {
4058         struct sock *sk = skb_to_full_sk(skb);
4059         struct cgroup *ancestor;
4060         struct cgroup *cgrp;
4061
4062         if (!sk || !sk_fullsock(sk))
4063                 return 0;
4064
4065         cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4066         ancestor = cgroup_ancestor(cgrp, ancestor_level);
4067         if (!ancestor)
4068                 return 0;
4069
4070         return ancestor->kn->id.id;
4071 }
4072
4073 static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
4074         .func           = bpf_skb_ancestor_cgroup_id,
4075         .gpl_only       = false,
4076         .ret_type       = RET_INTEGER,
4077         .arg1_type      = ARG_PTR_TO_CTX,
4078         .arg2_type      = ARG_ANYTHING,
4079 };
4080 #endif
4081
4082 static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff,
4083                                   unsigned long off, unsigned long len)
4084 {
4085         memcpy(dst_buff, src_buff + off, len);
4086         return 0;
4087 }
4088
4089 BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
4090            u64, flags, void *, meta, u64, meta_size)
4091 {
4092         u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
4093
4094         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
4095                 return -EINVAL;
4096         if (unlikely(xdp_size > (unsigned long)(xdp->data_end - xdp->data)))
4097                 return -EFAULT;
4098
4099         return bpf_event_output(map, flags, meta, meta_size, xdp->data,
4100                                 xdp_size, bpf_xdp_copy);
4101 }
4102
4103 static const struct bpf_func_proto bpf_xdp_event_output_proto = {
4104         .func           = bpf_xdp_event_output,
4105         .gpl_only       = true,
4106         .ret_type       = RET_INTEGER,
4107         .arg1_type      = ARG_PTR_TO_CTX,
4108         .arg2_type      = ARG_CONST_MAP_PTR,
4109         .arg3_type      = ARG_ANYTHING,
4110         .arg4_type      = ARG_PTR_TO_MEM,
4111         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
4112 };
4113
4114 BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
4115 {
4116         return skb->sk ? sock_gen_cookie(skb->sk) : 0;
4117 }
4118
4119 static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
4120         .func           = bpf_get_socket_cookie,
4121         .gpl_only       = false,
4122         .ret_type       = RET_INTEGER,
4123         .arg1_type      = ARG_PTR_TO_CTX,
4124 };
4125
4126 BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
4127 {
4128         return sock_gen_cookie(ctx->sk);
4129 }
4130
4131 static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
4132         .func           = bpf_get_socket_cookie_sock_addr,
4133         .gpl_only       = false,
4134         .ret_type       = RET_INTEGER,
4135         .arg1_type      = ARG_PTR_TO_CTX,
4136 };
4137
4138 BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
4139 {
4140         return sock_gen_cookie(ctx->sk);
4141 }
4142
4143 static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
4144         .func           = bpf_get_socket_cookie_sock_ops,
4145         .gpl_only       = false,
4146         .ret_type       = RET_INTEGER,
4147         .arg1_type      = ARG_PTR_TO_CTX,
4148 };
4149
4150 BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
4151 {
4152         struct sock *sk = sk_to_full_sk(skb->sk);
4153         kuid_t kuid;
4154
4155         if (!sk || !sk_fullsock(sk))
4156                 return overflowuid;
4157         kuid = sock_net_uid(sock_net(sk), sk);
4158         return from_kuid_munged(sock_net(sk)->user_ns, kuid);
4159 }
4160
4161 static const struct bpf_func_proto bpf_get_socket_uid_proto = {
4162         .func           = bpf_get_socket_uid,
4163         .gpl_only       = false,
4164         .ret_type       = RET_INTEGER,
4165         .arg1_type      = ARG_PTR_TO_CTX,
4166 };
4167
4168 BPF_CALL_5(bpf_sockopt_event_output, struct bpf_sock_ops_kern *, bpf_sock,
4169            struct bpf_map *, map, u64, flags, void *, data, u64, size)
4170 {
4171         if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
4172                 return -EINVAL;
4173
4174         return bpf_event_output(map, flags, data, size, NULL, 0, NULL);
4175 }
4176
4177 static const struct bpf_func_proto bpf_sockopt_event_output_proto =  {
4178         .func           = bpf_sockopt_event_output,
4179         .gpl_only       = true,
4180         .ret_type       = RET_INTEGER,
4181         .arg1_type      = ARG_PTR_TO_CTX,
4182         .arg2_type      = ARG_CONST_MAP_PTR,
4183         .arg3_type      = ARG_ANYTHING,
4184         .arg4_type      = ARG_PTR_TO_MEM,
4185         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
4186 };
4187
4188 BPF_CALL_5(bpf_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4189            int, level, int, optname, char *, optval, int, optlen)
4190 {
4191         struct sock *sk = bpf_sock->sk;
4192         int ret = 0;
4193         int val;
4194
4195         if (!sk_fullsock(sk))
4196                 return -EINVAL;
4197
4198         if (level == SOL_SOCKET) {
4199                 if (optlen != sizeof(int))
4200                         return -EINVAL;
4201                 val = *((int *)optval);
4202
4203                 /* Only some socketops are supported */
4204                 switch (optname) {
4205                 case SO_RCVBUF:
4206                         val = min_t(u32, val, sysctl_rmem_max);
4207                         sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
4208                         sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);
4209                         break;
4210                 case SO_SNDBUF:
4211                         val = min_t(u32, val, sysctl_wmem_max);
4212                         sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
4213                         sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
4214                         break;
4215                 case SO_MAX_PACING_RATE: /* 32bit version */
4216                         if (val != ~0U)
4217                                 cmpxchg(&sk->sk_pacing_status,
4218                                         SK_PACING_NONE,
4219                                         SK_PACING_NEEDED);
4220                         sk->sk_max_pacing_rate = (val == ~0U) ? ~0UL : val;
4221                         sk->sk_pacing_rate = min(sk->sk_pacing_rate,
4222                                                  sk->sk_max_pacing_rate);
4223                         break;
4224                 case SO_PRIORITY:
4225                         sk->sk_priority = val;
4226                         break;
4227                 case SO_RCVLOWAT:
4228                         if (val < 0)
4229                                 val = INT_MAX;
4230                         sk->sk_rcvlowat = val ? : 1;
4231                         break;
4232                 case SO_MARK:
4233                         if (sk->sk_mark != val) {
4234                                 sk->sk_mark = val;
4235                                 sk_dst_reset(sk);
4236                         }
4237                         break;
4238                 default:
4239                         ret = -EINVAL;
4240                 }
4241 #ifdef CONFIG_INET
4242         } else if (level == SOL_IP) {
4243                 if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4244                         return -EINVAL;
4245
4246                 val = *((int *)optval);
4247                 /* Only some options are supported */
4248                 switch (optname) {
4249                 case IP_TOS:
4250                         if (val < -1 || val > 0xff) {
4251                                 ret = -EINVAL;
4252                         } else {
4253                                 struct inet_sock *inet = inet_sk(sk);
4254
4255                                 if (val == -1)
4256                                         val = 0;
4257                                 inet->tos = val;
4258                         }
4259                         break;
4260                 default:
4261                         ret = -EINVAL;
4262                 }
4263 #if IS_ENABLED(CONFIG_IPV6)
4264         } else if (level == SOL_IPV6) {
4265                 if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4266                         return -EINVAL;
4267
4268                 val = *((int *)optval);
4269                 /* Only some options are supported */
4270                 switch (optname) {
4271                 case IPV6_TCLASS:
4272                         if (val < -1 || val > 0xff) {
4273                                 ret = -EINVAL;
4274                         } else {
4275                                 struct ipv6_pinfo *np = inet6_sk(sk);
4276
4277                                 if (val == -1)
4278                                         val = 0;
4279                                 np->tclass = val;
4280                         }
4281                         break;
4282                 default:
4283                         ret = -EINVAL;
4284                 }
4285 #endif
4286         } else if (level == SOL_TCP &&
4287                    sk->sk_prot->setsockopt == tcp_setsockopt) {
4288                 if (optname == TCP_CONGESTION) {
4289                         char name[TCP_CA_NAME_MAX];
4290                         bool reinit = bpf_sock->op > BPF_SOCK_OPS_NEEDS_ECN;
4291
4292                         strncpy(name, optval, min_t(long, optlen,
4293                                                     TCP_CA_NAME_MAX-1));
4294                         name[TCP_CA_NAME_MAX-1] = 0;
4295                         ret = tcp_set_congestion_control(sk, name, false,
4296                                                          reinit);
4297                 } else {
4298                         struct tcp_sock *tp = tcp_sk(sk);
4299
4300                         if (optlen != sizeof(int))
4301                                 return -EINVAL;
4302
4303                         val = *((int *)optval);
4304                         /* Only some options are supported */
4305                         switch (optname) {
4306                         case TCP_BPF_IW:
4307                                 if (val <= 0 || tp->data_segs_out > tp->syn_data)
4308                                         ret = -EINVAL;
4309                                 else
4310                                         tp->snd_cwnd = val;
4311                                 break;
4312                         case TCP_BPF_SNDCWND_CLAMP:
4313                                 if (val <= 0) {
4314                                         ret = -EINVAL;
4315                                 } else {
4316                                         tp->snd_cwnd_clamp = val;
4317                                         tp->snd_ssthresh = val;
4318                                 }
4319                                 break;
4320                         case TCP_SAVE_SYN:
4321                                 if (val < 0 || val > 1)
4322                                         ret = -EINVAL;
4323                                 else
4324                                         tp->save_syn = val;
4325                                 break;
4326                         default:
4327                                 ret = -EINVAL;
4328                         }
4329                 }
4330 #endif
4331         } else {
4332                 ret = -EINVAL;
4333         }
4334         return ret;
4335 }
4336
4337 static const struct bpf_func_proto bpf_setsockopt_proto = {
4338         .func           = bpf_setsockopt,
4339         .gpl_only       = false,
4340         .ret_type       = RET_INTEGER,
4341         .arg1_type      = ARG_PTR_TO_CTX,
4342         .arg2_type      = ARG_ANYTHING,
4343         .arg3_type      = ARG_ANYTHING,
4344         .arg4_type      = ARG_PTR_TO_MEM,
4345         .arg5_type      = ARG_CONST_SIZE,
4346 };
4347
4348 BPF_CALL_5(bpf_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4349            int, level, int, optname, char *, optval, int, optlen)
4350 {
4351         struct sock *sk = bpf_sock->sk;
4352
4353         if (!sk_fullsock(sk))
4354                 goto err_clear;
4355 #ifdef CONFIG_INET
4356         if (level == SOL_TCP && sk->sk_prot->getsockopt == tcp_getsockopt) {
4357                 struct inet_connection_sock *icsk;
4358                 struct tcp_sock *tp;
4359
4360                 switch (optname) {
4361                 case TCP_CONGESTION:
4362                         icsk = inet_csk(sk);
4363
4364                         if (!icsk->icsk_ca_ops || optlen <= 1)
4365                                 goto err_clear;
4366                         strncpy(optval, icsk->icsk_ca_ops->name, optlen);
4367                         optval[optlen - 1] = 0;
4368                         break;
4369                 case TCP_SAVED_SYN:
4370                         tp = tcp_sk(sk);
4371
4372                         if (optlen <= 0 || !tp->saved_syn ||
4373                             optlen > tp->saved_syn[0])
4374                                 goto err_clear;
4375                         memcpy(optval, tp->saved_syn + 1, optlen);
4376                         break;
4377                 default:
4378                         goto err_clear;
4379                 }
4380         } else if (level == SOL_IP) {
4381                 struct inet_sock *inet = inet_sk(sk);
4382
4383                 if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4384                         goto err_clear;
4385
4386                 /* Only some options are supported */
4387                 switch (optname) {
4388                 case IP_TOS:
4389                         *((int *)optval) = (int)inet->tos;
4390                         break;
4391                 default:
4392                         goto err_clear;
4393                 }
4394 #if IS_ENABLED(CONFIG_IPV6)
4395         } else if (level == SOL_IPV6) {
4396                 struct ipv6_pinfo *np = inet6_sk(sk);
4397
4398                 if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4399                         goto err_clear;
4400
4401                 /* Only some options are supported */
4402                 switch (optname) {
4403                 case IPV6_TCLASS:
4404                         *((int *)optval) = (int)np->tclass;
4405                         break;
4406                 default:
4407                         goto err_clear;
4408                 }
4409 #endif
4410         } else {
4411                 goto err_clear;
4412         }
4413         return 0;
4414 #endif
4415 err_clear:
4416         memset(optval, 0, optlen);
4417         return -EINVAL;
4418 }
4419
4420 static const struct bpf_func_proto bpf_getsockopt_proto = {
4421         .func           = bpf_getsockopt,
4422         .gpl_only       = false,
4423         .ret_type       = RET_INTEGER,
4424         .arg1_type      = ARG_PTR_TO_CTX,
4425         .arg2_type      = ARG_ANYTHING,
4426         .arg3_type      = ARG_ANYTHING,
4427         .arg4_type      = ARG_PTR_TO_UNINIT_MEM,
4428         .arg5_type      = ARG_CONST_SIZE,
4429 };
4430
4431 BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
4432            int, argval)
4433 {
4434         struct sock *sk = bpf_sock->sk;
4435         int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
4436
4437         if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
4438                 return -EINVAL;
4439
4440         if (val)
4441                 tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
4442
4443         return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
4444 }
4445
4446 static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
4447         .func           = bpf_sock_ops_cb_flags_set,
4448         .gpl_only       = false,
4449         .ret_type       = RET_INTEGER,
4450         .arg1_type      = ARG_PTR_TO_CTX,
4451         .arg2_type      = ARG_ANYTHING,
4452 };
4453
4454 const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly;
4455 EXPORT_SYMBOL_GPL(ipv6_bpf_stub);
4456
4457 BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
4458            int, addr_len)
4459 {
4460 #ifdef CONFIG_INET
4461         struct sock *sk = ctx->sk;
4462         int err;
4463
4464         /* Binding to port can be expensive so it's prohibited in the helper.
4465          * Only binding to IP is supported.
4466          */
4467         err = -EINVAL;
4468         if (addr->sa_family == AF_INET) {
4469                 if (addr_len < sizeof(struct sockaddr_in))
4470                         return err;
4471                 if (((struct sockaddr_in *)addr)->sin_port != htons(0))
4472                         return err;
4473                 return __inet_bind(sk, addr, addr_len, true, false);
4474 #if IS_ENABLED(CONFIG_IPV6)
4475         } else if (addr->sa_family == AF_INET6) {
4476                 if (addr_len < SIN6_LEN_RFC2133)
4477                         return err;
4478                 if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
4479                         return err;
4480                 /* ipv6_bpf_stub cannot be NULL, since it's called from
4481                  * bpf_cgroup_inet6_connect hook and ipv6 is already loaded
4482                  */
4483                 return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, true, false);
4484 #endif /* CONFIG_IPV6 */
4485         }
4486 #endif /* CONFIG_INET */
4487
4488         return -EAFNOSUPPORT;
4489 }
4490
4491 static const struct bpf_func_proto bpf_bind_proto = {
4492         .func           = bpf_bind,
4493         .gpl_only       = false,
4494         .ret_type       = RET_INTEGER,
4495         .arg1_type      = ARG_PTR_TO_CTX,
4496         .arg2_type      = ARG_PTR_TO_MEM,
4497         .arg3_type      = ARG_CONST_SIZE,
4498 };
4499
4500 #ifdef CONFIG_XFRM
4501 BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
4502            struct bpf_xfrm_state *, to, u32, size, u64, flags)
4503 {
4504         const struct sec_path *sp = skb_sec_path(skb);
4505         const struct xfrm_state *x;
4506
4507         if (!sp || unlikely(index >= sp->len || flags))
4508                 goto err_clear;
4509
4510         x = sp->xvec[index];
4511
4512         if (unlikely(size != sizeof(struct bpf_xfrm_state)))
4513                 goto err_clear;
4514
4515         to->reqid = x->props.reqid;
4516         to->spi = x->id.spi;
4517         to->family = x->props.family;
4518         to->ext = 0;
4519
4520         if (to->family == AF_INET6) {
4521                 memcpy(to->remote_ipv6, x->props.saddr.a6,
4522                        sizeof(to->remote_ipv6));
4523         } else {
4524                 to->remote_ipv4 = x->props.saddr.a4;
4525                 memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4526         }
4527
4528         return 0;
4529 err_clear:
4530         memset(to, 0, size);
4531         return -EINVAL;
4532 }
4533
4534 static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
4535         .func           = bpf_skb_get_xfrm_state,
4536         .gpl_only       = false,
4537         .ret_type       = RET_INTEGER,
4538         .arg1_type      = ARG_PTR_TO_CTX,
4539         .arg2_type      = ARG_ANYTHING,
4540         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
4541         .arg4_type      = ARG_CONST_SIZE,
4542         .arg5_type      = ARG_ANYTHING,
4543 };
4544 #endif
4545
4546 #if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
4547 static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params,
4548                                   const struct neighbour *neigh,
4549                                   const struct net_device *dev)
4550 {
4551         memcpy(params->dmac, neigh->ha, ETH_ALEN);
4552         memcpy(params->smac, dev->dev_addr, ETH_ALEN);
4553         params->h_vlan_TCI = 0;
4554         params->h_vlan_proto = 0;
4555         params->ifindex = dev->ifindex;
4556
4557         return 0;
4558 }
4559 #endif
4560
4561 #if IS_ENABLED(CONFIG_INET)
4562 static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4563                                u32 flags, bool check_mtu)
4564 {
4565         struct fib_nh_common *nhc;
4566         struct in_device *in_dev;
4567         struct neighbour *neigh;
4568         struct net_device *dev;
4569         struct fib_result res;
4570         struct flowi4 fl4;
4571         int err;
4572         u32 mtu;
4573
4574         dev = dev_get_by_index_rcu(net, params->ifindex);
4575         if (unlikely(!dev))
4576                 return -ENODEV;
4577
4578         /* verify forwarding is enabled on this interface */
4579         in_dev = __in_dev_get_rcu(dev);
4580         if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
4581                 return BPF_FIB_LKUP_RET_FWD_DISABLED;
4582
4583         if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4584                 fl4.flowi4_iif = 1;
4585                 fl4.flowi4_oif = params->ifindex;
4586         } else {
4587                 fl4.flowi4_iif = params->ifindex;
4588                 fl4.flowi4_oif = 0;
4589         }
4590         fl4.flowi4_tos = params->tos & IPTOS_RT_MASK;
4591         fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
4592         fl4.flowi4_flags = 0;
4593
4594         fl4.flowi4_proto = params->l4_protocol;
4595         fl4.daddr = params->ipv4_dst;
4596         fl4.saddr = params->ipv4_src;
4597         fl4.fl4_sport = params->sport;
4598         fl4.fl4_dport = params->dport;
4599
4600         if (flags & BPF_FIB_LOOKUP_DIRECT) {
4601                 u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4602                 struct fib_table *tb;
4603
4604                 tb = fib_get_table(net, tbid);
4605                 if (unlikely(!tb))
4606                         return BPF_FIB_LKUP_RET_NOT_FWDED;
4607
4608                 err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
4609         } else {
4610                 fl4.flowi4_mark = 0;
4611                 fl4.flowi4_secid = 0;
4612                 fl4.flowi4_tun_key.tun_id = 0;
4613                 fl4.flowi4_uid = sock_net_uid(net, NULL);
4614
4615                 err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
4616         }
4617
4618         if (err) {
4619                 /* map fib lookup errors to RTN_ type */
4620                 if (err == -EINVAL)
4621                         return BPF_FIB_LKUP_RET_BLACKHOLE;
4622                 if (err == -EHOSTUNREACH)
4623                         return BPF_FIB_LKUP_RET_UNREACHABLE;
4624                 if (err == -EACCES)
4625                         return BPF_FIB_LKUP_RET_PROHIBIT;
4626
4627                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4628         }
4629
4630         if (res.type != RTN_UNICAST)
4631                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4632
4633         if (res.fi->fib_nhs > 1)
4634                 fib_select_path(net, &res, &fl4, NULL);
4635
4636         if (check_mtu) {
4637                 mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
4638                 if (params->tot_len > mtu)
4639                         return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4640         }
4641
4642         nhc = res.nhc;
4643
4644         /* do not handle lwt encaps right now */
4645         if (nhc->nhc_lwtstate)
4646                 return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4647
4648         dev = nhc->nhc_dev;
4649
4650         params->rt_metric = res.fi->fib_priority;
4651
4652         /* xdp and cls_bpf programs are run in RCU-bh so
4653          * rcu_read_lock_bh is not needed here
4654          */
4655         if (likely(nhc->nhc_gw_family != AF_INET6)) {
4656                 if (nhc->nhc_gw_family)
4657                         params->ipv4_dst = nhc->nhc_gw.ipv4;
4658
4659                 neigh = __ipv4_neigh_lookup_noref(dev,
4660                                                  (__force u32)params->ipv4_dst);
4661         } else {
4662                 struct in6_addr *dst = (struct in6_addr *)params->ipv6_dst;
4663
4664                 params->family = AF_INET6;
4665                 *dst = nhc->nhc_gw.ipv6;
4666                 neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
4667         }
4668
4669         if (!neigh)
4670                 return BPF_FIB_LKUP_RET_NO_NEIGH;
4671
4672         return bpf_fib_set_fwd_params(params, neigh, dev);
4673 }
4674 #endif
4675
4676 #if IS_ENABLED(CONFIG_IPV6)
4677 static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4678                                u32 flags, bool check_mtu)
4679 {
4680         struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
4681         struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
4682         struct neighbour *neigh;
4683         struct net_device *dev;
4684         struct inet6_dev *idev;
4685         struct fib6_info *f6i;
4686         struct flowi6 fl6;
4687         int strict = 0;
4688         int oif;
4689         u32 mtu;
4690
4691         /* link local addresses are never forwarded */
4692         if (rt6_need_strict(dst) || rt6_need_strict(src))
4693                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4694
4695         dev = dev_get_by_index_rcu(net, params->ifindex);
4696         if (unlikely(!dev))
4697                 return -ENODEV;
4698
4699         idev = __in6_dev_get_safely(dev);
4700         if (unlikely(!idev || !net->ipv6.devconf_all->forwarding))
4701                 return BPF_FIB_LKUP_RET_FWD_DISABLED;
4702
4703         if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4704                 fl6.flowi6_iif = 1;
4705                 oif = fl6.flowi6_oif = params->ifindex;
4706         } else {
4707                 oif = fl6.flowi6_iif = params->ifindex;
4708                 fl6.flowi6_oif = 0;
4709                 strict = RT6_LOOKUP_F_HAS_SADDR;
4710         }
4711         fl6.flowlabel = params->flowinfo;
4712         fl6.flowi6_scope = 0;
4713         fl6.flowi6_flags = 0;
4714         fl6.mp_hash = 0;
4715
4716         fl6.flowi6_proto = params->l4_protocol;
4717         fl6.daddr = *dst;
4718         fl6.saddr = *src;
4719         fl6.fl6_sport = params->sport;
4720         fl6.fl6_dport = params->dport;
4721
4722         if (flags & BPF_FIB_LOOKUP_DIRECT) {
4723                 u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4724                 struct fib6_table *tb;
4725
4726                 tb = ipv6_stub->fib6_get_table(net, tbid);
4727                 if (unlikely(!tb))
4728                         return BPF_FIB_LKUP_RET_NOT_FWDED;
4729
4730                 f6i = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, strict);
4731         } else {
4732                 fl6.flowi6_mark = 0;
4733                 fl6.flowi6_secid = 0;
4734                 fl6.flowi6_tun_key.tun_id = 0;
4735                 fl6.flowi6_uid = sock_net_uid(net, NULL);
4736
4737                 f6i = ipv6_stub->fib6_lookup(net, oif, &fl6, strict);
4738         }
4739
4740         if (unlikely(IS_ERR_OR_NULL(f6i) || f6i == net->ipv6.fib6_null_entry))
4741                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4742
4743         if (unlikely(f6i->fib6_flags & RTF_REJECT)) {
4744                 switch (f6i->fib6_type) {
4745                 case RTN_BLACKHOLE:
4746                         return BPF_FIB_LKUP_RET_BLACKHOLE;
4747                 case RTN_UNREACHABLE:
4748                         return BPF_FIB_LKUP_RET_UNREACHABLE;
4749                 case RTN_PROHIBIT:
4750                         return BPF_FIB_LKUP_RET_PROHIBIT;
4751                 default:
4752                         return BPF_FIB_LKUP_RET_NOT_FWDED;
4753                 }
4754         }
4755
4756         if (f6i->fib6_type != RTN_UNICAST)
4757                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4758
4759         if (f6i->fib6_nsiblings && fl6.flowi6_oif == 0)
4760                 f6i = ipv6_stub->fib6_multipath_select(net, f6i, &fl6,
4761                                                        fl6.flowi6_oif, NULL,
4762                                                        strict);
4763
4764         if (check_mtu) {
4765                 mtu = ipv6_stub->ip6_mtu_from_fib6(f6i, dst, src);
4766                 if (params->tot_len > mtu)
4767                         return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4768         }
4769
4770         if (f6i->fib6_nh.fib_nh_lws)
4771                 return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4772
4773         if (f6i->fib6_nh.fib_nh_gw_family)
4774                 *dst = f6i->fib6_nh.fib_nh_gw6;
4775
4776         dev = f6i->fib6_nh.fib_nh_dev;
4777         params->rt_metric = f6i->fib6_metric;
4778
4779         /* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
4780          * not needed here.
4781          */
4782         neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
4783         if (!neigh)
4784                 return BPF_FIB_LKUP_RET_NO_NEIGH;
4785
4786         return bpf_fib_set_fwd_params(params, neigh, dev);
4787 }
4788 #endif
4789
4790 BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
4791            struct bpf_fib_lookup *, params, int, plen, u32, flags)
4792 {
4793         if (plen < sizeof(*params))
4794                 return -EINVAL;
4795
4796         if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4797                 return -EINVAL;
4798
4799         switch (params->family) {
4800 #if IS_ENABLED(CONFIG_INET)
4801         case AF_INET:
4802                 return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
4803                                            flags, true);
4804 #endif
4805 #if IS_ENABLED(CONFIG_IPV6)
4806         case AF_INET6:
4807                 return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
4808                                            flags, true);
4809 #endif
4810         }
4811         return -EAFNOSUPPORT;
4812 }
4813
4814 static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
4815         .func           = bpf_xdp_fib_lookup,
4816         .gpl_only       = true,
4817         .ret_type       = RET_INTEGER,
4818         .arg1_type      = ARG_PTR_TO_CTX,
4819         .arg2_type      = ARG_PTR_TO_MEM,
4820         .arg3_type      = ARG_CONST_SIZE,
4821         .arg4_type      = ARG_ANYTHING,
4822 };
4823
4824 BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
4825            struct bpf_fib_lookup *, params, int, plen, u32, flags)
4826 {
4827         struct net *net = dev_net(skb->dev);
4828         int rc = -EAFNOSUPPORT;
4829
4830         if (plen < sizeof(*params))
4831                 return -EINVAL;
4832
4833         if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4834                 return -EINVAL;
4835
4836         switch (params->family) {
4837 #if IS_ENABLED(CONFIG_INET)
4838         case AF_INET:
4839                 rc = bpf_ipv4_fib_lookup(net, params, flags, false);
4840                 break;
4841 #endif
4842 #if IS_ENABLED(CONFIG_IPV6)
4843         case AF_INET6:
4844                 rc = bpf_ipv6_fib_lookup(net, params, flags, false);
4845                 break;
4846 #endif
4847         }
4848
4849         if (!rc) {
4850                 struct net_device *dev;
4851
4852                 dev = dev_get_by_index_rcu(net, params->ifindex);
4853                 if (!is_skb_forwardable(dev, skb))
4854                         rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
4855         }
4856
4857         return rc;
4858 }
4859
4860 static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
4861         .func           = bpf_skb_fib_lookup,
4862         .gpl_only       = true,
4863         .ret_type       = RET_INTEGER,
4864         .arg1_type      = ARG_PTR_TO_CTX,
4865         .arg2_type      = ARG_PTR_TO_MEM,
4866         .arg3_type      = ARG_CONST_SIZE,
4867         .arg4_type      = ARG_ANYTHING,
4868 };
4869
4870 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4871 static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
4872 {
4873         int err;
4874         struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;
4875
4876         if (!seg6_validate_srh(srh, len))
4877                 return -EINVAL;
4878
4879         switch (type) {
4880         case BPF_LWT_ENCAP_SEG6_INLINE:
4881                 if (skb->protocol != htons(ETH_P_IPV6))
4882                         return -EBADMSG;
4883
4884                 err = seg6_do_srh_inline(skb, srh);
4885                 break;
4886         case BPF_LWT_ENCAP_SEG6:
4887                 skb_reset_inner_headers(skb);
4888                 skb->encapsulation = 1;
4889                 err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
4890                 break;
4891         default:
4892                 return -EINVAL;
4893         }
4894
4895         bpf_compute_data_pointers(skb);
4896         if (err)
4897                 return err;
4898
4899         ipv6_hdr(skb)->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
4900         skb_set_transport_header(skb, sizeof(struct ipv6hdr));
4901
4902         return seg6_lookup_nexthop(skb, NULL, 0);
4903 }
4904 #endif /* CONFIG_IPV6_SEG6_BPF */
4905
4906 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
4907 static int bpf_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len,
4908                              bool ingress)
4909 {
4910         return bpf_lwt_push_ip_encap(skb, hdr, len, ingress);
4911 }
4912 #endif
4913
4914 BPF_CALL_4(bpf_lwt_in_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
4915            u32, len)
4916 {
4917         switch (type) {
4918 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4919         case BPF_LWT_ENCAP_SEG6:
4920         case BPF_LWT_ENCAP_SEG6_INLINE:
4921                 return bpf_push_seg6_encap(skb, type, hdr, len);
4922 #endif
4923 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
4924         case BPF_LWT_ENCAP_IP:
4925                 return bpf_push_ip_encap(skb, hdr, len, true /* ingress */);
4926 #endif
4927         default:
4928                 return -EINVAL;
4929         }
4930 }
4931
4932 BPF_CALL_4(bpf_lwt_xmit_push_encap, struct sk_buff *, skb, u32, type,
4933            void *, hdr, u32, len)
4934 {
4935         switch (type) {
4936 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
4937         case BPF_LWT_ENCAP_IP:
4938                 return bpf_push_ip_encap(skb, hdr, len, false /* egress */);
4939 #endif
4940         default:
4941                 return -EINVAL;
4942         }
4943 }
4944
4945 static const struct bpf_func_proto bpf_lwt_in_push_encap_proto = {
4946         .func           = bpf_lwt_in_push_encap,
4947         .gpl_only       = false,
4948         .ret_type       = RET_INTEGER,
4949         .arg1_type      = ARG_PTR_TO_CTX,
4950         .arg2_type      = ARG_ANYTHING,
4951         .arg3_type      = ARG_PTR_TO_MEM,
4952         .arg4_type      = ARG_CONST_SIZE
4953 };
4954
4955 static const struct bpf_func_proto bpf_lwt_xmit_push_encap_proto = {
4956         .func           = bpf_lwt_xmit_push_encap,
4957         .gpl_only       = false,
4958         .ret_type       = RET_INTEGER,
4959         .arg1_type      = ARG_PTR_TO_CTX,
4960         .arg2_type      = ARG_ANYTHING,
4961         .arg3_type      = ARG_PTR_TO_MEM,
4962         .arg4_type      = ARG_CONST_SIZE
4963 };
4964
4965 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4966 BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
4967            const void *, from, u32, len)
4968 {
4969         struct seg6_bpf_srh_state *srh_state =
4970                 this_cpu_ptr(&seg6_bpf_srh_states);
4971         struct ipv6_sr_hdr *srh = srh_state->srh;
4972         void *srh_tlvs, *srh_end, *ptr;
4973         int srhoff = 0;
4974
4975         if (srh == NULL)
4976                 return -EINVAL;
4977
4978         srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
4979         srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
4980
4981         ptr = skb->data + offset;
4982         if (ptr >= srh_tlvs && ptr + len <= srh_end)
4983                 srh_state->valid = false;
4984         else if (ptr < (void *)&srh->flags ||
4985                  ptr + len > (void *)&srh->segments)
4986                 return -EFAULT;
4987
4988         if (unlikely(bpf_try_make_writable(skb, offset + len)))
4989                 return -EFAULT;
4990         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
4991                 return -EINVAL;
4992         srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
4993
4994         memcpy(skb->data + offset, from, len);
4995         return 0;
4996 }
4997
4998 static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
4999         .func           = bpf_lwt_seg6_store_bytes,
5000         .gpl_only       = false,
5001         .ret_type       = RET_INTEGER,
5002         .arg1_type      = ARG_PTR_TO_CTX,
5003         .arg2_type      = ARG_ANYTHING,
5004         .arg3_type      = ARG_PTR_TO_MEM,
5005         .arg4_type      = ARG_CONST_SIZE
5006 };
5007
5008 static void bpf_update_srh_state(struct sk_buff *skb)
5009 {
5010         struct seg6_bpf_srh_state *srh_state =
5011                 this_cpu_ptr(&seg6_bpf_srh_states);
5012         int srhoff = 0;
5013
5014         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) {
5015                 srh_state->srh = NULL;
5016         } else {
5017                 srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5018                 srh_state->hdrlen = srh_state->srh->hdrlen << 3;
5019                 srh_state->valid = true;
5020         }
5021 }
5022
5023 BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
5024            u32, action, void *, param, u32, param_len)
5025 {
5026         struct seg6_bpf_srh_state *srh_state =
5027                 this_cpu_ptr(&seg6_bpf_srh_states);
5028         int hdroff = 0;
5029         int err;
5030
5031         switch (action) {
5032         case SEG6_LOCAL_ACTION_END_X:
5033                 if (!seg6_bpf_has_valid_srh(skb))
5034                         return -EBADMSG;
5035                 if (param_len != sizeof(struct in6_addr))
5036                         return -EINVAL;
5037                 return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
5038         case SEG6_LOCAL_ACTION_END_T:
5039                 if (!seg6_bpf_has_valid_srh(skb))
5040                         return -EBADMSG;
5041                 if (param_len != sizeof(int))
5042                         return -EINVAL;
5043                 return seg6_lookup_nexthop(skb, NULL, *(int *)param);
5044         case SEG6_LOCAL_ACTION_END_DT6:
5045                 if (!seg6_bpf_has_valid_srh(skb))
5046                         return -EBADMSG;
5047                 if (param_len != sizeof(int))
5048                         return -EINVAL;
5049
5050                 if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
5051                         return -EBADMSG;
5052                 if (!pskb_pull(skb, hdroff))
5053                         return -EBADMSG;
5054
5055                 skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
5056                 skb_reset_network_header(skb);
5057                 skb_reset_transport_header(skb);
5058                 skb->encapsulation = 0;
5059
5060                 bpf_compute_data_pointers(skb);
5061                 bpf_update_srh_state(skb);
5062                 return seg6_lookup_nexthop(skb, NULL, *(int *)param);
5063         case SEG6_LOCAL_ACTION_END_B6:
5064                 if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
5065                         return -EBADMSG;
5066                 err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
5067                                           param, param_len);
5068                 if (!err)
5069                         bpf_update_srh_state(skb);
5070
5071                 return err;
5072         case SEG6_LOCAL_ACTION_END_B6_ENCAP:
5073                 if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
5074                         return -EBADMSG;
5075                 err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
5076                                           param, param_len);
5077                 if (!err)
5078                         bpf_update_srh_state(skb);
5079
5080                 return err;
5081         default:
5082                 return -EINVAL;
5083         }
5084 }
5085
5086 static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
5087         .func           = bpf_lwt_seg6_action,
5088         .gpl_only       = false,
5089         .ret_type       = RET_INTEGER,
5090         .arg1_type      = ARG_PTR_TO_CTX,
5091         .arg2_type      = ARG_ANYTHING,
5092         .arg3_type      = ARG_PTR_TO_MEM,
5093         .arg4_type      = ARG_CONST_SIZE
5094 };
5095
5096 BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
5097            s32, len)
5098 {
5099         struct seg6_bpf_srh_state *srh_state =
5100                 this_cpu_ptr(&seg6_bpf_srh_states);
5101         struct ipv6_sr_hdr *srh = srh_state->srh;
5102         void *srh_end, *srh_tlvs, *ptr;
5103         struct ipv6hdr *hdr;
5104         int srhoff = 0;
5105         int ret;
5106
5107         if (unlikely(srh == NULL))
5108                 return -EINVAL;
5109
5110         srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
5111                         ((srh->first_segment + 1) << 4));
5112         srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
5113                         srh_state->hdrlen);
5114         ptr = skb->data + offset;
5115
5116         if (unlikely(ptr < srh_tlvs || ptr > srh_end))
5117                 return -EFAULT;
5118         if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
5119                 return -EFAULT;
5120
5121         if (len > 0) {
5122                 ret = skb_cow_head(skb, len);
5123                 if (unlikely(ret < 0))
5124                         return ret;
5125
5126                 ret = bpf_skb_net_hdr_push(skb, offset, len);
5127         } else {
5128                 ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
5129         }
5130
5131         bpf_compute_data_pointers(skb);
5132         if (unlikely(ret < 0))
5133                 return ret;
5134
5135         hdr = (struct ipv6hdr *)skb->data;
5136         hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
5137
5138         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
5139                 return -EINVAL;
5140         srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5141         srh_state->hdrlen += len;
5142         srh_state->valid = false;
5143         return 0;
5144 }
5145
5146 static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
5147         .func           = bpf_lwt_seg6_adjust_srh,
5148         .gpl_only       = false,
5149         .ret_type       = RET_INTEGER,
5150         .arg1_type      = ARG_PTR_TO_CTX,
5151         .arg2_type      = ARG_ANYTHING,
5152         .arg3_type      = ARG_ANYTHING,
5153 };
5154 #endif /* CONFIG_IPV6_SEG6_BPF */
5155
5156 #define CONVERT_COMMON_TCP_SOCK_FIELDS(md_type, CONVERT)                \
5157 do {                                                                    \
5158         switch (si->off) {                                              \
5159         case offsetof(md_type, snd_cwnd):                               \
5160                 CONVERT(snd_cwnd); break;                               \
5161         case offsetof(md_type, srtt_us):                                \
5162                 CONVERT(srtt_us); break;                                \
5163         case offsetof(md_type, snd_ssthresh):                           \
5164                 CONVERT(snd_ssthresh); break;                           \
5165         case offsetof(md_type, rcv_nxt):                                \
5166                 CONVERT(rcv_nxt); break;                                \
5167         case offsetof(md_type, snd_nxt):                                \
5168                 CONVERT(snd_nxt); break;                                \
5169         case offsetof(md_type, snd_una):                                \
5170                 CONVERT(snd_una); break;                                \
5171         case offsetof(md_type, mss_cache):                              \
5172                 CONVERT(mss_cache); break;                              \
5173         case offsetof(md_type, ecn_flags):                              \
5174                 CONVERT(ecn_flags); break;                              \
5175         case offsetof(md_type, rate_delivered):                         \
5176                 CONVERT(rate_delivered); break;                         \
5177         case offsetof(md_type, rate_interval_us):                       \
5178                 CONVERT(rate_interval_us); break;                       \
5179         case offsetof(md_type, packets_out):                            \
5180                 CONVERT(packets_out); break;                            \
5181         case offsetof(md_type, retrans_out):                            \
5182                 CONVERT(retrans_out); break;                            \
5183         case offsetof(md_type, total_retrans):                          \
5184                 CONVERT(total_retrans); break;                          \
5185         case offsetof(md_type, segs_in):                                \
5186                 CONVERT(segs_in); break;                                \
5187         case offsetof(md_type, data_segs_in):                           \
5188                 CONVERT(data_segs_in); break;                           \
5189         case offsetof(md_type, segs_out):                               \
5190                 CONVERT(segs_out); break;                               \
5191         case offsetof(md_type, data_segs_out):                          \
5192                 CONVERT(data_segs_out); break;                          \
5193         case offsetof(md_type, lost_out):                               \
5194                 CONVERT(lost_out); break;                               \
5195         case offsetof(md_type, sacked_out):                             \
5196                 CONVERT(sacked_out); break;                             \
5197         case offsetof(md_type, bytes_received):                         \
5198                 CONVERT(bytes_received); break;                         \
5199         case offsetof(md_type, bytes_acked):                            \
5200                 CONVERT(bytes_acked); break;                            \
5201         }                                                               \
5202 } while (0)
5203
5204 #ifdef CONFIG_INET
5205 static struct sock *sk_lookup(struct net *net, struct bpf_sock_tuple *tuple,
5206                               int dif, int sdif, u8 family, u8 proto)
5207 {
5208         bool refcounted = false;
5209         struct sock *sk = NULL;
5210
5211         if (family == AF_INET) {
5212                 __be32 src4 = tuple->ipv4.saddr;
5213                 __be32 dst4 = tuple->ipv4.daddr;
5214
5215                 if (proto == IPPROTO_TCP)
5216                         sk = __inet_lookup(net, &tcp_hashinfo, NULL, 0,
5217                                            src4, tuple->ipv4.sport,
5218                                            dst4, tuple->ipv4.dport,
5219                                            dif, sdif, &refcounted);
5220                 else
5221                         sk = __udp4_lib_lookup(net, src4, tuple->ipv4.sport,
5222                                                dst4, tuple->ipv4.dport,
5223                                                dif, sdif, &udp_table, NULL);
5224 #if IS_ENABLED(CONFIG_IPV6)
5225         } else {
5226                 struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr;
5227                 struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr;
5228
5229                 if (proto == IPPROTO_TCP)
5230                         sk = __inet6_lookup(net, &tcp_hashinfo, NULL, 0,
5231                                             src6, tuple->ipv6.sport,
5232                                             dst6, ntohs(tuple->ipv6.dport),
5233                                             dif, sdif, &refcounted);
5234                 else if (likely(ipv6_bpf_stub))
5235                         sk = ipv6_bpf_stub->udp6_lib_lookup(net,
5236                                                             src6, tuple->ipv6.sport,
5237                                                             dst6, tuple->ipv6.dport,
5238                                                             dif, sdif,
5239                                                             &udp_table, NULL);
5240 #endif
5241         }
5242
5243         if (unlikely(sk && !refcounted && !sock_flag(sk, SOCK_RCU_FREE))) {
5244                 WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
5245                 sk = NULL;
5246         }
5247         return sk;
5248 }
5249
5250 /* bpf_skc_lookup performs the core lookup for different types of sockets,
5251  * taking a reference on the socket if it doesn't have the flag SOCK_RCU_FREE.
5252  * Returns the socket as an 'unsigned long' to simplify the casting in the
5253  * callers to satisfy BPF_CALL declarations.
5254  */
5255 static struct sock *
5256 __bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5257                  struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
5258                  u64 flags)
5259 {
5260         struct sock *sk = NULL;
5261         u8 family = AF_UNSPEC;
5262         struct net *net;
5263         int sdif;
5264
5265         family = len == sizeof(tuple->ipv4) ? AF_INET : AF_INET6;
5266         if (unlikely(family == AF_UNSPEC || flags ||
5267                      !((s32)netns_id < 0 || netns_id <= S32_MAX)))
5268                 goto out;
5269
5270         if (family == AF_INET)
5271                 sdif = inet_sdif(skb);
5272         else
5273                 sdif = inet6_sdif(skb);
5274
5275         if ((s32)netns_id < 0) {
5276                 net = caller_net;
5277                 sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
5278         } else {
5279                 net = get_net_ns_by_id(caller_net, netns_id);
5280                 if (unlikely(!net))
5281                         goto out;
5282                 sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
5283                 put_net(net);
5284         }
5285
5286 out:
5287         return sk;
5288 }
5289
5290 static struct sock *
5291 __bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5292                 struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
5293                 u64 flags)
5294 {
5295         struct sock *sk = __bpf_skc_lookup(skb, tuple, len, caller_net,
5296                                            ifindex, proto, netns_id, flags);
5297
5298         if (sk)
5299                 sk = sk_to_full_sk(sk);
5300
5301         return sk;
5302 }
5303
5304 static struct sock *
5305 bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5306                u8 proto, u64 netns_id, u64 flags)
5307 {
5308         struct net *caller_net;
5309         int ifindex;
5310
5311         if (skb->dev) {
5312                 caller_net = dev_net(skb->dev);
5313                 ifindex = skb->dev->ifindex;
5314         } else {
5315                 caller_net = sock_net(skb->sk);
5316                 ifindex = 0;
5317         }
5318
5319         return __bpf_skc_lookup(skb, tuple, len, caller_net, ifindex, proto,
5320                                 netns_id, flags);
5321 }
5322
5323 static struct sock *
5324 bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5325               u8 proto, u64 netns_id, u64 flags)
5326 {
5327         struct sock *sk = bpf_skc_lookup(skb, tuple, len, proto, netns_id,
5328                                          flags);
5329
5330         if (sk)
5331                 sk = sk_to_full_sk(sk);
5332
5333         return sk;
5334 }
5335
5336 BPF_CALL_5(bpf_skc_lookup_tcp, struct sk_buff *, skb,
5337            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5338 {
5339         return (unsigned long)bpf_skc_lookup(skb, tuple, len, IPPROTO_TCP,
5340                                              netns_id, flags);
5341 }
5342
5343 static const struct bpf_func_proto bpf_skc_lookup_tcp_proto = {
5344         .func           = bpf_skc_lookup_tcp,
5345         .gpl_only       = false,
5346         .pkt_access     = true,
5347         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5348         .arg1_type      = ARG_PTR_TO_CTX,
5349         .arg2_type      = ARG_PTR_TO_MEM,
5350         .arg3_type      = ARG_CONST_SIZE,
5351         .arg4_type      = ARG_ANYTHING,
5352         .arg5_type      = ARG_ANYTHING,
5353 };
5354
5355 BPF_CALL_5(bpf_sk_lookup_tcp, struct sk_buff *, skb,
5356            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5357 {
5358         return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_TCP,
5359                                             netns_id, flags);
5360 }
5361
5362 static const struct bpf_func_proto bpf_sk_lookup_tcp_proto = {
5363         .func           = bpf_sk_lookup_tcp,
5364         .gpl_only       = false,
5365         .pkt_access     = true,
5366         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5367         .arg1_type      = ARG_PTR_TO_CTX,
5368         .arg2_type      = ARG_PTR_TO_MEM,
5369         .arg3_type      = ARG_CONST_SIZE,
5370         .arg4_type      = ARG_ANYTHING,
5371         .arg5_type      = ARG_ANYTHING,
5372 };
5373
5374 BPF_CALL_5(bpf_sk_lookup_udp, struct sk_buff *, skb,
5375            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5376 {
5377         return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_UDP,
5378                                             netns_id, flags);
5379 }
5380
5381 static const struct bpf_func_proto bpf_sk_lookup_udp_proto = {
5382         .func           = bpf_sk_lookup_udp,
5383         .gpl_only       = false,
5384         .pkt_access     = true,
5385         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5386         .arg1_type      = ARG_PTR_TO_CTX,
5387         .arg2_type      = ARG_PTR_TO_MEM,
5388         .arg3_type      = ARG_CONST_SIZE,
5389         .arg4_type      = ARG_ANYTHING,
5390         .arg5_type      = ARG_ANYTHING,
5391 };
5392
5393 BPF_CALL_1(bpf_sk_release, struct sock *, sk)
5394 {
5395         if (!sock_flag(sk, SOCK_RCU_FREE))
5396                 sock_gen_put(sk);
5397         return 0;
5398 }
5399
5400 static const struct bpf_func_proto bpf_sk_release_proto = {
5401         .func           = bpf_sk_release,
5402         .gpl_only       = false,
5403         .ret_type       = RET_INTEGER,
5404         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5405 };
5406
5407 BPF_CALL_5(bpf_xdp_sk_lookup_udp, struct xdp_buff *, ctx,
5408            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5409 {
5410         struct net *caller_net = dev_net(ctx->rxq->dev);
5411         int ifindex = ctx->rxq->dev->ifindex;
5412
5413         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
5414                                               ifindex, IPPROTO_UDP, netns_id,
5415                                               flags);
5416 }
5417
5418 static const struct bpf_func_proto bpf_xdp_sk_lookup_udp_proto = {
5419         .func           = bpf_xdp_sk_lookup_udp,
5420         .gpl_only       = false,
5421         .pkt_access     = true,
5422         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5423         .arg1_type      = ARG_PTR_TO_CTX,
5424         .arg2_type      = ARG_PTR_TO_MEM,
5425         .arg3_type      = ARG_CONST_SIZE,
5426         .arg4_type      = ARG_ANYTHING,
5427         .arg5_type      = ARG_ANYTHING,
5428 };
5429
5430 BPF_CALL_5(bpf_xdp_skc_lookup_tcp, struct xdp_buff *, ctx,
5431            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5432 {
5433         struct net *caller_net = dev_net(ctx->rxq->dev);
5434         int ifindex = ctx->rxq->dev->ifindex;
5435
5436         return (unsigned long)__bpf_skc_lookup(NULL, tuple, len, caller_net,
5437                                                ifindex, IPPROTO_TCP, netns_id,
5438                                                flags);
5439 }
5440
5441 static const struct bpf_func_proto bpf_xdp_skc_lookup_tcp_proto = {
5442         .func           = bpf_xdp_skc_lookup_tcp,
5443         .gpl_only       = false,
5444         .pkt_access     = true,
5445         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5446         .arg1_type      = ARG_PTR_TO_CTX,
5447         .arg2_type      = ARG_PTR_TO_MEM,
5448         .arg3_type      = ARG_CONST_SIZE,
5449         .arg4_type      = ARG_ANYTHING,
5450         .arg5_type      = ARG_ANYTHING,
5451 };
5452
5453 BPF_CALL_5(bpf_xdp_sk_lookup_tcp, struct xdp_buff *, ctx,
5454            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5455 {
5456         struct net *caller_net = dev_net(ctx->rxq->dev);
5457         int ifindex = ctx->rxq->dev->ifindex;
5458
5459         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
5460                                               ifindex, IPPROTO_TCP, netns_id,
5461                                               flags);
5462 }
5463
5464 static const struct bpf_func_proto bpf_xdp_sk_lookup_tcp_proto = {
5465         .func           = bpf_xdp_sk_lookup_tcp,
5466         .gpl_only       = false,
5467         .pkt_access     = true,
5468         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5469         .arg1_type      = ARG_PTR_TO_CTX,
5470         .arg2_type      = ARG_PTR_TO_MEM,
5471         .arg3_type      = ARG_CONST_SIZE,
5472         .arg4_type      = ARG_ANYTHING,
5473         .arg5_type      = ARG_ANYTHING,
5474 };
5475
5476 BPF_CALL_5(bpf_sock_addr_skc_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
5477            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5478 {
5479         return (unsigned long)__bpf_skc_lookup(NULL, tuple, len,
5480                                                sock_net(ctx->sk), 0,
5481                                                IPPROTO_TCP, netns_id, flags);
5482 }
5483
5484 static const struct bpf_func_proto bpf_sock_addr_skc_lookup_tcp_proto = {
5485         .func           = bpf_sock_addr_skc_lookup_tcp,
5486         .gpl_only       = false,
5487         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5488         .arg1_type      = ARG_PTR_TO_CTX,
5489         .arg2_type      = ARG_PTR_TO_MEM,
5490         .arg3_type      = ARG_CONST_SIZE,
5491         .arg4_type      = ARG_ANYTHING,
5492         .arg5_type      = ARG_ANYTHING,
5493 };
5494
5495 BPF_CALL_5(bpf_sock_addr_sk_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
5496            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5497 {
5498         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
5499                                               sock_net(ctx->sk), 0, IPPROTO_TCP,
5500                                               netns_id, flags);
5501 }
5502
5503 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_tcp_proto = {
5504         .func           = bpf_sock_addr_sk_lookup_tcp,
5505         .gpl_only       = false,
5506         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5507         .arg1_type      = ARG_PTR_TO_CTX,
5508         .arg2_type      = ARG_PTR_TO_MEM,
5509         .arg3_type      = ARG_CONST_SIZE,
5510         .arg4_type      = ARG_ANYTHING,
5511         .arg5_type      = ARG_ANYTHING,
5512 };
5513
5514 BPF_CALL_5(bpf_sock_addr_sk_lookup_udp, struct bpf_sock_addr_kern *, ctx,
5515            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5516 {
5517         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
5518                                               sock_net(ctx->sk), 0, IPPROTO_UDP,
5519                                               netns_id, flags);
5520 }
5521
5522 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_udp_proto = {
5523         .func           = bpf_sock_addr_sk_lookup_udp,
5524         .gpl_only       = false,
5525         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5526         .arg1_type      = ARG_PTR_TO_CTX,
5527         .arg2_type      = ARG_PTR_TO_MEM,
5528         .arg3_type      = ARG_CONST_SIZE,
5529         .arg4_type      = ARG_ANYTHING,
5530         .arg5_type      = ARG_ANYTHING,
5531 };
5532
5533 bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
5534                                   struct bpf_insn_access_aux *info)
5535 {
5536         if (off < 0 || off >= offsetofend(struct bpf_tcp_sock, bytes_acked))
5537                 return false;
5538
5539         if (off % size != 0)
5540                 return false;
5541
5542         switch (off) {
5543         case offsetof(struct bpf_tcp_sock, bytes_received):
5544         case offsetof(struct bpf_tcp_sock, bytes_acked):
5545                 return size == sizeof(__u64);
5546         default:
5547                 return size == sizeof(__u32);
5548         }
5549 }
5550
5551 u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
5552                                     const struct bpf_insn *si,
5553                                     struct bpf_insn *insn_buf,
5554                                     struct bpf_prog *prog, u32 *target_size)
5555 {
5556         struct bpf_insn *insn = insn_buf;
5557
5558 #define BPF_TCP_SOCK_GET_COMMON(FIELD)                                  \
5559         do {                                                            \
5560                 BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, FIELD) >     \
5561                              FIELD_SIZEOF(struct bpf_tcp_sock, FIELD)); \
5562                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_sock, FIELD),\
5563                                       si->dst_reg, si->src_reg,         \
5564                                       offsetof(struct tcp_sock, FIELD)); \
5565         } while (0)
5566
5567         CONVERT_COMMON_TCP_SOCK_FIELDS(struct bpf_tcp_sock,
5568                                        BPF_TCP_SOCK_GET_COMMON);
5569
5570         if (insn > insn_buf)
5571                 return insn - insn_buf;
5572
5573         switch (si->off) {
5574         case offsetof(struct bpf_tcp_sock, rtt_min):
5575                 BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) !=
5576                              sizeof(struct minmax));
5577                 BUILD_BUG_ON(sizeof(struct minmax) <
5578                              sizeof(struct minmax_sample));
5579
5580                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5581                                       offsetof(struct tcp_sock, rtt_min) +
5582                                       offsetof(struct minmax_sample, v));
5583                 break;
5584         }
5585
5586         return insn - insn_buf;
5587 }
5588
5589 BPF_CALL_1(bpf_tcp_sock, struct sock *, sk)
5590 {
5591         if (sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP)
5592                 return (unsigned long)sk;
5593
5594         return (unsigned long)NULL;
5595 }
5596
5597 static const struct bpf_func_proto bpf_tcp_sock_proto = {
5598         .func           = bpf_tcp_sock,
5599         .gpl_only       = false,
5600         .ret_type       = RET_PTR_TO_TCP_SOCK_OR_NULL,
5601         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5602 };
5603
5604 BPF_CALL_1(bpf_get_listener_sock, struct sock *, sk)
5605 {
5606         sk = sk_to_full_sk(sk);
5607
5608         if (sk->sk_state == TCP_LISTEN && sock_flag(sk, SOCK_RCU_FREE))
5609                 return (unsigned long)sk;
5610
5611         return (unsigned long)NULL;
5612 }
5613
5614 static const struct bpf_func_proto bpf_get_listener_sock_proto = {
5615         .func           = bpf_get_listener_sock,
5616         .gpl_only       = false,
5617         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5618         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5619 };
5620
5621 BPF_CALL_1(bpf_skb_ecn_set_ce, struct sk_buff *, skb)
5622 {
5623         unsigned int iphdr_len;
5624
5625         if (skb->protocol == cpu_to_be16(ETH_P_IP))
5626                 iphdr_len = sizeof(struct iphdr);
5627         else if (skb->protocol == cpu_to_be16(ETH_P_IPV6))
5628                 iphdr_len = sizeof(struct ipv6hdr);
5629         else
5630                 return 0;
5631
5632         if (skb_headlen(skb) < iphdr_len)
5633                 return 0;
5634
5635         if (skb_cloned(skb) && !skb_clone_writable(skb, iphdr_len))
5636                 return 0;
5637
5638         return INET_ECN_set_ce(skb);
5639 }
5640
5641 static const struct bpf_func_proto bpf_skb_ecn_set_ce_proto = {
5642         .func           = bpf_skb_ecn_set_ce,
5643         .gpl_only       = false,
5644         .ret_type       = RET_INTEGER,
5645         .arg1_type      = ARG_PTR_TO_CTX,
5646 };
5647
5648 BPF_CALL_5(bpf_tcp_check_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
5649            struct tcphdr *, th, u32, th_len)
5650 {
5651 #ifdef CONFIG_SYN_COOKIES
5652         u32 cookie;
5653         int ret;
5654
5655         if (unlikely(th_len < sizeof(*th)))
5656                 return -EINVAL;
5657
5658         /* sk_listener() allows TCP_NEW_SYN_RECV, which makes no sense here. */
5659         if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
5660                 return -EINVAL;
5661
5662         if (!sock_net(sk)->ipv4.sysctl_tcp_syncookies)
5663                 return -EINVAL;
5664
5665         if (!th->ack || th->rst || th->syn)
5666                 return -ENOENT;
5667
5668         if (tcp_synq_no_recent_overflow(sk))
5669                 return -ENOENT;
5670
5671         cookie = ntohl(th->ack_seq) - 1;
5672
5673         switch (sk->sk_family) {
5674         case AF_INET:
5675                 if (unlikely(iph_len < sizeof(struct iphdr)))
5676                         return -EINVAL;
5677
5678                 ret = __cookie_v4_check((struct iphdr *)iph, th, cookie);
5679                 break;
5680
5681 #if IS_BUILTIN(CONFIG_IPV6)
5682         case AF_INET6:
5683                 if (unlikely(iph_len < sizeof(struct ipv6hdr)))
5684                         return -EINVAL;
5685
5686                 ret = __cookie_v6_check((struct ipv6hdr *)iph, th, cookie);
5687                 break;
5688 #endif /* CONFIG_IPV6 */
5689
5690         default:
5691                 return -EPROTONOSUPPORT;
5692         }
5693
5694         if (ret > 0)
5695                 return 0;
5696
5697         return -ENOENT;
5698 #else
5699         return -ENOTSUPP;
5700 #endif
5701 }
5702
5703 static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = {
5704         .func           = bpf_tcp_check_syncookie,
5705         .gpl_only       = true,
5706         .pkt_access     = true,
5707         .ret_type       = RET_INTEGER,
5708         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5709         .arg2_type      = ARG_PTR_TO_MEM,
5710         .arg3_type      = ARG_CONST_SIZE,
5711         .arg4_type      = ARG_PTR_TO_MEM,
5712         .arg5_type      = ARG_CONST_SIZE,
5713 };
5714
5715 #endif /* CONFIG_INET */
5716
5717 bool bpf_helper_changes_pkt_data(void *func)
5718 {
5719         if (func == bpf_skb_vlan_push ||
5720             func == bpf_skb_vlan_pop ||
5721             func == bpf_skb_store_bytes ||
5722             func == bpf_skb_change_proto ||
5723             func == bpf_skb_change_head ||
5724             func == sk_skb_change_head ||
5725             func == bpf_skb_change_tail ||
5726             func == sk_skb_change_tail ||
5727             func == bpf_skb_adjust_room ||
5728             func == bpf_skb_pull_data ||
5729             func == sk_skb_pull_data ||
5730             func == bpf_clone_redirect ||
5731             func == bpf_l3_csum_replace ||
5732             func == bpf_l4_csum_replace ||
5733             func == bpf_xdp_adjust_head ||
5734             func == bpf_xdp_adjust_meta ||
5735             func == bpf_msg_pull_data ||
5736             func == bpf_msg_push_data ||
5737             func == bpf_msg_pop_data ||
5738             func == bpf_xdp_adjust_tail ||
5739 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
5740             func == bpf_lwt_seg6_store_bytes ||
5741             func == bpf_lwt_seg6_adjust_srh ||
5742             func == bpf_lwt_seg6_action ||
5743 #endif
5744             func == bpf_lwt_in_push_encap ||
5745             func == bpf_lwt_xmit_push_encap)
5746                 return true;
5747
5748         return false;
5749 }
5750
5751 static const struct bpf_func_proto *
5752 bpf_base_func_proto(enum bpf_func_id func_id)
5753 {
5754         switch (func_id) {
5755         case BPF_FUNC_map_lookup_elem:
5756                 return &bpf_map_lookup_elem_proto;
5757         case BPF_FUNC_map_update_elem:
5758                 return &bpf_map_update_elem_proto;
5759         case BPF_FUNC_map_delete_elem:
5760                 return &bpf_map_delete_elem_proto;
5761         case BPF_FUNC_map_push_elem:
5762                 return &bpf_map_push_elem_proto;
5763         case BPF_FUNC_map_pop_elem:
5764                 return &bpf_map_pop_elem_proto;
5765         case BPF_FUNC_map_peek_elem:
5766                 return &bpf_map_peek_elem_proto;
5767         case BPF_FUNC_get_prandom_u32:
5768                 return &bpf_get_prandom_u32_proto;
5769         case BPF_FUNC_get_smp_processor_id:
5770                 return &bpf_get_raw_smp_processor_id_proto;
5771         case BPF_FUNC_get_numa_node_id:
5772                 return &bpf_get_numa_node_id_proto;
5773         case BPF_FUNC_tail_call:
5774                 return &bpf_tail_call_proto;
5775         case BPF_FUNC_ktime_get_ns:
5776                 return &bpf_ktime_get_ns_proto;
5777         default:
5778                 break;
5779         }
5780
5781         if (!capable(CAP_SYS_ADMIN))
5782                 return NULL;
5783
5784         switch (func_id) {
5785         case BPF_FUNC_spin_lock:
5786                 return &bpf_spin_lock_proto;
5787         case BPF_FUNC_spin_unlock:
5788                 return &bpf_spin_unlock_proto;
5789         case BPF_FUNC_trace_printk:
5790                 return bpf_get_trace_printk_proto();
5791         default:
5792                 return NULL;
5793         }
5794 }
5795
5796 static const struct bpf_func_proto *
5797 sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5798 {
5799         switch (func_id) {
5800         /* inet and inet6 sockets are created in a process
5801          * context so there is always a valid uid/gid
5802          */
5803         case BPF_FUNC_get_current_uid_gid:
5804                 return &bpf_get_current_uid_gid_proto;
5805         case BPF_FUNC_get_local_storage:
5806                 return &bpf_get_local_storage_proto;
5807         default:
5808                 return bpf_base_func_proto(func_id);
5809         }
5810 }
5811
5812 static const struct bpf_func_proto *
5813 sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5814 {
5815         switch (func_id) {
5816         /* inet and inet6 sockets are created in a process
5817          * context so there is always a valid uid/gid
5818          */
5819         case BPF_FUNC_get_current_uid_gid:
5820                 return &bpf_get_current_uid_gid_proto;
5821         case BPF_FUNC_bind:
5822                 switch (prog->expected_attach_type) {
5823                 case BPF_CGROUP_INET4_CONNECT:
5824                 case BPF_CGROUP_INET6_CONNECT:
5825                         return &bpf_bind_proto;
5826                 default:
5827                         return NULL;
5828                 }
5829         case BPF_FUNC_get_socket_cookie:
5830                 return &bpf_get_socket_cookie_sock_addr_proto;
5831         case BPF_FUNC_get_local_storage:
5832                 return &bpf_get_local_storage_proto;
5833 #ifdef CONFIG_INET
5834         case BPF_FUNC_sk_lookup_tcp:
5835                 return &bpf_sock_addr_sk_lookup_tcp_proto;
5836         case BPF_FUNC_sk_lookup_udp:
5837                 return &bpf_sock_addr_sk_lookup_udp_proto;
5838         case BPF_FUNC_sk_release:
5839                 return &bpf_sk_release_proto;
5840         case BPF_FUNC_skc_lookup_tcp:
5841                 return &bpf_sock_addr_skc_lookup_tcp_proto;
5842 #endif /* CONFIG_INET */
5843         default:
5844                 return bpf_base_func_proto(func_id);
5845         }
5846 }
5847
5848 static const struct bpf_func_proto *
5849 sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5850 {
5851         switch (func_id) {
5852         case BPF_FUNC_skb_load_bytes:
5853                 return &bpf_skb_load_bytes_proto;
5854         case BPF_FUNC_skb_load_bytes_relative:
5855                 return &bpf_skb_load_bytes_relative_proto;
5856         case BPF_FUNC_get_socket_cookie:
5857                 return &bpf_get_socket_cookie_proto;
5858         case BPF_FUNC_get_socket_uid:
5859                 return &bpf_get_socket_uid_proto;
5860         default:
5861                 return bpf_base_func_proto(func_id);
5862         }
5863 }
5864
5865 static const struct bpf_func_proto *
5866 cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5867 {
5868         switch (func_id) {
5869         case BPF_FUNC_get_local_storage:
5870                 return &bpf_get_local_storage_proto;
5871         case BPF_FUNC_sk_fullsock:
5872                 return &bpf_sk_fullsock_proto;
5873 #ifdef CONFIG_INET
5874         case BPF_FUNC_tcp_sock:
5875                 return &bpf_tcp_sock_proto;
5876         case BPF_FUNC_get_listener_sock:
5877                 return &bpf_get_listener_sock_proto;
5878         case BPF_FUNC_skb_ecn_set_ce:
5879                 return &bpf_skb_ecn_set_ce_proto;
5880 #endif
5881         default:
5882                 return sk_filter_func_proto(func_id, prog);
5883         }
5884 }
5885
5886 static const struct bpf_func_proto *
5887 tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5888 {
5889         switch (func_id) {
5890         case BPF_FUNC_skb_store_bytes:
5891                 return &bpf_skb_store_bytes_proto;
5892         case BPF_FUNC_skb_load_bytes:
5893                 return &bpf_skb_load_bytes_proto;
5894         case BPF_FUNC_skb_load_bytes_relative:
5895                 return &bpf_skb_load_bytes_relative_proto;
5896         case BPF_FUNC_skb_pull_data:
5897                 return &bpf_skb_pull_data_proto;
5898         case BPF_FUNC_csum_diff:
5899                 return &bpf_csum_diff_proto;
5900         case BPF_FUNC_csum_update:
5901                 return &bpf_csum_update_proto;
5902         case BPF_FUNC_l3_csum_replace:
5903                 return &bpf_l3_csum_replace_proto;
5904         case BPF_FUNC_l4_csum_replace:
5905                 return &bpf_l4_csum_replace_proto;
5906         case BPF_FUNC_clone_redirect:
5907                 return &bpf_clone_redirect_proto;
5908         case BPF_FUNC_get_cgroup_classid:
5909                 return &bpf_get_cgroup_classid_proto;
5910         case BPF_FUNC_skb_vlan_push:
5911                 return &bpf_skb_vlan_push_proto;
5912         case BPF_FUNC_skb_vlan_pop:
5913                 return &bpf_skb_vlan_pop_proto;
5914         case BPF_FUNC_skb_change_proto:
5915                 return &bpf_skb_change_proto_proto;
5916         case BPF_FUNC_skb_change_type:
5917                 return &bpf_skb_change_type_proto;
5918         case BPF_FUNC_skb_adjust_room:
5919                 return &bpf_skb_adjust_room_proto;
5920         case BPF_FUNC_skb_change_tail:
5921                 return &bpf_skb_change_tail_proto;
5922         case BPF_FUNC_skb_get_tunnel_key:
5923                 return &bpf_skb_get_tunnel_key_proto;
5924         case BPF_FUNC_skb_set_tunnel_key:
5925                 return bpf_get_skb_set_tunnel_proto(func_id);
5926         case BPF_FUNC_skb_get_tunnel_opt:
5927                 return &bpf_skb_get_tunnel_opt_proto;
5928         case BPF_FUNC_skb_set_tunnel_opt:
5929                 return bpf_get_skb_set_tunnel_proto(func_id);
5930         case BPF_FUNC_redirect:
5931                 return &bpf_redirect_proto;
5932         case BPF_FUNC_get_route_realm:
5933                 return &bpf_get_route_realm_proto;
5934         case BPF_FUNC_get_hash_recalc:
5935                 return &bpf_get_hash_recalc_proto;
5936         case BPF_FUNC_set_hash_invalid:
5937                 return &bpf_set_hash_invalid_proto;
5938         case BPF_FUNC_set_hash:
5939                 return &bpf_set_hash_proto;
5940         case BPF_FUNC_perf_event_output:
5941                 return &bpf_skb_event_output_proto;
5942         case BPF_FUNC_get_smp_processor_id:
5943                 return &bpf_get_smp_processor_id_proto;
5944         case BPF_FUNC_skb_under_cgroup:
5945                 return &bpf_skb_under_cgroup_proto;
5946         case BPF_FUNC_get_socket_cookie:
5947                 return &bpf_get_socket_cookie_proto;
5948         case BPF_FUNC_get_socket_uid:
5949                 return &bpf_get_socket_uid_proto;
5950         case BPF_FUNC_fib_lookup:
5951                 return &bpf_skb_fib_lookup_proto;
5952         case BPF_FUNC_sk_fullsock:
5953                 return &bpf_sk_fullsock_proto;
5954 #ifdef CONFIG_XFRM
5955         case BPF_FUNC_skb_get_xfrm_state:
5956                 return &bpf_skb_get_xfrm_state_proto;
5957 #endif
5958 #ifdef CONFIG_SOCK_CGROUP_DATA
5959         case BPF_FUNC_skb_cgroup_id:
5960                 return &bpf_skb_cgroup_id_proto;
5961         case BPF_FUNC_skb_ancestor_cgroup_id:
5962                 return &bpf_skb_ancestor_cgroup_id_proto;
5963 #endif
5964 #ifdef CONFIG_INET
5965         case BPF_FUNC_sk_lookup_tcp:
5966                 return &bpf_sk_lookup_tcp_proto;
5967         case BPF_FUNC_sk_lookup_udp:
5968                 return &bpf_sk_lookup_udp_proto;
5969         case BPF_FUNC_sk_release:
5970                 return &bpf_sk_release_proto;
5971         case BPF_FUNC_tcp_sock:
5972                 return &bpf_tcp_sock_proto;
5973         case BPF_FUNC_get_listener_sock:
5974                 return &bpf_get_listener_sock_proto;
5975         case BPF_FUNC_skc_lookup_tcp:
5976                 return &bpf_skc_lookup_tcp_proto;
5977         case BPF_FUNC_tcp_check_syncookie:
5978                 return &bpf_tcp_check_syncookie_proto;
5979         case BPF_FUNC_skb_ecn_set_ce:
5980                 return &bpf_skb_ecn_set_ce_proto;
5981 #endif
5982         default:
5983                 return bpf_base_func_proto(func_id);
5984         }
5985 }
5986
5987 static const struct bpf_func_proto *
5988 xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5989 {
5990         switch (func_id) {
5991         case BPF_FUNC_perf_event_output:
5992                 return &bpf_xdp_event_output_proto;
5993         case BPF_FUNC_get_smp_processor_id:
5994                 return &bpf_get_smp_processor_id_proto;
5995         case BPF_FUNC_csum_diff:
5996                 return &bpf_csum_diff_proto;
5997         case BPF_FUNC_xdp_adjust_head:
5998                 return &bpf_xdp_adjust_head_proto;
5999         case BPF_FUNC_xdp_adjust_meta:
6000                 return &bpf_xdp_adjust_meta_proto;
6001         case BPF_FUNC_redirect:
6002                 return &bpf_xdp_redirect_proto;
6003         case BPF_FUNC_redirect_map:
6004                 return &bpf_xdp_redirect_map_proto;
6005         case BPF_FUNC_xdp_adjust_tail:
6006                 return &bpf_xdp_adjust_tail_proto;
6007         case BPF_FUNC_fib_lookup:
6008                 return &bpf_xdp_fib_lookup_proto;
6009 #ifdef CONFIG_INET
6010         case BPF_FUNC_sk_lookup_udp:
6011                 return &bpf_xdp_sk_lookup_udp_proto;
6012         case BPF_FUNC_sk_lookup_tcp:
6013                 return &bpf_xdp_sk_lookup_tcp_proto;
6014         case BPF_FUNC_sk_release:
6015                 return &bpf_sk_release_proto;
6016         case BPF_FUNC_skc_lookup_tcp:
6017                 return &bpf_xdp_skc_lookup_tcp_proto;
6018         case BPF_FUNC_tcp_check_syncookie:
6019                 return &bpf_tcp_check_syncookie_proto;
6020 #endif
6021         default:
6022                 return bpf_base_func_proto(func_id);
6023         }
6024 }
6025
6026 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
6027 const struct bpf_func_proto bpf_sock_hash_update_proto __weak;
6028
6029 static const struct bpf_func_proto *
6030 sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6031 {
6032         switch (func_id) {
6033         case BPF_FUNC_setsockopt:
6034                 return &bpf_setsockopt_proto;
6035         case BPF_FUNC_getsockopt:
6036                 return &bpf_getsockopt_proto;
6037         case BPF_FUNC_sock_ops_cb_flags_set:
6038                 return &bpf_sock_ops_cb_flags_set_proto;
6039         case BPF_FUNC_sock_map_update:
6040                 return &bpf_sock_map_update_proto;
6041         case BPF_FUNC_sock_hash_update:
6042                 return &bpf_sock_hash_update_proto;
6043         case BPF_FUNC_get_socket_cookie:
6044                 return &bpf_get_socket_cookie_sock_ops_proto;
6045         case BPF_FUNC_get_local_storage:
6046                 return &bpf_get_local_storage_proto;
6047         case BPF_FUNC_perf_event_output:
6048                 return &bpf_sockopt_event_output_proto;
6049         default:
6050                 return bpf_base_func_proto(func_id);
6051         }
6052 }
6053
6054 const struct bpf_func_proto bpf_msg_redirect_map_proto __weak;
6055 const struct bpf_func_proto bpf_msg_redirect_hash_proto __weak;
6056
6057 static const struct bpf_func_proto *
6058 sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6059 {
6060         switch (func_id) {
6061         case BPF_FUNC_msg_redirect_map:
6062                 return &bpf_msg_redirect_map_proto;
6063         case BPF_FUNC_msg_redirect_hash:
6064                 return &bpf_msg_redirect_hash_proto;
6065         case BPF_FUNC_msg_apply_bytes:
6066                 return &bpf_msg_apply_bytes_proto;
6067         case BPF_FUNC_msg_cork_bytes:
6068                 return &bpf_msg_cork_bytes_proto;
6069         case BPF_FUNC_msg_pull_data:
6070                 return &bpf_msg_pull_data_proto;
6071         case BPF_FUNC_msg_push_data:
6072                 return &bpf_msg_push_data_proto;
6073         case BPF_FUNC_msg_pop_data:
6074                 return &bpf_msg_pop_data_proto;
6075         default:
6076                 return bpf_base_func_proto(func_id);
6077         }
6078 }
6079
6080 const struct bpf_func_proto bpf_sk_redirect_map_proto __weak;
6081 const struct bpf_func_proto bpf_sk_redirect_hash_proto __weak;
6082
6083 static const struct bpf_func_proto *
6084 sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6085 {
6086         switch (func_id) {
6087         case BPF_FUNC_skb_store_bytes:
6088                 return &bpf_skb_store_bytes_proto;
6089         case BPF_FUNC_skb_load_bytes:
6090                 return &bpf_skb_load_bytes_proto;
6091         case BPF_FUNC_skb_pull_data:
6092                 return &sk_skb_pull_data_proto;
6093         case BPF_FUNC_skb_change_tail:
6094                 return &sk_skb_change_tail_proto;
6095         case BPF_FUNC_skb_change_head:
6096                 return &sk_skb_change_head_proto;
6097         case BPF_FUNC_get_socket_cookie:
6098                 return &bpf_get_socket_cookie_proto;
6099         case BPF_FUNC_get_socket_uid:
6100                 return &bpf_get_socket_uid_proto;
6101         case BPF_FUNC_sk_redirect_map:
6102                 return &bpf_sk_redirect_map_proto;
6103         case BPF_FUNC_sk_redirect_hash:
6104                 return &bpf_sk_redirect_hash_proto;
6105 #ifdef CONFIG_INET
6106         case BPF_FUNC_sk_lookup_tcp:
6107                 return &bpf_sk_lookup_tcp_proto;
6108         case BPF_FUNC_sk_lookup_udp:
6109                 return &bpf_sk_lookup_udp_proto;
6110         case BPF_FUNC_sk_release:
6111                 return &bpf_sk_release_proto;
6112         case BPF_FUNC_skc_lookup_tcp:
6113                 return &bpf_skc_lookup_tcp_proto;
6114 #endif
6115         default:
6116                 return bpf_base_func_proto(func_id);
6117         }
6118 }
6119
6120 static const struct bpf_func_proto *
6121 flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6122 {
6123         switch (func_id) {
6124         case BPF_FUNC_skb_load_bytes:
6125                 return &bpf_skb_load_bytes_proto;
6126         default:
6127                 return bpf_base_func_proto(func_id);
6128         }
6129 }
6130
6131 static const struct bpf_func_proto *
6132 lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6133 {
6134         switch (func_id) {
6135         case BPF_FUNC_skb_load_bytes:
6136                 return &bpf_skb_load_bytes_proto;
6137         case BPF_FUNC_skb_pull_data:
6138                 return &bpf_skb_pull_data_proto;
6139         case BPF_FUNC_csum_diff:
6140                 return &bpf_csum_diff_proto;
6141         case BPF_FUNC_get_cgroup_classid:
6142                 return &bpf_get_cgroup_classid_proto;
6143         case BPF_FUNC_get_route_realm:
6144                 return &bpf_get_route_realm_proto;
6145         case BPF_FUNC_get_hash_recalc:
6146                 return &bpf_get_hash_recalc_proto;
6147         case BPF_FUNC_perf_event_output:
6148                 return &bpf_skb_event_output_proto;
6149         case BPF_FUNC_get_smp_processor_id:
6150                 return &bpf_get_smp_processor_id_proto;
6151         case BPF_FUNC_skb_under_cgroup:
6152                 return &bpf_skb_under_cgroup_proto;
6153         default:
6154                 return bpf_base_func_proto(func_id);
6155         }
6156 }
6157
6158 static const struct bpf_func_proto *
6159 lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6160 {
6161         switch (func_id) {
6162         case BPF_FUNC_lwt_push_encap:
6163                 return &bpf_lwt_in_push_encap_proto;
6164         default:
6165                 return lwt_out_func_proto(func_id, prog);
6166         }
6167 }
6168
6169 static const struct bpf_func_proto *
6170 lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6171 {
6172         switch (func_id) {
6173         case BPF_FUNC_skb_get_tunnel_key:
6174                 return &bpf_skb_get_tunnel_key_proto;
6175         case BPF_FUNC_skb_set_tunnel_key:
6176                 return bpf_get_skb_set_tunnel_proto(func_id);
6177         case BPF_FUNC_skb_get_tunnel_opt:
6178                 return &bpf_skb_get_tunnel_opt_proto;
6179         case BPF_FUNC_skb_set_tunnel_opt:
6180                 return bpf_get_skb_set_tunnel_proto(func_id);
6181         case BPF_FUNC_redirect:
6182                 return &bpf_redirect_proto;
6183         case BPF_FUNC_clone_redirect:
6184                 return &bpf_clone_redirect_proto;
6185         case BPF_FUNC_skb_change_tail:
6186                 return &bpf_skb_change_tail_proto;
6187         case BPF_FUNC_skb_change_head:
6188                 return &bpf_skb_change_head_proto;
6189         case BPF_FUNC_skb_store_bytes:
6190                 return &bpf_skb_store_bytes_proto;
6191         case BPF_FUNC_csum_update:
6192                 return &bpf_csum_update_proto;
6193         case BPF_FUNC_l3_csum_replace:
6194                 return &bpf_l3_csum_replace_proto;
6195         case BPF_FUNC_l4_csum_replace:
6196                 return &bpf_l4_csum_replace_proto;
6197         case BPF_FUNC_set_hash_invalid:
6198                 return &bpf_set_hash_invalid_proto;
6199         case BPF_FUNC_lwt_push_encap:
6200                 return &bpf_lwt_xmit_push_encap_proto;
6201         default:
6202                 return lwt_out_func_proto(func_id, prog);
6203         }
6204 }
6205
6206 static const struct bpf_func_proto *
6207 lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6208 {
6209         switch (func_id) {
6210 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6211         case BPF_FUNC_lwt_seg6_store_bytes:
6212                 return &bpf_lwt_seg6_store_bytes_proto;
6213         case BPF_FUNC_lwt_seg6_action:
6214                 return &bpf_lwt_seg6_action_proto;
6215         case BPF_FUNC_lwt_seg6_adjust_srh:
6216                 return &bpf_lwt_seg6_adjust_srh_proto;
6217 #endif
6218         default:
6219                 return lwt_out_func_proto(func_id, prog);
6220         }
6221 }
6222
6223 static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
6224                                     const struct bpf_prog *prog,
6225                                     struct bpf_insn_access_aux *info)
6226 {
6227         const int size_default = sizeof(__u32);
6228
6229         if (off < 0 || off >= sizeof(struct __sk_buff))
6230                 return false;
6231
6232         /* The verifier guarantees that size > 0. */
6233         if (off % size != 0)
6234                 return false;
6235
6236         switch (off) {
6237         case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6238                 if (off + size > offsetofend(struct __sk_buff, cb[4]))
6239                         return false;
6240                 break;
6241         case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
6242         case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
6243         case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
6244         case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
6245         case bpf_ctx_range(struct __sk_buff, data):
6246         case bpf_ctx_range(struct __sk_buff, data_meta):
6247         case bpf_ctx_range(struct __sk_buff, data_end):
6248                 if (size != size_default)
6249                         return false;
6250                 break;
6251         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6252                 if (size != sizeof(__u64))
6253                         return false;
6254                 break;
6255         case bpf_ctx_range(struct __sk_buff, tstamp):
6256                 if (size != sizeof(__u64))
6257                         return false;
6258                 break;
6259         case offsetof(struct __sk_buff, sk):
6260                 if (type == BPF_WRITE || size != sizeof(__u64))
6261                         return false;
6262                 info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
6263                 break;
6264         default:
6265                 /* Only narrow read access allowed for now. */
6266                 if (type == BPF_WRITE) {
6267                         if (size != size_default)
6268                                 return false;
6269                 } else {
6270                         bpf_ctx_record_field_size(info, size_default);
6271                         if (!bpf_ctx_narrow_access_ok(off, size, size_default))
6272                                 return false;
6273                 }
6274         }
6275
6276         return true;
6277 }
6278
6279 static bool sk_filter_is_valid_access(int off, int size,
6280                                       enum bpf_access_type type,
6281                                       const struct bpf_prog *prog,
6282                                       struct bpf_insn_access_aux *info)
6283 {
6284         switch (off) {
6285         case bpf_ctx_range(struct __sk_buff, tc_classid):
6286         case bpf_ctx_range(struct __sk_buff, data):
6287         case bpf_ctx_range(struct __sk_buff, data_meta):
6288         case bpf_ctx_range(struct __sk_buff, data_end):
6289         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6290         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6291         case bpf_ctx_range(struct __sk_buff, tstamp):
6292         case bpf_ctx_range(struct __sk_buff, wire_len):
6293                 return false;
6294         }
6295
6296         if (type == BPF_WRITE) {
6297                 switch (off) {
6298                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6299                         break;
6300                 default:
6301                         return false;
6302                 }
6303         }
6304
6305         return bpf_skb_is_valid_access(off, size, type, prog, info);
6306 }
6307
6308 static bool cg_skb_is_valid_access(int off, int size,
6309                                    enum bpf_access_type type,
6310                                    const struct bpf_prog *prog,
6311                                    struct bpf_insn_access_aux *info)
6312 {
6313         switch (off) {
6314         case bpf_ctx_range(struct __sk_buff, tc_classid):
6315         case bpf_ctx_range(struct __sk_buff, data_meta):
6316         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6317         case bpf_ctx_range(struct __sk_buff, wire_len):
6318                 return false;
6319         case bpf_ctx_range(struct __sk_buff, data):
6320         case bpf_ctx_range(struct __sk_buff, data_end):
6321                 if (!capable(CAP_SYS_ADMIN))
6322                         return false;
6323                 break;
6324         }
6325
6326         if (type == BPF_WRITE) {
6327                 switch (off) {
6328                 case bpf_ctx_range(struct __sk_buff, mark):
6329                 case bpf_ctx_range(struct __sk_buff, priority):
6330                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6331                         break;
6332                 case bpf_ctx_range(struct __sk_buff, tstamp):
6333                         if (!capable(CAP_SYS_ADMIN))
6334                                 return false;
6335                         break;
6336                 default:
6337                         return false;
6338                 }
6339         }
6340
6341         switch (off) {
6342         case bpf_ctx_range(struct __sk_buff, data):
6343                 info->reg_type = PTR_TO_PACKET;
6344                 break;
6345         case bpf_ctx_range(struct __sk_buff, data_end):
6346                 info->reg_type = PTR_TO_PACKET_END;
6347                 break;
6348         }
6349
6350         return bpf_skb_is_valid_access(off, size, type, prog, info);
6351 }
6352
6353 static bool lwt_is_valid_access(int off, int size,
6354                                 enum bpf_access_type type,
6355                                 const struct bpf_prog *prog,
6356                                 struct bpf_insn_access_aux *info)
6357 {
6358         switch (off) {
6359         case bpf_ctx_range(struct __sk_buff, tc_classid):
6360         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6361         case bpf_ctx_range(struct __sk_buff, data_meta):
6362         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6363         case bpf_ctx_range(struct __sk_buff, tstamp):
6364         case bpf_ctx_range(struct __sk_buff, wire_len):
6365                 return false;
6366         }
6367
6368         if (type == BPF_WRITE) {
6369                 switch (off) {
6370                 case bpf_ctx_range(struct __sk_buff, mark):
6371                 case bpf_ctx_range(struct __sk_buff, priority):
6372                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6373                         break;
6374                 default:
6375                         return false;
6376                 }
6377         }
6378
6379         switch (off) {
6380         case bpf_ctx_range(struct __sk_buff, data):
6381                 info->reg_type = PTR_TO_PACKET;
6382                 break;
6383         case bpf_ctx_range(struct __sk_buff, data_end):
6384                 info->reg_type = PTR_TO_PACKET_END;
6385                 break;
6386         }
6387
6388         return bpf_skb_is_valid_access(off, size, type, prog, info);
6389 }
6390
6391 /* Attach type specific accesses */
6392 static bool __sock_filter_check_attach_type(int off,
6393                                             enum bpf_access_type access_type,
6394                                             enum bpf_attach_type attach_type)
6395 {
6396         switch (off) {
6397         case offsetof(struct bpf_sock, bound_dev_if):
6398         case offsetof(struct bpf_sock, mark):
6399         case offsetof(struct bpf_sock, priority):
6400                 switch (attach_type) {
6401                 case BPF_CGROUP_INET_SOCK_CREATE:
6402                         goto full_access;
6403                 default:
6404                         return false;
6405                 }
6406         case bpf_ctx_range(struct bpf_sock, src_ip4):
6407                 switch (attach_type) {
6408                 case BPF_CGROUP_INET4_POST_BIND:
6409                         goto read_only;
6410                 default:
6411                         return false;
6412                 }
6413         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6414                 switch (attach_type) {
6415                 case BPF_CGROUP_INET6_POST_BIND:
6416                         goto read_only;
6417                 default:
6418                         return false;
6419                 }
6420         case bpf_ctx_range(struct bpf_sock, src_port):
6421                 switch (attach_type) {
6422                 case BPF_CGROUP_INET4_POST_BIND:
6423                 case BPF_CGROUP_INET6_POST_BIND:
6424                         goto read_only;
6425                 default:
6426                         return false;
6427                 }
6428         }
6429 read_only:
6430         return access_type == BPF_READ;
6431 full_access:
6432         return true;
6433 }
6434
6435 bool bpf_sock_common_is_valid_access(int off, int size,
6436                                      enum bpf_access_type type,
6437                                      struct bpf_insn_access_aux *info)
6438 {
6439         switch (off) {
6440         case bpf_ctx_range_till(struct bpf_sock, type, priority):
6441                 return false;
6442         default:
6443                 return bpf_sock_is_valid_access(off, size, type, info);
6444         }
6445 }
6446
6447 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
6448                               struct bpf_insn_access_aux *info)
6449 {
6450         const int size_default = sizeof(__u32);
6451
6452         if (off < 0 || off >= sizeof(struct bpf_sock))
6453                 return false;
6454         if (off % size != 0)
6455                 return false;
6456
6457         switch (off) {
6458         case offsetof(struct bpf_sock, state):
6459         case offsetof(struct bpf_sock, family):
6460         case offsetof(struct bpf_sock, type):
6461         case offsetof(struct bpf_sock, protocol):
6462         case offsetof(struct bpf_sock, dst_port):
6463         case offsetof(struct bpf_sock, src_port):
6464         case bpf_ctx_range(struct bpf_sock, src_ip4):
6465         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6466         case bpf_ctx_range(struct bpf_sock, dst_ip4):
6467         case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
6468                 bpf_ctx_record_field_size(info, size_default);
6469                 return bpf_ctx_narrow_access_ok(off, size, size_default);
6470         }
6471
6472         return size == size_default;
6473 }
6474
6475 static bool sock_filter_is_valid_access(int off, int size,
6476                                         enum bpf_access_type type,
6477                                         const struct bpf_prog *prog,
6478                                         struct bpf_insn_access_aux *info)
6479 {
6480         if (!bpf_sock_is_valid_access(off, size, type, info))
6481                 return false;
6482         return __sock_filter_check_attach_type(off, type,
6483                                                prog->expected_attach_type);
6484 }
6485
6486 static int bpf_noop_prologue(struct bpf_insn *insn_buf, bool direct_write,
6487                              const struct bpf_prog *prog)
6488 {
6489         /* Neither direct read nor direct write requires any preliminary
6490          * action.
6491          */
6492         return 0;
6493 }
6494
6495 static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
6496                                 const struct bpf_prog *prog, int drop_verdict)
6497 {
6498         struct bpf_insn *insn = insn_buf;
6499
6500         if (!direct_write)
6501                 return 0;
6502
6503         /* if (!skb->cloned)
6504          *       goto start;
6505          *
6506          * (Fast-path, otherwise approximation that we might be
6507          *  a clone, do the rest in helper.)
6508          */
6509         *insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET());
6510         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
6511         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
6512
6513         /* ret = bpf_skb_pull_data(skb, 0); */
6514         *insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
6515         *insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
6516         *insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
6517                                BPF_FUNC_skb_pull_data);
6518         /* if (!ret)
6519          *      goto restore;
6520          * return TC_ACT_SHOT;
6521          */
6522         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
6523         *insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
6524         *insn++ = BPF_EXIT_INSN();
6525
6526         /* restore: */
6527         *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
6528         /* start: */
6529         *insn++ = prog->insnsi[0];
6530
6531         return insn - insn_buf;
6532 }
6533
6534 static int bpf_gen_ld_abs(const struct bpf_insn *orig,
6535                           struct bpf_insn *insn_buf)
6536 {
6537         bool indirect = BPF_MODE(orig->code) == BPF_IND;
6538         struct bpf_insn *insn = insn_buf;
6539
6540         /* We're guaranteed here that CTX is in R6. */
6541         *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
6542         if (!indirect) {
6543                 *insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
6544         } else {
6545                 *insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
6546                 if (orig->imm)
6547                         *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
6548         }
6549
6550         switch (BPF_SIZE(orig->code)) {
6551         case BPF_B:
6552                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
6553                 break;
6554         case BPF_H:
6555                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
6556                 break;
6557         case BPF_W:
6558                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
6559                 break;
6560         }
6561
6562         *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
6563         *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
6564         *insn++ = BPF_EXIT_INSN();
6565
6566         return insn - insn_buf;
6567 }
6568
6569 static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
6570                                const struct bpf_prog *prog)
6571 {
6572         return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
6573 }
6574
6575 static bool tc_cls_act_is_valid_access(int off, int size,
6576                                        enum bpf_access_type type,
6577                                        const struct bpf_prog *prog,
6578                                        struct bpf_insn_access_aux *info)
6579 {
6580         if (type == BPF_WRITE) {
6581                 switch (off) {
6582                 case bpf_ctx_range(struct __sk_buff, mark):
6583                 case bpf_ctx_range(struct __sk_buff, tc_index):
6584                 case bpf_ctx_range(struct __sk_buff, priority):
6585                 case bpf_ctx_range(struct __sk_buff, tc_classid):
6586                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6587                 case bpf_ctx_range(struct __sk_buff, tstamp):
6588                 case bpf_ctx_range(struct __sk_buff, queue_mapping):
6589                         break;
6590                 default:
6591                         return false;
6592                 }
6593         }
6594
6595         switch (off) {
6596         case bpf_ctx_range(struct __sk_buff, data):
6597                 info->reg_type = PTR_TO_PACKET;
6598                 break;
6599         case bpf_ctx_range(struct __sk_buff, data_meta):
6600                 info->reg_type = PTR_TO_PACKET_META;
6601                 break;
6602         case bpf_ctx_range(struct __sk_buff, data_end):
6603                 info->reg_type = PTR_TO_PACKET_END;
6604                 break;
6605         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6606         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6607                 return false;
6608         }
6609
6610         return bpf_skb_is_valid_access(off, size, type, prog, info);
6611 }
6612
6613 static bool __is_valid_xdp_access(int off, int size)
6614 {
6615         if (off < 0 || off >= sizeof(struct xdp_md))
6616                 return false;
6617         if (off % size != 0)
6618                 return false;
6619         if (size != sizeof(__u32))
6620                 return false;
6621
6622         return true;
6623 }
6624
6625 static bool xdp_is_valid_access(int off, int size,
6626                                 enum bpf_access_type type,
6627                                 const struct bpf_prog *prog,
6628                                 struct bpf_insn_access_aux *info)
6629 {
6630         if (type == BPF_WRITE) {
6631                 if (bpf_prog_is_dev_bound(prog->aux)) {
6632                         switch (off) {
6633                         case offsetof(struct xdp_md, rx_queue_index):
6634                                 return __is_valid_xdp_access(off, size);
6635                         }
6636                 }
6637                 return false;
6638         }
6639
6640         switch (off) {
6641         case offsetof(struct xdp_md, data):
6642                 info->reg_type = PTR_TO_PACKET;
6643                 break;
6644         case offsetof(struct xdp_md, data_meta):
6645                 info->reg_type = PTR_TO_PACKET_META;
6646                 break;
6647         case offsetof(struct xdp_md, data_end):
6648                 info->reg_type = PTR_TO_PACKET_END;
6649                 break;
6650         }
6651
6652         return __is_valid_xdp_access(off, size);
6653 }
6654
6655 void bpf_warn_invalid_xdp_action(u32 act)
6656 {
6657         const u32 act_max = XDP_REDIRECT;
6658
6659         WARN_ONCE(1, "%s XDP return value %u, expect packet loss!\n",
6660                   act > act_max ? "Illegal" : "Driver unsupported",
6661                   act);
6662 }
6663 EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
6664
6665 static bool sock_addr_is_valid_access(int off, int size,
6666                                       enum bpf_access_type type,
6667                                       const struct bpf_prog *prog,
6668                                       struct bpf_insn_access_aux *info)
6669 {
6670         const int size_default = sizeof(__u32);
6671
6672         if (off < 0 || off >= sizeof(struct bpf_sock_addr))
6673                 return false;
6674         if (off % size != 0)
6675                 return false;
6676
6677         /* Disallow access to IPv6 fields from IPv4 contex and vise
6678          * versa.
6679          */
6680         switch (off) {
6681         case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
6682                 switch (prog->expected_attach_type) {
6683                 case BPF_CGROUP_INET4_BIND:
6684                 case BPF_CGROUP_INET4_CONNECT:
6685                 case BPF_CGROUP_UDP4_SENDMSG:
6686                         break;
6687                 default:
6688                         return false;
6689                 }
6690                 break;
6691         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
6692                 switch (prog->expected_attach_type) {
6693                 case BPF_CGROUP_INET6_BIND:
6694                 case BPF_CGROUP_INET6_CONNECT:
6695                 case BPF_CGROUP_UDP6_SENDMSG:
6696                         break;
6697                 default:
6698                         return false;
6699                 }
6700                 break;
6701         case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
6702                 switch (prog->expected_attach_type) {
6703                 case BPF_CGROUP_UDP4_SENDMSG:
6704                         break;
6705                 default:
6706                         return false;
6707                 }
6708                 break;
6709         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
6710                                 msg_src_ip6[3]):
6711                 switch (prog->expected_attach_type) {
6712                 case BPF_CGROUP_UDP6_SENDMSG:
6713                         break;
6714                 default:
6715                         return false;
6716                 }
6717                 break;
6718         }
6719
6720         switch (off) {
6721         case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
6722         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
6723         case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
6724         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
6725                                 msg_src_ip6[3]):
6726                 /* Only narrow read access allowed for now. */
6727                 if (type == BPF_READ) {
6728                         bpf_ctx_record_field_size(info, size_default);
6729                         if (!bpf_ctx_narrow_access_ok(off, size, size_default))
6730                                 return false;
6731                 } else {
6732                         if (size != size_default)
6733                                 return false;
6734                 }
6735                 break;
6736         case bpf_ctx_range(struct bpf_sock_addr, user_port):
6737                 if (size != size_default)
6738                         return false;
6739                 break;
6740         default:
6741                 if (type == BPF_READ) {
6742                         if (size != size_default)
6743                                 return false;
6744                 } else {
6745                         return false;
6746                 }
6747         }
6748
6749         return true;
6750 }
6751
6752 static bool sock_ops_is_valid_access(int off, int size,
6753                                      enum bpf_access_type type,
6754                                      const struct bpf_prog *prog,
6755                                      struct bpf_insn_access_aux *info)
6756 {
6757         const int size_default = sizeof(__u32);
6758
6759         if (off < 0 || off >= sizeof(struct bpf_sock_ops))
6760                 return false;
6761
6762         /* The verifier guarantees that size > 0. */
6763         if (off % size != 0)
6764                 return false;
6765
6766         if (type == BPF_WRITE) {
6767                 switch (off) {
6768                 case offsetof(struct bpf_sock_ops, reply):
6769                 case offsetof(struct bpf_sock_ops, sk_txhash):
6770                         if (size != size_default)
6771                                 return false;
6772                         break;
6773                 default:
6774                         return false;
6775                 }
6776         } else {
6777                 switch (off) {
6778                 case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received,
6779                                         bytes_acked):
6780                         if (size != sizeof(__u64))
6781                                 return false;
6782                         break;
6783                 default:
6784                         if (size != size_default)
6785                                 return false;
6786                         break;
6787                 }
6788         }
6789
6790         return true;
6791 }
6792
6793 static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
6794                            const struct bpf_prog *prog)
6795 {
6796         return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
6797 }
6798
6799 static bool sk_skb_is_valid_access(int off, int size,
6800                                    enum bpf_access_type type,
6801                                    const struct bpf_prog *prog,
6802                                    struct bpf_insn_access_aux *info)
6803 {
6804         switch (off) {
6805         case bpf_ctx_range(struct __sk_buff, tc_classid):
6806         case bpf_ctx_range(struct __sk_buff, data_meta):
6807         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6808         case bpf_ctx_range(struct __sk_buff, tstamp):
6809         case bpf_ctx_range(struct __sk_buff, wire_len):
6810                 return false;
6811         }
6812
6813         if (type == BPF_WRITE) {
6814                 switch (off) {
6815                 case bpf_ctx_range(struct __sk_buff, tc_index):
6816                 case bpf_ctx_range(struct __sk_buff, priority):
6817                         break;
6818                 default:
6819                         return false;
6820                 }
6821         }
6822
6823         switch (off) {
6824         case bpf_ctx_range(struct __sk_buff, mark):
6825                 return false;
6826         case bpf_ctx_range(struct __sk_buff, data):
6827                 info->reg_type = PTR_TO_PACKET;
6828                 break;
6829         case bpf_ctx_range(struct __sk_buff, data_end):
6830                 info->reg_type = PTR_TO_PACKET_END;
6831                 break;
6832         }
6833
6834         return bpf_skb_is_valid_access(off, size, type, prog, info);
6835 }
6836
6837 static bool sk_msg_is_valid_access(int off, int size,
6838                                    enum bpf_access_type type,
6839                                    const struct bpf_prog *prog,
6840                                    struct bpf_insn_access_aux *info)
6841 {
6842         if (type == BPF_WRITE)
6843                 return false;
6844
6845         if (off % size != 0)
6846                 return false;
6847
6848         switch (off) {
6849         case offsetof(struct sk_msg_md, data):
6850                 info->reg_type = PTR_TO_PACKET;
6851                 if (size != sizeof(__u64))
6852                         return false;
6853                 break;
6854         case offsetof(struct sk_msg_md, data_end):
6855                 info->reg_type = PTR_TO_PACKET_END;
6856                 if (size != sizeof(__u64))
6857                         return false;
6858                 break;
6859         case bpf_ctx_range(struct sk_msg_md, family):
6860         case bpf_ctx_range(struct sk_msg_md, remote_ip4):
6861         case bpf_ctx_range(struct sk_msg_md, local_ip4):
6862         case bpf_ctx_range_till(struct sk_msg_md, remote_ip6[0], remote_ip6[3]):
6863         case bpf_ctx_range_till(struct sk_msg_md, local_ip6[0], local_ip6[3]):
6864         case bpf_ctx_range(struct sk_msg_md, remote_port):
6865         case bpf_ctx_range(struct sk_msg_md, local_port):
6866         case bpf_ctx_range(struct sk_msg_md, size):
6867                 if (size != sizeof(__u32))
6868                         return false;
6869                 break;
6870         default:
6871                 return false;
6872         }
6873         return true;
6874 }
6875
6876 static bool flow_dissector_is_valid_access(int off, int size,
6877                                            enum bpf_access_type type,
6878                                            const struct bpf_prog *prog,
6879                                            struct bpf_insn_access_aux *info)
6880 {
6881         if (type == BPF_WRITE)
6882                 return false;
6883
6884         switch (off) {
6885         case bpf_ctx_range(struct __sk_buff, data):
6886                 info->reg_type = PTR_TO_PACKET;
6887                 break;
6888         case bpf_ctx_range(struct __sk_buff, data_end):
6889                 info->reg_type = PTR_TO_PACKET_END;
6890                 break;
6891         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6892                 info->reg_type = PTR_TO_FLOW_KEYS;
6893                 break;
6894         default:
6895                 return false;
6896         }
6897
6898         return bpf_skb_is_valid_access(off, size, type, prog, info);
6899 }
6900
6901 static u32 bpf_convert_ctx_access(enum bpf_access_type type,
6902                                   const struct bpf_insn *si,
6903                                   struct bpf_insn *insn_buf,
6904                                   struct bpf_prog *prog, u32 *target_size)
6905 {
6906         struct bpf_insn *insn = insn_buf;
6907         int off;
6908
6909         switch (si->off) {
6910         case offsetof(struct __sk_buff, len):
6911                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6912                                       bpf_target_off(struct sk_buff, len, 4,
6913                                                      target_size));
6914                 break;
6915
6916         case offsetof(struct __sk_buff, protocol):
6917                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
6918                                       bpf_target_off(struct sk_buff, protocol, 2,
6919                                                      target_size));
6920                 break;
6921
6922         case offsetof(struct __sk_buff, vlan_proto):
6923                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
6924                                       bpf_target_off(struct sk_buff, vlan_proto, 2,
6925                                                      target_size));
6926                 break;
6927
6928         case offsetof(struct __sk_buff, priority):
6929                 if (type == BPF_WRITE)
6930                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6931                                               bpf_target_off(struct sk_buff, priority, 4,
6932                                                              target_size));
6933                 else
6934                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6935                                               bpf_target_off(struct sk_buff, priority, 4,
6936                                                              target_size));
6937                 break;
6938
6939         case offsetof(struct __sk_buff, ingress_ifindex):
6940                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6941                                       bpf_target_off(struct sk_buff, skb_iif, 4,
6942                                                      target_size));
6943                 break;
6944
6945         case offsetof(struct __sk_buff, ifindex):
6946                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
6947                                       si->dst_reg, si->src_reg,
6948                                       offsetof(struct sk_buff, dev));
6949                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
6950                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6951                                       bpf_target_off(struct net_device, ifindex, 4,
6952                                                      target_size));
6953                 break;
6954
6955         case offsetof(struct __sk_buff, hash):
6956                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6957                                       bpf_target_off(struct sk_buff, hash, 4,
6958                                                      target_size));
6959                 break;
6960
6961         case offsetof(struct __sk_buff, mark):
6962                 if (type == BPF_WRITE)
6963                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6964                                               bpf_target_off(struct sk_buff, mark, 4,
6965                                                              target_size));
6966                 else
6967                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6968                                               bpf_target_off(struct sk_buff, mark, 4,
6969                                                              target_size));
6970                 break;
6971
6972         case offsetof(struct __sk_buff, pkt_type):
6973                 *target_size = 1;
6974                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
6975                                       PKT_TYPE_OFFSET());
6976                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
6977 #ifdef __BIG_ENDIAN_BITFIELD
6978                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
6979 #endif
6980                 break;
6981
6982         case offsetof(struct __sk_buff, queue_mapping):
6983                 if (type == BPF_WRITE) {
6984                         *insn++ = BPF_JMP_IMM(BPF_JGE, si->src_reg, NO_QUEUE_MAPPING, 1);
6985                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
6986                                               bpf_target_off(struct sk_buff,
6987                                                              queue_mapping,
6988                                                              2, target_size));
6989                 } else {
6990                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
6991                                               bpf_target_off(struct sk_buff,
6992                                                              queue_mapping,
6993                                                              2, target_size));
6994                 }
6995                 break;
6996
6997         case offsetof(struct __sk_buff, vlan_present):
6998                 *target_size = 1;
6999                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
7000                                       PKT_VLAN_PRESENT_OFFSET());
7001                 if (PKT_VLAN_PRESENT_BIT)
7002                         *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, PKT_VLAN_PRESENT_BIT);
7003                 if (PKT_VLAN_PRESENT_BIT < 7)
7004                         *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1);
7005                 break;
7006
7007         case offsetof(struct __sk_buff, vlan_tci):
7008                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7009                                       bpf_target_off(struct sk_buff, vlan_tci, 2,
7010                                                      target_size));
7011                 break;
7012
7013         case offsetof(struct __sk_buff, cb[0]) ...
7014              offsetofend(struct __sk_buff, cb[4]) - 1:
7015                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);
7016                 BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
7017                               offsetof(struct qdisc_skb_cb, data)) %
7018                              sizeof(__u64));
7019
7020                 prog->cb_access = 1;
7021                 off  = si->off;
7022                 off -= offsetof(struct __sk_buff, cb[0]);
7023                 off += offsetof(struct sk_buff, cb);
7024                 off += offsetof(struct qdisc_skb_cb, data);
7025                 if (type == BPF_WRITE)
7026                         *insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
7027                                               si->src_reg, off);
7028                 else
7029                         *insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
7030                                               si->src_reg, off);
7031                 break;
7032
7033         case offsetof(struct __sk_buff, tc_classid):
7034                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, tc_classid) != 2);
7035
7036                 off  = si->off;
7037                 off -= offsetof(struct __sk_buff, tc_classid);
7038                 off += offsetof(struct sk_buff, cb);
7039                 off += offsetof(struct qdisc_skb_cb, tc_classid);
7040                 *target_size = 2;
7041                 if (type == BPF_WRITE)
7042                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg,
7043                                               si->src_reg, off);
7044                 else
7045                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
7046                                               si->src_reg, off);
7047                 break;
7048
7049         case offsetof(struct __sk_buff, data):
7050                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
7051                                       si->dst_reg, si->src_reg,
7052                                       offsetof(struct sk_buff, data));
7053                 break;
7054
7055         case offsetof(struct __sk_buff, data_meta):
7056                 off  = si->off;
7057                 off -= offsetof(struct __sk_buff, data_meta);
7058                 off += offsetof(struct sk_buff, cb);
7059                 off += offsetof(struct bpf_skb_data_end, data_meta);
7060                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7061                                       si->src_reg, off);
7062                 break;
7063
7064         case offsetof(struct __sk_buff, data_end):
7065                 off  = si->off;
7066                 off -= offsetof(struct __sk_buff, data_end);
7067                 off += offsetof(struct sk_buff, cb);
7068                 off += offsetof(struct bpf_skb_data_end, data_end);
7069                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7070                                       si->src_reg, off);
7071                 break;
7072
7073         case offsetof(struct __sk_buff, tc_index):
7074 #ifdef CONFIG_NET_SCHED
7075                 if (type == BPF_WRITE)
7076                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
7077                                               bpf_target_off(struct sk_buff, tc_index, 2,
7078                                                              target_size));
7079                 else
7080                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7081                                               bpf_target_off(struct sk_buff, tc_index, 2,
7082                                                              target_size));
7083 #else
7084                 *target_size = 2;
7085                 if (type == BPF_WRITE)
7086                         *insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
7087                 else
7088                         *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7089 #endif
7090                 break;
7091
7092         case offsetof(struct __sk_buff, napi_id):
7093 #if defined(CONFIG_NET_RX_BUSY_POLL)
7094                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7095                                       bpf_target_off(struct sk_buff, napi_id, 4,
7096                                                      target_size));
7097                 *insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
7098                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7099 #else
7100                 *target_size = 4;
7101                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7102 #endif
7103                 break;
7104         case offsetof(struct __sk_buff, family):
7105                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
7106
7107                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7108                                       si->dst_reg, si->src_reg,
7109                                       offsetof(struct sk_buff, sk));
7110                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7111                                       bpf_target_off(struct sock_common,
7112                                                      skc_family,
7113                                                      2, target_size));
7114                 break;
7115         case offsetof(struct __sk_buff, remote_ip4):
7116                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
7117
7118                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7119                                       si->dst_reg, si->src_reg,
7120                                       offsetof(struct sk_buff, sk));
7121                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7122                                       bpf_target_off(struct sock_common,
7123                                                      skc_daddr,
7124                                                      4, target_size));
7125                 break;
7126         case offsetof(struct __sk_buff, local_ip4):
7127                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7128                                           skc_rcv_saddr) != 4);
7129
7130                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7131                                       si->dst_reg, si->src_reg,
7132                                       offsetof(struct sk_buff, sk));
7133                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7134                                       bpf_target_off(struct sock_common,
7135                                                      skc_rcv_saddr,
7136                                                      4, target_size));
7137                 break;
7138         case offsetof(struct __sk_buff, remote_ip6[0]) ...
7139              offsetof(struct __sk_buff, remote_ip6[3]):
7140 #if IS_ENABLED(CONFIG_IPV6)
7141                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7142                                           skc_v6_daddr.s6_addr32[0]) != 4);
7143
7144                 off = si->off;
7145                 off -= offsetof(struct __sk_buff, remote_ip6[0]);
7146
7147                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7148                                       si->dst_reg, si->src_reg,
7149                                       offsetof(struct sk_buff, sk));
7150                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7151                                       offsetof(struct sock_common,
7152                                                skc_v6_daddr.s6_addr32[0]) +
7153                                       off);
7154 #else
7155                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7156 #endif
7157                 break;
7158         case offsetof(struct __sk_buff, local_ip6[0]) ...
7159              offsetof(struct __sk_buff, local_ip6[3]):
7160 #if IS_ENABLED(CONFIG_IPV6)
7161                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7162                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
7163
7164                 off = si->off;
7165                 off -= offsetof(struct __sk_buff, local_ip6[0]);
7166
7167                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7168                                       si->dst_reg, si->src_reg,
7169                                       offsetof(struct sk_buff, sk));
7170                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7171                                       offsetof(struct sock_common,
7172                                                skc_v6_rcv_saddr.s6_addr32[0]) +
7173                                       off);
7174 #else
7175                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7176 #endif
7177                 break;
7178
7179         case offsetof(struct __sk_buff, remote_port):
7180                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
7181
7182                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7183                                       si->dst_reg, si->src_reg,
7184                                       offsetof(struct sk_buff, sk));
7185                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7186                                       bpf_target_off(struct sock_common,
7187                                                      skc_dport,
7188                                                      2, target_size));
7189 #ifndef __BIG_ENDIAN_BITFIELD
7190                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
7191 #endif
7192                 break;
7193
7194         case offsetof(struct __sk_buff, local_port):
7195                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
7196
7197                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7198                                       si->dst_reg, si->src_reg,
7199                                       offsetof(struct sk_buff, sk));
7200                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7201                                       bpf_target_off(struct sock_common,
7202                                                      skc_num, 2, target_size));
7203                 break;
7204
7205         case offsetof(struct __sk_buff, flow_keys):
7206                 off  = si->off;
7207                 off -= offsetof(struct __sk_buff, flow_keys);
7208                 off += offsetof(struct sk_buff, cb);
7209                 off += offsetof(struct qdisc_skb_cb, flow_keys);
7210                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7211                                       si->src_reg, off);
7212                 break;
7213
7214         case offsetof(struct __sk_buff, tstamp):
7215                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, tstamp) != 8);
7216
7217                 if (type == BPF_WRITE)
7218                         *insn++ = BPF_STX_MEM(BPF_DW,
7219                                               si->dst_reg, si->src_reg,
7220                                               bpf_target_off(struct sk_buff,
7221                                                              tstamp, 8,
7222                                                              target_size));
7223                 else
7224                         *insn++ = BPF_LDX_MEM(BPF_DW,
7225                                               si->dst_reg, si->src_reg,
7226                                               bpf_target_off(struct sk_buff,
7227                                                              tstamp, 8,
7228                                                              target_size));
7229                 break;
7230
7231         case offsetof(struct __sk_buff, gso_segs):
7232                 /* si->dst_reg = skb_shinfo(SKB); */
7233 #ifdef NET_SKBUFF_DATA_USES_OFFSET
7234                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, head),
7235                                       si->dst_reg, si->src_reg,
7236                                       offsetof(struct sk_buff, head));
7237                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
7238                                       BPF_REG_AX, si->src_reg,
7239                                       offsetof(struct sk_buff, end));
7240                 *insn++ = BPF_ALU64_REG(BPF_ADD, si->dst_reg, BPF_REG_AX);
7241 #else
7242                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
7243                                       si->dst_reg, si->src_reg,
7244                                       offsetof(struct sk_buff, end));
7245 #endif
7246                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_segs),
7247                                       si->dst_reg, si->dst_reg,
7248                                       bpf_target_off(struct skb_shared_info,
7249                                                      gso_segs, 2,
7250                                                      target_size));
7251                 break;
7252         case offsetof(struct __sk_buff, wire_len):
7253                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, pkt_len) != 4);
7254
7255                 off = si->off;
7256                 off -= offsetof(struct __sk_buff, wire_len);
7257                 off += offsetof(struct sk_buff, cb);
7258                 off += offsetof(struct qdisc_skb_cb, pkt_len);
7259                 *target_size = 4;
7260                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, off);
7261                 break;
7262
7263         case offsetof(struct __sk_buff, sk):
7264                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7265                                       si->dst_reg, si->src_reg,
7266                                       offsetof(struct sk_buff, sk));
7267                 break;
7268         }
7269
7270         return insn - insn_buf;
7271 }
7272
7273 u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
7274                                 const struct bpf_insn *si,
7275                                 struct bpf_insn *insn_buf,
7276                                 struct bpf_prog *prog, u32 *target_size)
7277 {
7278         struct bpf_insn *insn = insn_buf;
7279         int off;
7280
7281         switch (si->off) {
7282         case offsetof(struct bpf_sock, bound_dev_if):
7283                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_bound_dev_if) != 4);
7284
7285                 if (type == BPF_WRITE)
7286                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7287                                         offsetof(struct sock, sk_bound_dev_if));
7288                 else
7289                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7290                                       offsetof(struct sock, sk_bound_dev_if));
7291                 break;
7292
7293         case offsetof(struct bpf_sock, mark):
7294                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_mark) != 4);
7295
7296                 if (type == BPF_WRITE)
7297                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7298                                         offsetof(struct sock, sk_mark));
7299                 else
7300                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7301                                       offsetof(struct sock, sk_mark));
7302                 break;
7303
7304         case offsetof(struct bpf_sock, priority):
7305                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_priority) != 4);
7306
7307                 if (type == BPF_WRITE)
7308                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7309                                         offsetof(struct sock, sk_priority));
7310                 else
7311                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7312                                       offsetof(struct sock, sk_priority));
7313                 break;
7314
7315         case offsetof(struct bpf_sock, family):
7316                 *insn++ = BPF_LDX_MEM(
7317                         BPF_FIELD_SIZEOF(struct sock_common, skc_family),
7318                         si->dst_reg, si->src_reg,
7319                         bpf_target_off(struct sock_common,
7320                                        skc_family,
7321                                        FIELD_SIZEOF(struct sock_common,
7322                                                     skc_family),
7323                                        target_size));
7324                 break;
7325
7326         case offsetof(struct bpf_sock, type):
7327                 BUILD_BUG_ON(HWEIGHT32(SK_FL_TYPE_MASK) != BITS_PER_BYTE * 2);
7328                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7329                                       offsetof(struct sock, __sk_flags_offset));
7330                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
7331                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
7332                 *target_size = 2;
7333                 break;
7334
7335         case offsetof(struct bpf_sock, protocol):
7336                 BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE);
7337                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7338                                       offsetof(struct sock, __sk_flags_offset));
7339                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
7340                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT);
7341                 *target_size = 1;
7342                 break;
7343
7344         case offsetof(struct bpf_sock, src_ip4):
7345                 *insn++ = BPF_LDX_MEM(
7346                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7347                         bpf_target_off(struct sock_common, skc_rcv_saddr,
7348                                        FIELD_SIZEOF(struct sock_common,
7349                                                     skc_rcv_saddr),
7350                                        target_size));
7351                 break;
7352
7353         case offsetof(struct bpf_sock, dst_ip4):
7354                 *insn++ = BPF_LDX_MEM(
7355                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7356                         bpf_target_off(struct sock_common, skc_daddr,
7357                                        FIELD_SIZEOF(struct sock_common,
7358                                                     skc_daddr),
7359                                        target_size));
7360                 break;
7361
7362         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
7363 #if IS_ENABLED(CONFIG_IPV6)
7364                 off = si->off;
7365                 off -= offsetof(struct bpf_sock, src_ip6[0]);
7366                 *insn++ = BPF_LDX_MEM(
7367                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7368                         bpf_target_off(
7369                                 struct sock_common,
7370                                 skc_v6_rcv_saddr.s6_addr32[0],
7371                                 FIELD_SIZEOF(struct sock_common,
7372                                              skc_v6_rcv_saddr.s6_addr32[0]),
7373                                 target_size) + off);
7374 #else
7375                 (void)off;
7376                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7377 #endif
7378                 break;
7379
7380         case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
7381 #if IS_ENABLED(CONFIG_IPV6)
7382                 off = si->off;
7383                 off -= offsetof(struct bpf_sock, dst_ip6[0]);
7384                 *insn++ = BPF_LDX_MEM(
7385                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7386                         bpf_target_off(struct sock_common,
7387                                        skc_v6_daddr.s6_addr32[0],
7388                                        FIELD_SIZEOF(struct sock_common,
7389                                                     skc_v6_daddr.s6_addr32[0]),
7390                                        target_size) + off);
7391 #else
7392                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7393                 *target_size = 4;
7394 #endif
7395                 break;
7396
7397         case offsetof(struct bpf_sock, src_port):
7398                 *insn++ = BPF_LDX_MEM(
7399                         BPF_FIELD_SIZEOF(struct sock_common, skc_num),
7400                         si->dst_reg, si->src_reg,
7401                         bpf_target_off(struct sock_common, skc_num,
7402                                        FIELD_SIZEOF(struct sock_common,
7403                                                     skc_num),
7404                                        target_size));
7405                 break;
7406
7407         case offsetof(struct bpf_sock, dst_port):
7408                 *insn++ = BPF_LDX_MEM(
7409                         BPF_FIELD_SIZEOF(struct sock_common, skc_dport),
7410                         si->dst_reg, si->src_reg,
7411                         bpf_target_off(struct sock_common, skc_dport,
7412                                        FIELD_SIZEOF(struct sock_common,
7413                                                     skc_dport),
7414                                        target_size));
7415                 break;
7416
7417         case offsetof(struct bpf_sock, state):
7418                 *insn++ = BPF_LDX_MEM(
7419                         BPF_FIELD_SIZEOF(struct sock_common, skc_state),
7420                         si->dst_reg, si->src_reg,
7421                         bpf_target_off(struct sock_common, skc_state,
7422                                        FIELD_SIZEOF(struct sock_common,
7423                                                     skc_state),
7424                                        target_size));
7425                 break;
7426         }
7427
7428         return insn - insn_buf;
7429 }
7430
7431 static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
7432                                          const struct bpf_insn *si,
7433                                          struct bpf_insn *insn_buf,
7434                                          struct bpf_prog *prog, u32 *target_size)
7435 {
7436         struct bpf_insn *insn = insn_buf;
7437
7438         switch (si->off) {
7439         case offsetof(struct __sk_buff, ifindex):
7440                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
7441                                       si->dst_reg, si->src_reg,
7442                                       offsetof(struct sk_buff, dev));
7443                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7444                                       bpf_target_off(struct net_device, ifindex, 4,
7445                                                      target_size));
7446                 break;
7447         default:
7448                 return bpf_convert_ctx_access(type, si, insn_buf, prog,
7449                                               target_size);
7450         }
7451
7452         return insn - insn_buf;
7453 }
7454
7455 static u32 xdp_convert_ctx_access(enum bpf_access_type type,
7456                                   const struct bpf_insn *si,
7457                                   struct bpf_insn *insn_buf,
7458                                   struct bpf_prog *prog, u32 *target_size)
7459 {
7460         struct bpf_insn *insn = insn_buf;
7461
7462         switch (si->off) {
7463         case offsetof(struct xdp_md, data):
7464                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
7465                                       si->dst_reg, si->src_reg,
7466                                       offsetof(struct xdp_buff, data));
7467                 break;
7468         case offsetof(struct xdp_md, data_meta):
7469                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta),
7470                                       si->dst_reg, si->src_reg,
7471                                       offsetof(struct xdp_buff, data_meta));
7472                 break;
7473         case offsetof(struct xdp_md, data_end):
7474                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
7475                                       si->dst_reg, si->src_reg,
7476                                       offsetof(struct xdp_buff, data_end));
7477                 break;
7478         case offsetof(struct xdp_md, ingress_ifindex):
7479                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
7480                                       si->dst_reg, si->src_reg,
7481                                       offsetof(struct xdp_buff, rxq));
7482                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev),
7483                                       si->dst_reg, si->dst_reg,
7484                                       offsetof(struct xdp_rxq_info, dev));
7485                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7486                                       offsetof(struct net_device, ifindex));
7487                 break;
7488         case offsetof(struct xdp_md, rx_queue_index):
7489                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
7490                                       si->dst_reg, si->src_reg,
7491                                       offsetof(struct xdp_buff, rxq));
7492                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7493                                       offsetof(struct xdp_rxq_info,
7494                                                queue_index));
7495                 break;
7496         }
7497
7498         return insn - insn_buf;
7499 }
7500
7501 /* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of
7502  * context Structure, F is Field in context structure that contains a pointer
7503  * to Nested Structure of type NS that has the field NF.
7504  *
7505  * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make
7506  * sure that SIZE is not greater than actual size of S.F.NF.
7507  *
7508  * If offset OFF is provided, the load happens from that offset relative to
7509  * offset of NF.
7510  */
7511 #define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF)          \
7512         do {                                                                   \
7513                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg,     \
7514                                       si->src_reg, offsetof(S, F));            \
7515                 *insn++ = BPF_LDX_MEM(                                         \
7516                         SIZE, si->dst_reg, si->dst_reg,                        \
7517                         bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),           \
7518                                        target_size)                            \
7519                                 + OFF);                                        \
7520         } while (0)
7521
7522 #define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF)                              \
7523         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF,                     \
7524                                              BPF_FIELD_SIZEOF(NS, NF), 0)
7525
7526 /* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to
7527  * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation.
7528  *
7529  * It doesn't support SIZE argument though since narrow stores are not
7530  * supported for now.
7531  *
7532  * In addition it uses Temporary Field TF (member of struct S) as the 3rd
7533  * "register" since two registers available in convert_ctx_access are not
7534  * enough: we can't override neither SRC, since it contains value to store, nor
7535  * DST since it contains pointer to context that may be used by later
7536  * instructions. But we need a temporary place to save pointer to nested
7537  * structure whose field we want to store to.
7538  */
7539 #define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF, TF)                \
7540         do {                                                                   \
7541                 int tmp_reg = BPF_REG_9;                                       \
7542                 if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
7543                         --tmp_reg;                                             \
7544                 if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
7545                         --tmp_reg;                                             \
7546                 *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg,            \
7547                                       offsetof(S, TF));                        \
7548                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg,         \
7549                                       si->dst_reg, offsetof(S, F));            \
7550                 *insn++ = BPF_STX_MEM(                                         \
7551                         BPF_FIELD_SIZEOF(NS, NF), tmp_reg, si->src_reg,        \
7552                         bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),           \
7553                                        target_size)                            \
7554                                 + OFF);                                        \
7555                 *insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg,            \
7556                                       offsetof(S, TF));                        \
7557         } while (0)
7558
7559 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \
7560                                                       TF)                      \
7561         do {                                                                   \
7562                 if (type == BPF_WRITE) {                                       \
7563                         SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF,    \
7564                                                          TF);                  \
7565                 } else {                                                       \
7566                         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(                  \
7567                                 S, NS, F, NF, SIZE, OFF);  \
7568                 }                                                              \
7569         } while (0)
7570
7571 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(S, NS, F, NF, TF)                 \
7572         SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(                         \
7573                 S, NS, F, NF, BPF_FIELD_SIZEOF(NS, NF), 0, TF)
7574
7575 static u32 sock_addr_convert_ctx_access(enum bpf_access_type type,
7576                                         const struct bpf_insn *si,
7577                                         struct bpf_insn *insn_buf,
7578                                         struct bpf_prog *prog, u32 *target_size)
7579 {
7580         struct bpf_insn *insn = insn_buf;
7581         int off;
7582
7583         switch (si->off) {
7584         case offsetof(struct bpf_sock_addr, user_family):
7585                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
7586                                             struct sockaddr, uaddr, sa_family);
7587                 break;
7588
7589         case offsetof(struct bpf_sock_addr, user_ip4):
7590                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7591                         struct bpf_sock_addr_kern, struct sockaddr_in, uaddr,
7592                         sin_addr, BPF_SIZE(si->code), 0, tmp_reg);
7593                 break;
7594
7595         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
7596                 off = si->off;
7597                 off -= offsetof(struct bpf_sock_addr, user_ip6[0]);
7598                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7599                         struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
7600                         sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off,
7601                         tmp_reg);
7602                 break;
7603
7604         case offsetof(struct bpf_sock_addr, user_port):
7605                 /* To get port we need to know sa_family first and then treat
7606                  * sockaddr as either sockaddr_in or sockaddr_in6.
7607                  * Though we can simplify since port field has same offset and
7608                  * size in both structures.
7609                  * Here we check this invariant and use just one of the
7610                  * structures if it's true.
7611                  */
7612                 BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) !=
7613                              offsetof(struct sockaddr_in6, sin6_port));
7614                 BUILD_BUG_ON(FIELD_SIZEOF(struct sockaddr_in, sin_port) !=
7615                              FIELD_SIZEOF(struct sockaddr_in6, sin6_port));
7616                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(struct bpf_sock_addr_kern,
7617                                                      struct sockaddr_in6, uaddr,
7618                                                      sin6_port, tmp_reg);
7619                 break;
7620
7621         case offsetof(struct bpf_sock_addr, family):
7622                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
7623                                             struct sock, sk, sk_family);
7624                 break;
7625
7626         case offsetof(struct bpf_sock_addr, type):
7627                 SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
7628                         struct bpf_sock_addr_kern, struct sock, sk,
7629                         __sk_flags_offset, BPF_W, 0);
7630                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
7631                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
7632                 break;
7633
7634         case offsetof(struct bpf_sock_addr, protocol):
7635                 SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
7636                         struct bpf_sock_addr_kern, struct sock, sk,
7637                         __sk_flags_offset, BPF_W, 0);
7638                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
7639                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
7640                                         SK_FL_PROTO_SHIFT);
7641                 break;
7642
7643         case offsetof(struct bpf_sock_addr, msg_src_ip4):
7644                 /* Treat t_ctx as struct in_addr for msg_src_ip4. */
7645                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7646                         struct bpf_sock_addr_kern, struct in_addr, t_ctx,
7647                         s_addr, BPF_SIZE(si->code), 0, tmp_reg);
7648                 break;
7649
7650         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
7651                                 msg_src_ip6[3]):
7652                 off = si->off;
7653                 off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]);
7654                 /* Treat t_ctx as struct in6_addr for msg_src_ip6. */
7655                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7656                         struct bpf_sock_addr_kern, struct in6_addr, t_ctx,
7657                         s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg);
7658                 break;
7659         }
7660
7661         return insn - insn_buf;
7662 }
7663
7664 static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
7665                                        const struct bpf_insn *si,
7666                                        struct bpf_insn *insn_buf,
7667                                        struct bpf_prog *prog,
7668                                        u32 *target_size)
7669 {
7670         struct bpf_insn *insn = insn_buf;
7671         int off;
7672
7673 /* Helper macro for adding read access to tcp_sock or sock fields. */
7674 #define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
7675         do {                                                                  \
7676                 BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >                   \
7677                              FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
7678                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
7679                                                 struct bpf_sock_ops_kern,     \
7680                                                 is_fullsock),                 \
7681                                       si->dst_reg, si->src_reg,               \
7682                                       offsetof(struct bpf_sock_ops_kern,      \
7683                                                is_fullsock));                 \
7684                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 2);            \
7685                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
7686                                                 struct bpf_sock_ops_kern, sk),\
7687                                       si->dst_reg, si->src_reg,               \
7688                                       offsetof(struct bpf_sock_ops_kern, sk));\
7689                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ,                   \
7690                                                        OBJ_FIELD),            \
7691                                       si->dst_reg, si->dst_reg,               \
7692                                       offsetof(OBJ, OBJ_FIELD));              \
7693         } while (0)
7694
7695 #define SOCK_OPS_GET_TCP_SOCK_FIELD(FIELD) \
7696                 SOCK_OPS_GET_FIELD(FIELD, FIELD, struct tcp_sock)
7697
7698 /* Helper macro for adding write access to tcp_sock or sock fields.
7699  * The macro is called with two registers, dst_reg which contains a pointer
7700  * to ctx (context) and src_reg which contains the value that should be
7701  * stored. However, we need an additional register since we cannot overwrite
7702  * dst_reg because it may be used later in the program.
7703  * Instead we "borrow" one of the other register. We first save its value
7704  * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore
7705  * it at the end of the macro.
7706  */
7707 #define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
7708         do {                                                                  \
7709                 int reg = BPF_REG_9;                                          \
7710                 BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >                   \
7711                              FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
7712                 if (si->dst_reg == reg || si->src_reg == reg)                 \
7713                         reg--;                                                \
7714                 if (si->dst_reg == reg || si->src_reg == reg)                 \
7715                         reg--;                                                \
7716                 *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg,               \
7717                                       offsetof(struct bpf_sock_ops_kern,      \
7718                                                temp));                        \
7719                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
7720                                                 struct bpf_sock_ops_kern,     \
7721                                                 is_fullsock),                 \
7722                                       reg, si->dst_reg,                       \
7723                                       offsetof(struct bpf_sock_ops_kern,      \
7724                                                is_fullsock));                 \
7725                 *insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);                    \
7726                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
7727                                                 struct bpf_sock_ops_kern, sk),\
7728                                       reg, si->dst_reg,                       \
7729                                       offsetof(struct bpf_sock_ops_kern, sk));\
7730                 *insn++ = BPF_STX_MEM(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD),       \
7731                                       reg, si->src_reg,                       \
7732                                       offsetof(OBJ, OBJ_FIELD));              \
7733                 *insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg,               \
7734                                       offsetof(struct bpf_sock_ops_kern,      \
7735                                                temp));                        \
7736         } while (0)
7737
7738 #define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE)            \
7739         do {                                                                  \
7740                 if (TYPE == BPF_WRITE)                                        \
7741                         SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
7742                 else                                                          \
7743                         SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
7744         } while (0)
7745
7746         CONVERT_COMMON_TCP_SOCK_FIELDS(struct bpf_sock_ops,
7747                                        SOCK_OPS_GET_TCP_SOCK_FIELD);
7748
7749         if (insn > insn_buf)
7750                 return insn - insn_buf;
7751
7752         switch (si->off) {
7753         case offsetof(struct bpf_sock_ops, op) ...
7754              offsetof(struct bpf_sock_ops, replylong[3]):
7755                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, op) !=
7756                              FIELD_SIZEOF(struct bpf_sock_ops_kern, op));
7757                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, reply) !=
7758                              FIELD_SIZEOF(struct bpf_sock_ops_kern, reply));
7759                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, replylong) !=
7760                              FIELD_SIZEOF(struct bpf_sock_ops_kern, replylong));
7761                 off = si->off;
7762                 off -= offsetof(struct bpf_sock_ops, op);
7763                 off += offsetof(struct bpf_sock_ops_kern, op);
7764                 if (type == BPF_WRITE)
7765                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7766                                               off);
7767                 else
7768                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7769                                               off);
7770                 break;
7771
7772         case offsetof(struct bpf_sock_ops, family):
7773                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
7774
7775                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7776                                               struct bpf_sock_ops_kern, sk),
7777                                       si->dst_reg, si->src_reg,
7778                                       offsetof(struct bpf_sock_ops_kern, sk));
7779                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7780                                       offsetof(struct sock_common, skc_family));
7781                 break;
7782
7783         case offsetof(struct bpf_sock_ops, remote_ip4):
7784                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
7785
7786                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7787                                                 struct bpf_sock_ops_kern, sk),
7788                                       si->dst_reg, si->src_reg,
7789                                       offsetof(struct bpf_sock_ops_kern, sk));
7790                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7791                                       offsetof(struct sock_common, skc_daddr));
7792                 break;
7793
7794         case offsetof(struct bpf_sock_ops, local_ip4):
7795                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7796                                           skc_rcv_saddr) != 4);
7797
7798                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7799                                               struct bpf_sock_ops_kern, sk),
7800                                       si->dst_reg, si->src_reg,
7801                                       offsetof(struct bpf_sock_ops_kern, sk));
7802                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7803                                       offsetof(struct sock_common,
7804                                                skc_rcv_saddr));
7805                 break;
7806
7807         case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
7808              offsetof(struct bpf_sock_ops, remote_ip6[3]):
7809 #if IS_ENABLED(CONFIG_IPV6)
7810                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7811                                           skc_v6_daddr.s6_addr32[0]) != 4);
7812
7813                 off = si->off;
7814                 off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
7815                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7816                                                 struct bpf_sock_ops_kern, sk),
7817                                       si->dst_reg, si->src_reg,
7818                                       offsetof(struct bpf_sock_ops_kern, sk));
7819                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7820                                       offsetof(struct sock_common,
7821                                                skc_v6_daddr.s6_addr32[0]) +
7822                                       off);
7823 #else
7824                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7825 #endif
7826                 break;
7827
7828         case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
7829              offsetof(struct bpf_sock_ops, local_ip6[3]):
7830 #if IS_ENABLED(CONFIG_IPV6)
7831                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7832                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
7833
7834                 off = si->off;
7835                 off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
7836                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7837                                                 struct bpf_sock_ops_kern, sk),
7838                                       si->dst_reg, si->src_reg,
7839                                       offsetof(struct bpf_sock_ops_kern, sk));
7840                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7841                                       offsetof(struct sock_common,
7842                                                skc_v6_rcv_saddr.s6_addr32[0]) +
7843                                       off);
7844 #else
7845                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7846 #endif
7847                 break;
7848
7849         case offsetof(struct bpf_sock_ops, remote_port):
7850                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
7851
7852                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7853                                                 struct bpf_sock_ops_kern, sk),
7854                                       si->dst_reg, si->src_reg,
7855                                       offsetof(struct bpf_sock_ops_kern, sk));
7856                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7857                                       offsetof(struct sock_common, skc_dport));
7858 #ifndef __BIG_ENDIAN_BITFIELD
7859                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
7860 #endif
7861                 break;
7862
7863         case offsetof(struct bpf_sock_ops, local_port):
7864                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
7865
7866                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7867                                                 struct bpf_sock_ops_kern, sk),
7868                                       si->dst_reg, si->src_reg,
7869                                       offsetof(struct bpf_sock_ops_kern, sk));
7870                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7871                                       offsetof(struct sock_common, skc_num));
7872                 break;
7873
7874         case offsetof(struct bpf_sock_ops, is_fullsock):
7875                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7876                                                 struct bpf_sock_ops_kern,
7877                                                 is_fullsock),
7878                                       si->dst_reg, si->src_reg,
7879                                       offsetof(struct bpf_sock_ops_kern,
7880                                                is_fullsock));
7881                 break;
7882
7883         case offsetof(struct bpf_sock_ops, state):
7884                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_state) != 1);
7885
7886                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7887                                                 struct bpf_sock_ops_kern, sk),
7888                                       si->dst_reg, si->src_reg,
7889                                       offsetof(struct bpf_sock_ops_kern, sk));
7890                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg,
7891                                       offsetof(struct sock_common, skc_state));
7892                 break;
7893
7894         case offsetof(struct bpf_sock_ops, rtt_min):
7895                 BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) !=
7896                              sizeof(struct minmax));
7897                 BUILD_BUG_ON(sizeof(struct minmax) <
7898                              sizeof(struct minmax_sample));
7899
7900                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7901                                                 struct bpf_sock_ops_kern, sk),
7902                                       si->dst_reg, si->src_reg,
7903                                       offsetof(struct bpf_sock_ops_kern, sk));
7904                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7905                                       offsetof(struct tcp_sock, rtt_min) +
7906                                       FIELD_SIZEOF(struct minmax_sample, t));
7907                 break;
7908
7909         case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags):
7910                 SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags,
7911                                    struct tcp_sock);
7912                 break;
7913
7914         case offsetof(struct bpf_sock_ops, sk_txhash):
7915                 SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash,
7916                                           struct sock, type);
7917                 break;
7918         }
7919         return insn - insn_buf;
7920 }
7921
7922 static u32 sk_skb_convert_ctx_access(enum bpf_access_type type,
7923                                      const struct bpf_insn *si,
7924                                      struct bpf_insn *insn_buf,
7925                                      struct bpf_prog *prog, u32 *target_size)
7926 {
7927         struct bpf_insn *insn = insn_buf;
7928         int off;
7929
7930         switch (si->off) {
7931         case offsetof(struct __sk_buff, data_end):
7932                 off  = si->off;
7933                 off -= offsetof(struct __sk_buff, data_end);
7934                 off += offsetof(struct sk_buff, cb);
7935                 off += offsetof(struct tcp_skb_cb, bpf.data_end);
7936                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7937                                       si->src_reg, off);
7938                 break;
7939         default:
7940                 return bpf_convert_ctx_access(type, si, insn_buf, prog,
7941                                               target_size);
7942         }
7943
7944         return insn - insn_buf;
7945 }
7946
7947 static u32 sk_msg_convert_ctx_access(enum bpf_access_type type,
7948                                      const struct bpf_insn *si,
7949                                      struct bpf_insn *insn_buf,
7950                                      struct bpf_prog *prog, u32 *target_size)
7951 {
7952         struct bpf_insn *insn = insn_buf;
7953 #if IS_ENABLED(CONFIG_IPV6)
7954         int off;
7955 #endif
7956
7957         /* convert ctx uses the fact sg element is first in struct */
7958         BUILD_BUG_ON(offsetof(struct sk_msg, sg) != 0);
7959
7960         switch (si->off) {
7961         case offsetof(struct sk_msg_md, data):
7962                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data),
7963                                       si->dst_reg, si->src_reg,
7964                                       offsetof(struct sk_msg, data));
7965                 break;
7966         case offsetof(struct sk_msg_md, data_end):
7967                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data_end),
7968                                       si->dst_reg, si->src_reg,
7969                                       offsetof(struct sk_msg, data_end));
7970                 break;
7971         case offsetof(struct sk_msg_md, family):
7972                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
7973
7974                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7975                                               struct sk_msg, sk),
7976                                       si->dst_reg, si->src_reg,
7977                                       offsetof(struct sk_msg, sk));
7978                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7979                                       offsetof(struct sock_common, skc_family));
7980                 break;
7981
7982         case offsetof(struct sk_msg_md, remote_ip4):
7983                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
7984
7985                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7986                                                 struct sk_msg, sk),
7987                                       si->dst_reg, si->src_reg,
7988                                       offsetof(struct sk_msg, sk));
7989                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7990                                       offsetof(struct sock_common, skc_daddr));
7991                 break;
7992
7993         case offsetof(struct sk_msg_md, local_ip4):
7994                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7995                                           skc_rcv_saddr) != 4);
7996
7997                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
7998                                               struct sk_msg, sk),
7999                                       si->dst_reg, si->src_reg,
8000                                       offsetof(struct sk_msg, sk));
8001                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8002                                       offsetof(struct sock_common,
8003                                                skc_rcv_saddr));
8004                 break;
8005
8006         case offsetof(struct sk_msg_md, remote_ip6[0]) ...
8007              offsetof(struct sk_msg_md, remote_ip6[3]):
8008 #if IS_ENABLED(CONFIG_IPV6)
8009                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8010                                           skc_v6_daddr.s6_addr32[0]) != 4);
8011
8012                 off = si->off;
8013                 off -= offsetof(struct sk_msg_md, remote_ip6[0]);
8014                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8015                                                 struct sk_msg, sk),
8016                                       si->dst_reg, si->src_reg,
8017                                       offsetof(struct sk_msg, sk));
8018                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8019                                       offsetof(struct sock_common,
8020                                                skc_v6_daddr.s6_addr32[0]) +
8021                                       off);
8022 #else
8023                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8024 #endif
8025                 break;
8026
8027         case offsetof(struct sk_msg_md, local_ip6[0]) ...
8028              offsetof(struct sk_msg_md, local_ip6[3]):
8029 #if IS_ENABLED(CONFIG_IPV6)
8030                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8031                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
8032
8033                 off = si->off;
8034                 off -= offsetof(struct sk_msg_md, local_ip6[0]);
8035                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8036                                                 struct sk_msg, sk),
8037                                       si->dst_reg, si->src_reg,
8038                                       offsetof(struct sk_msg, sk));
8039                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8040                                       offsetof(struct sock_common,
8041                                                skc_v6_rcv_saddr.s6_addr32[0]) +
8042                                       off);
8043 #else
8044                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8045 #endif
8046                 break;
8047
8048         case offsetof(struct sk_msg_md, remote_port):
8049                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
8050
8051                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8052                                                 struct sk_msg, sk),
8053                                       si->dst_reg, si->src_reg,
8054                                       offsetof(struct sk_msg, sk));
8055                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8056                                       offsetof(struct sock_common, skc_dport));
8057 #ifndef __BIG_ENDIAN_BITFIELD
8058                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
8059 #endif
8060                 break;
8061
8062         case offsetof(struct sk_msg_md, local_port):
8063                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
8064
8065                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8066                                                 struct sk_msg, sk),
8067                                       si->dst_reg, si->src_reg,
8068                                       offsetof(struct sk_msg, sk));
8069                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8070                                       offsetof(struct sock_common, skc_num));
8071                 break;
8072
8073         case offsetof(struct sk_msg_md, size):
8074                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_sg, size),
8075                                       si->dst_reg, si->src_reg,
8076                                       offsetof(struct sk_msg_sg, size));
8077                 break;
8078         }
8079
8080         return insn - insn_buf;
8081 }
8082
8083 const struct bpf_verifier_ops sk_filter_verifier_ops = {
8084         .get_func_proto         = sk_filter_func_proto,
8085         .is_valid_access        = sk_filter_is_valid_access,
8086         .convert_ctx_access     = bpf_convert_ctx_access,
8087         .gen_ld_abs             = bpf_gen_ld_abs,
8088 };
8089
8090 const struct bpf_prog_ops sk_filter_prog_ops = {
8091         .test_run               = bpf_prog_test_run_skb,
8092 };
8093
8094 const struct bpf_verifier_ops tc_cls_act_verifier_ops = {
8095         .get_func_proto         = tc_cls_act_func_proto,
8096         .is_valid_access        = tc_cls_act_is_valid_access,
8097         .convert_ctx_access     = tc_cls_act_convert_ctx_access,
8098         .gen_prologue           = tc_cls_act_prologue,
8099         .gen_ld_abs             = bpf_gen_ld_abs,
8100 };
8101
8102 const struct bpf_prog_ops tc_cls_act_prog_ops = {
8103         .test_run               = bpf_prog_test_run_skb,
8104 };
8105
8106 const struct bpf_verifier_ops xdp_verifier_ops = {
8107         .get_func_proto         = xdp_func_proto,
8108         .is_valid_access        = xdp_is_valid_access,
8109         .convert_ctx_access     = xdp_convert_ctx_access,
8110         .gen_prologue           = bpf_noop_prologue,
8111 };
8112
8113 const struct bpf_prog_ops xdp_prog_ops = {
8114         .test_run               = bpf_prog_test_run_xdp,
8115 };
8116
8117 const struct bpf_verifier_ops cg_skb_verifier_ops = {
8118         .get_func_proto         = cg_skb_func_proto,
8119         .is_valid_access        = cg_skb_is_valid_access,
8120         .convert_ctx_access     = bpf_convert_ctx_access,
8121 };
8122
8123 const struct bpf_prog_ops cg_skb_prog_ops = {
8124         .test_run               = bpf_prog_test_run_skb,
8125 };
8126
8127 const struct bpf_verifier_ops lwt_in_verifier_ops = {
8128         .get_func_proto         = lwt_in_func_proto,
8129         .is_valid_access        = lwt_is_valid_access,
8130         .convert_ctx_access     = bpf_convert_ctx_access,
8131 };
8132
8133 const struct bpf_prog_ops lwt_in_prog_ops = {
8134         .test_run               = bpf_prog_test_run_skb,
8135 };
8136
8137 const struct bpf_verifier_ops lwt_out_verifier_ops = {
8138         .get_func_proto         = lwt_out_func_proto,
8139         .is_valid_access        = lwt_is_valid_access,
8140         .convert_ctx_access     = bpf_convert_ctx_access,
8141 };
8142
8143 const struct bpf_prog_ops lwt_out_prog_ops = {
8144         .test_run               = bpf_prog_test_run_skb,
8145 };
8146
8147 const struct bpf_verifier_ops lwt_xmit_verifier_ops = {
8148         .get_func_proto         = lwt_xmit_func_proto,
8149         .is_valid_access        = lwt_is_valid_access,
8150         .convert_ctx_access     = bpf_convert_ctx_access,
8151         .gen_prologue           = tc_cls_act_prologue,
8152 };
8153
8154 const struct bpf_prog_ops lwt_xmit_prog_ops = {
8155         .test_run               = bpf_prog_test_run_skb,
8156 };
8157
8158 const struct bpf_verifier_ops lwt_seg6local_verifier_ops = {
8159         .get_func_proto         = lwt_seg6local_func_proto,
8160         .is_valid_access        = lwt_is_valid_access,
8161         .convert_ctx_access     = bpf_convert_ctx_access,
8162 };
8163
8164 const struct bpf_prog_ops lwt_seg6local_prog_ops = {
8165         .test_run               = bpf_prog_test_run_skb,
8166 };
8167
8168 const struct bpf_verifier_ops cg_sock_verifier_ops = {
8169         .get_func_proto         = sock_filter_func_proto,
8170         .is_valid_access        = sock_filter_is_valid_access,
8171         .convert_ctx_access     = bpf_sock_convert_ctx_access,
8172 };
8173
8174 const struct bpf_prog_ops cg_sock_prog_ops = {
8175 };
8176
8177 const struct bpf_verifier_ops cg_sock_addr_verifier_ops = {
8178         .get_func_proto         = sock_addr_func_proto,
8179         .is_valid_access        = sock_addr_is_valid_access,
8180         .convert_ctx_access     = sock_addr_convert_ctx_access,
8181 };
8182
8183 const struct bpf_prog_ops cg_sock_addr_prog_ops = {
8184 };
8185
8186 const struct bpf_verifier_ops sock_ops_verifier_ops = {
8187         .get_func_proto         = sock_ops_func_proto,
8188         .is_valid_access        = sock_ops_is_valid_access,
8189         .convert_ctx_access     = sock_ops_convert_ctx_access,
8190 };
8191
8192 const struct bpf_prog_ops sock_ops_prog_ops = {
8193 };
8194
8195 const struct bpf_verifier_ops sk_skb_verifier_ops = {
8196         .get_func_proto         = sk_skb_func_proto,
8197         .is_valid_access        = sk_skb_is_valid_access,
8198         .convert_ctx_access     = sk_skb_convert_ctx_access,
8199         .gen_prologue           = sk_skb_prologue,
8200 };
8201
8202 const struct bpf_prog_ops sk_skb_prog_ops = {
8203 };
8204
8205 const struct bpf_verifier_ops sk_msg_verifier_ops = {
8206         .get_func_proto         = sk_msg_func_proto,
8207         .is_valid_access        = sk_msg_is_valid_access,
8208         .convert_ctx_access     = sk_msg_convert_ctx_access,
8209         .gen_prologue           = bpf_noop_prologue,
8210 };
8211
8212 const struct bpf_prog_ops sk_msg_prog_ops = {
8213 };
8214
8215 const struct bpf_verifier_ops flow_dissector_verifier_ops = {
8216         .get_func_proto         = flow_dissector_func_proto,
8217         .is_valid_access        = flow_dissector_is_valid_access,
8218         .convert_ctx_access     = bpf_convert_ctx_access,
8219 };
8220
8221 const struct bpf_prog_ops flow_dissector_prog_ops = {
8222         .test_run               = bpf_prog_test_run_flow_dissector,
8223 };
8224
8225 int sk_detach_filter(struct sock *sk)
8226 {
8227         int ret = -ENOENT;
8228         struct sk_filter *filter;
8229
8230         if (sock_flag(sk, SOCK_FILTER_LOCKED))
8231                 return -EPERM;
8232
8233         filter = rcu_dereference_protected(sk->sk_filter,
8234                                            lockdep_sock_is_held(sk));
8235         if (filter) {
8236                 RCU_INIT_POINTER(sk->sk_filter, NULL);
8237                 sk_filter_uncharge(sk, filter);
8238                 ret = 0;
8239         }
8240
8241         return ret;
8242 }
8243 EXPORT_SYMBOL_GPL(sk_detach_filter);
8244
8245 int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
8246                   unsigned int len)
8247 {
8248         struct sock_fprog_kern *fprog;
8249         struct sk_filter *filter;
8250         int ret = 0;
8251
8252         lock_sock(sk);
8253         filter = rcu_dereference_protected(sk->sk_filter,
8254                                            lockdep_sock_is_held(sk));
8255         if (!filter)
8256                 goto out;
8257
8258         /* We're copying the filter that has been originally attached,
8259          * so no conversion/decode needed anymore. eBPF programs that
8260          * have no original program cannot be dumped through this.
8261          */
8262         ret = -EACCES;
8263         fprog = filter->prog->orig_prog;
8264         if (!fprog)
8265                 goto out;
8266
8267         ret = fprog->len;
8268         if (!len)
8269                 /* User space only enquires number of filter blocks. */
8270                 goto out;
8271
8272         ret = -EINVAL;
8273         if (len < fprog->len)
8274                 goto out;
8275
8276         ret = -EFAULT;
8277         if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
8278                 goto out;
8279
8280         /* Instead of bytes, the API requests to return the number
8281          * of filter blocks.
8282          */
8283         ret = fprog->len;
8284 out:
8285         release_sock(sk);
8286         return ret;
8287 }
8288
8289 #ifdef CONFIG_INET
8290 struct sk_reuseport_kern {
8291         struct sk_buff *skb;
8292         struct sock *sk;
8293         struct sock *selected_sk;
8294         void *data_end;
8295         u32 hash;
8296         u32 reuseport_id;
8297         bool bind_inany;
8298 };
8299
8300 static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,
8301                                     struct sock_reuseport *reuse,
8302                                     struct sock *sk, struct sk_buff *skb,
8303                                     u32 hash)
8304 {
8305         reuse_kern->skb = skb;
8306         reuse_kern->sk = sk;
8307         reuse_kern->selected_sk = NULL;
8308         reuse_kern->data_end = skb->data + skb_headlen(skb);
8309         reuse_kern->hash = hash;
8310         reuse_kern->reuseport_id = reuse->reuseport_id;
8311         reuse_kern->bind_inany = reuse->bind_inany;
8312 }
8313
8314 struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,
8315                                   struct bpf_prog *prog, struct sk_buff *skb,
8316                                   u32 hash)
8317 {
8318         struct sk_reuseport_kern reuse_kern;
8319         enum sk_action action;
8320
8321         bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, hash);
8322         action = BPF_PROG_RUN(prog, &reuse_kern);
8323
8324         if (action == SK_PASS)
8325                 return reuse_kern.selected_sk;
8326         else
8327                 return ERR_PTR(-ECONNREFUSED);
8328 }
8329
8330 BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern,
8331            struct bpf_map *, map, void *, key, u32, flags)
8332 {
8333         struct sock_reuseport *reuse;
8334         struct sock *selected_sk;
8335
8336         selected_sk = map->ops->map_lookup_elem(map, key);
8337         if (!selected_sk)
8338                 return -ENOENT;
8339
8340         reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
8341         if (!reuse)
8342                 /* selected_sk is unhashed (e.g. by close()) after the
8343                  * above map_lookup_elem().  Treat selected_sk has already
8344                  * been removed from the map.
8345                  */
8346                 return -ENOENT;
8347
8348         if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
8349                 struct sock *sk;
8350
8351                 if (unlikely(!reuse_kern->reuseport_id))
8352                         /* There is a small race between adding the
8353                          * sk to the map and setting the
8354                          * reuse_kern->reuseport_id.
8355                          * Treat it as the sk has not been added to
8356                          * the bpf map yet.
8357                          */
8358                         return -ENOENT;
8359
8360                 sk = reuse_kern->sk;
8361                 if (sk->sk_protocol != selected_sk->sk_protocol)
8362                         return -EPROTOTYPE;
8363                 else if (sk->sk_family != selected_sk->sk_family)
8364                         return -EAFNOSUPPORT;
8365
8366                 /* Catch all. Likely bound to a different sockaddr. */
8367                 return -EBADFD;
8368         }
8369
8370         reuse_kern->selected_sk = selected_sk;
8371
8372         return 0;
8373 }
8374
8375 static const struct bpf_func_proto sk_select_reuseport_proto = {
8376         .func           = sk_select_reuseport,
8377         .gpl_only       = false,
8378         .ret_type       = RET_INTEGER,
8379         .arg1_type      = ARG_PTR_TO_CTX,
8380         .arg2_type      = ARG_CONST_MAP_PTR,
8381         .arg3_type      = ARG_PTR_TO_MAP_KEY,
8382         .arg4_type      = ARG_ANYTHING,
8383 };
8384
8385 BPF_CALL_4(sk_reuseport_load_bytes,
8386            const struct sk_reuseport_kern *, reuse_kern, u32, offset,
8387            void *, to, u32, len)
8388 {
8389         return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
8390 }
8391
8392 static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
8393         .func           = sk_reuseport_load_bytes,
8394         .gpl_only       = false,
8395         .ret_type       = RET_INTEGER,
8396         .arg1_type      = ARG_PTR_TO_CTX,
8397         .arg2_type      = ARG_ANYTHING,
8398         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
8399         .arg4_type      = ARG_CONST_SIZE,
8400 };
8401
8402 BPF_CALL_5(sk_reuseport_load_bytes_relative,
8403            const struct sk_reuseport_kern *, reuse_kern, u32, offset,
8404            void *, to, u32, len, u32, start_header)
8405 {
8406         return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
8407                                                len, start_header);
8408 }
8409
8410 static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
8411         .func           = sk_reuseport_load_bytes_relative,
8412         .gpl_only       = false,
8413         .ret_type       = RET_INTEGER,
8414         .arg1_type      = ARG_PTR_TO_CTX,
8415         .arg2_type      = ARG_ANYTHING,
8416         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
8417         .arg4_type      = ARG_CONST_SIZE,
8418         .arg5_type      = ARG_ANYTHING,
8419 };
8420
8421 static const struct bpf_func_proto *
8422 sk_reuseport_func_proto(enum bpf_func_id func_id,
8423                         const struct bpf_prog *prog)
8424 {
8425         switch (func_id) {
8426         case BPF_FUNC_sk_select_reuseport:
8427                 return &sk_select_reuseport_proto;
8428         case BPF_FUNC_skb_load_bytes:
8429                 return &sk_reuseport_load_bytes_proto;
8430         case BPF_FUNC_skb_load_bytes_relative:
8431                 return &sk_reuseport_load_bytes_relative_proto;
8432         default:
8433                 return bpf_base_func_proto(func_id);
8434         }
8435 }
8436
8437 static bool
8438 sk_reuseport_is_valid_access(int off, int size,
8439                              enum bpf_access_type type,
8440                              const struct bpf_prog *prog,
8441                              struct bpf_insn_access_aux *info)
8442 {
8443         const u32 size_default = sizeof(__u32);
8444
8445         if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
8446             off % size || type != BPF_READ)
8447                 return false;
8448
8449         switch (off) {
8450         case offsetof(struct sk_reuseport_md, data):
8451                 info->reg_type = PTR_TO_PACKET;
8452                 return size == sizeof(__u64);
8453
8454         case offsetof(struct sk_reuseport_md, data_end):
8455                 info->reg_type = PTR_TO_PACKET_END;
8456                 return size == sizeof(__u64);
8457
8458         case offsetof(struct sk_reuseport_md, hash):
8459                 return size == size_default;
8460
8461         /* Fields that allow narrowing */
8462         case offsetof(struct sk_reuseport_md, eth_protocol):
8463                 if (size < FIELD_SIZEOF(struct sk_buff, protocol))
8464                         return false;
8465                 /* fall through */
8466         case offsetof(struct sk_reuseport_md, ip_protocol):
8467         case offsetof(struct sk_reuseport_md, bind_inany):
8468         case offsetof(struct sk_reuseport_md, len):
8469                 bpf_ctx_record_field_size(info, size_default);
8470                 return bpf_ctx_narrow_access_ok(off, size, size_default);
8471
8472         default:
8473                 return false;
8474         }
8475 }
8476
8477 #define SK_REUSEPORT_LOAD_FIELD(F) ({                                   \
8478         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
8479                               si->dst_reg, si->src_reg,                 \
8480                               bpf_target_off(struct sk_reuseport_kern, F, \
8481                                              FIELD_SIZEOF(struct sk_reuseport_kern, F), \
8482                                              target_size));             \
8483         })
8484
8485 #define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)                          \
8486         SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,           \
8487                                     struct sk_buff,                     \
8488                                     skb,                                \
8489                                     SKB_FIELD)
8490
8491 #define SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(SK_FIELD, BPF_SIZE, EXTRA_OFF) \
8492         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(struct sk_reuseport_kern,  \
8493                                              struct sock,               \
8494                                              sk,                        \
8495                                              SK_FIELD, BPF_SIZE, EXTRA_OFF)
8496
8497 static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
8498                                            const struct bpf_insn *si,
8499                                            struct bpf_insn *insn_buf,
8500                                            struct bpf_prog *prog,
8501                                            u32 *target_size)
8502 {
8503         struct bpf_insn *insn = insn_buf;
8504
8505         switch (si->off) {
8506         case offsetof(struct sk_reuseport_md, data):
8507                 SK_REUSEPORT_LOAD_SKB_FIELD(data);
8508                 break;
8509
8510         case offsetof(struct sk_reuseport_md, len):
8511                 SK_REUSEPORT_LOAD_SKB_FIELD(len);
8512                 break;
8513
8514         case offsetof(struct sk_reuseport_md, eth_protocol):
8515                 SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
8516                 break;
8517
8518         case offsetof(struct sk_reuseport_md, ip_protocol):
8519                 BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE);
8520                 SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(__sk_flags_offset,
8521                                                     BPF_W, 0);
8522                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
8523                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
8524                                         SK_FL_PROTO_SHIFT);
8525                 /* SK_FL_PROTO_MASK and SK_FL_PROTO_SHIFT are endian
8526                  * aware.  No further narrowing or masking is needed.
8527                  */
8528                 *target_size = 1;
8529                 break;
8530
8531         case offsetof(struct sk_reuseport_md, data_end):
8532                 SK_REUSEPORT_LOAD_FIELD(data_end);
8533                 break;
8534
8535         case offsetof(struct sk_reuseport_md, hash):
8536                 SK_REUSEPORT_LOAD_FIELD(hash);
8537                 break;
8538
8539         case offsetof(struct sk_reuseport_md, bind_inany):
8540                 SK_REUSEPORT_LOAD_FIELD(bind_inany);
8541                 break;
8542         }
8543
8544         return insn - insn_buf;
8545 }
8546
8547 const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
8548         .get_func_proto         = sk_reuseport_func_proto,
8549         .is_valid_access        = sk_reuseport_is_valid_access,
8550         .convert_ctx_access     = sk_reuseport_convert_ctx_access,
8551 };
8552
8553 const struct bpf_prog_ops sk_reuseport_prog_ops = {
8554 };
8555 #endif /* CONFIG_INET */