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