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