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