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