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