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