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