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