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