46321033ae0e7797cdea89d17a87ba29755267b8
[platform/kernel/linux-rpi.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/ip.h>
37 #include <net/protocol.h>
38 #include <net/netlink.h>
39 #include <linux/skbuff.h>
40 #include <net/sock.h>
41 #include <net/flow_dissector.h>
42 #include <linux/errno.h>
43 #include <linux/timer.h>
44 #include <linux/uaccess.h>
45 #include <asm/unaligned.h>
46 #include <linux/filter.h>
47 #include <linux/ratelimit.h>
48 #include <linux/seccomp.h>
49 #include <linux/if_vlan.h>
50 #include <linux/bpf.h>
51 #include <net/sch_generic.h>
52 #include <net/cls_cgroup.h>
53 #include <net/dst_metadata.h>
54 #include <net/dst.h>
55 #include <net/sock_reuseport.h>
56 #include <net/busy_poll.h>
57 #include <net/tcp.h>
58 #include <linux/bpf_trace.h>
59
60 /**
61  *      sk_filter_trim_cap - run a packet through a socket filter
62  *      @sk: sock associated with &sk_buff
63  *      @skb: buffer to filter
64  *      @cap: limit on how short the eBPF program may trim the packet
65  *
66  * Run the eBPF program and then cut skb->data to correct size returned by
67  * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
68  * than pkt_len we keep whole skb->data. This is the socket level
69  * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
70  * be accepted or -EPERM if the packet should be tossed.
71  *
72  */
73 int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
74 {
75         int err;
76         struct sk_filter *filter;
77
78         /*
79          * If the skb was allocated from pfmemalloc reserves, only
80          * allow SOCK_MEMALLOC sockets to use it as this socket is
81          * helping free memory
82          */
83         if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
84                 NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
85                 return -ENOMEM;
86         }
87         err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
88         if (err)
89                 return err;
90
91         err = security_sock_rcv_skb(sk, skb);
92         if (err)
93                 return err;
94
95         rcu_read_lock();
96         filter = rcu_dereference(sk->sk_filter);
97         if (filter) {
98                 struct sock *save_sk = skb->sk;
99                 unsigned int pkt_len;
100
101                 skb->sk = sk;
102                 pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
103                 skb->sk = save_sk;
104                 err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
105         }
106         rcu_read_unlock();
107
108         return err;
109 }
110 EXPORT_SYMBOL(sk_filter_trim_cap);
111
112 BPF_CALL_1(__skb_get_pay_offset, struct sk_buff *, skb)
113 {
114         return skb_get_poff(skb);
115 }
116
117 BPF_CALL_3(__skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
118 {
119         struct nlattr *nla;
120
121         if (skb_is_nonlinear(skb))
122                 return 0;
123
124         if (skb->len < sizeof(struct nlattr))
125                 return 0;
126
127         if (a > skb->len - sizeof(struct nlattr))
128                 return 0;
129
130         nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
131         if (nla)
132                 return (void *) nla - (void *) skb->data;
133
134         return 0;
135 }
136
137 BPF_CALL_3(__skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
138 {
139         struct nlattr *nla;
140
141         if (skb_is_nonlinear(skb))
142                 return 0;
143
144         if (skb->len < sizeof(struct nlattr))
145                 return 0;
146
147         if (a > skb->len - sizeof(struct nlattr))
148                 return 0;
149
150         nla = (struct nlattr *) &skb->data[a];
151         if (nla->nla_len > skb->len - a)
152                 return 0;
153
154         nla = nla_find_nested(nla, x);
155         if (nla)
156                 return (void *) nla - (void *) skb->data;
157
158         return 0;
159 }
160
161 BPF_CALL_0(__get_raw_cpu_id)
162 {
163         return raw_smp_processor_id();
164 }
165
166 static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
167         .func           = __get_raw_cpu_id,
168         .gpl_only       = false,
169         .ret_type       = RET_INTEGER,
170 };
171
172 static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
173                               struct bpf_insn *insn_buf)
174 {
175         struct bpf_insn *insn = insn_buf;
176
177         switch (skb_field) {
178         case SKF_AD_MARK:
179                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);
180
181                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
182                                       offsetof(struct sk_buff, mark));
183                 break;
184
185         case SKF_AD_PKTTYPE:
186                 *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET());
187                 *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
188 #ifdef __BIG_ENDIAN_BITFIELD
189                 *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
190 #endif
191                 break;
192
193         case SKF_AD_QUEUE:
194                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2);
195
196                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
197                                       offsetof(struct sk_buff, queue_mapping));
198                 break;
199
200         case SKF_AD_VLAN_TAG:
201         case SKF_AD_VLAN_TAG_PRESENT:
202                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_tci) != 2);
203                 BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);
204
205                 /* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
206                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
207                                       offsetof(struct sk_buff, vlan_tci));
208                 if (skb_field == SKF_AD_VLAN_TAG) {
209                         *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg,
210                                                 ~VLAN_TAG_PRESENT);
211                 } else {
212                         /* dst_reg >>= 12 */
213                         *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 12);
214                         /* dst_reg &= 1 */
215                         *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1);
216                 }
217                 break;
218         }
219
220         return insn - insn_buf;
221 }
222
223 static bool convert_bpf_extensions(struct sock_filter *fp,
224                                    struct bpf_insn **insnp)
225 {
226         struct bpf_insn *insn = *insnp;
227         u32 cnt;
228
229         switch (fp->k) {
230         case SKF_AD_OFF + SKF_AD_PROTOCOL:
231                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);
232
233                 /* A = *(u16 *) (CTX + offsetof(protocol)) */
234                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
235                                       offsetof(struct sk_buff, protocol));
236                 /* A = ntohs(A) [emitting a nop or swap16] */
237                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
238                 break;
239
240         case SKF_AD_OFF + SKF_AD_PKTTYPE:
241                 cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
242                 insn += cnt - 1;
243                 break;
244
245         case SKF_AD_OFF + SKF_AD_IFINDEX:
246         case SKF_AD_OFF + SKF_AD_HATYPE:
247                 BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
248                 BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, type) != 2);
249
250                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
251                                       BPF_REG_TMP, BPF_REG_CTX,
252                                       offsetof(struct sk_buff, dev));
253                 /* if (tmp != 0) goto pc + 1 */
254                 *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
255                 *insn++ = BPF_EXIT_INSN();
256                 if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
257                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
258                                             offsetof(struct net_device, ifindex));
259                 else
260                         *insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
261                                             offsetof(struct net_device, type));
262                 break;
263
264         case SKF_AD_OFF + SKF_AD_MARK:
265                 cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
266                 insn += cnt - 1;
267                 break;
268
269         case SKF_AD_OFF + SKF_AD_RXHASH:
270                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);
271
272                 *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
273                                     offsetof(struct sk_buff, hash));
274                 break;
275
276         case SKF_AD_OFF + SKF_AD_QUEUE:
277                 cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
278                 insn += cnt - 1;
279                 break;
280
281         case SKF_AD_OFF + SKF_AD_VLAN_TAG:
282                 cnt = convert_skb_access(SKF_AD_VLAN_TAG,
283                                          BPF_REG_A, BPF_REG_CTX, insn);
284                 insn += cnt - 1;
285                 break;
286
287         case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
288                 cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
289                                          BPF_REG_A, BPF_REG_CTX, insn);
290                 insn += cnt - 1;
291                 break;
292
293         case SKF_AD_OFF + SKF_AD_VLAN_TPID:
294                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);
295
296                 /* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
297                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
298                                       offsetof(struct sk_buff, vlan_proto));
299                 /* A = ntohs(A) [emitting a nop or swap16] */
300                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
301                 break;
302
303         case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
304         case SKF_AD_OFF + SKF_AD_NLATTR:
305         case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
306         case SKF_AD_OFF + SKF_AD_CPU:
307         case SKF_AD_OFF + SKF_AD_RANDOM:
308                 /* arg1 = CTX */
309                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
310                 /* arg2 = A */
311                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
312                 /* arg3 = X */
313                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
314                 /* Emit call(arg1=CTX, arg2=A, arg3=X) */
315                 switch (fp->k) {
316                 case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
317                         *insn = BPF_EMIT_CALL(__skb_get_pay_offset);
318                         break;
319                 case SKF_AD_OFF + SKF_AD_NLATTR:
320                         *insn = BPF_EMIT_CALL(__skb_get_nlattr);
321                         break;
322                 case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
323                         *insn = BPF_EMIT_CALL(__skb_get_nlattr_nest);
324                         break;
325                 case SKF_AD_OFF + SKF_AD_CPU:
326                         *insn = BPF_EMIT_CALL(__get_raw_cpu_id);
327                         break;
328                 case SKF_AD_OFF + SKF_AD_RANDOM:
329                         *insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
330                         bpf_user_rnd_init_once();
331                         break;
332                 }
333                 break;
334
335         case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
336                 /* A ^= X */
337                 *insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
338                 break;
339
340         default:
341                 /* This is just a dummy call to avoid letting the compiler
342                  * evict __bpf_call_base() as an optimization. Placed here
343                  * where no-one bothers.
344                  */
345                 BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
346                 return false;
347         }
348
349         *insnp = insn;
350         return true;
351 }
352
353 /**
354  *      bpf_convert_filter - convert filter program
355  *      @prog: the user passed filter program
356  *      @len: the length of the user passed filter program
357  *      @new_prog: allocated 'struct bpf_prog' or NULL
358  *      @new_len: pointer to store length of converted program
359  *
360  * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
361  * style extended BPF (eBPF).
362  * Conversion workflow:
363  *
364  * 1) First pass for calculating the new program length:
365  *   bpf_convert_filter(old_prog, old_len, NULL, &new_len)
366  *
367  * 2) 2nd pass to remap in two passes: 1st pass finds new
368  *    jump offsets, 2nd pass remapping:
369  *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len);
370  */
371 static int bpf_convert_filter(struct sock_filter *prog, int len,
372                               struct bpf_prog *new_prog, int *new_len)
373 {
374         int new_flen = 0, pass = 0, target, i, stack_off;
375         struct bpf_insn *new_insn, *first_insn = NULL;
376         struct sock_filter *fp;
377         int *addrs = NULL;
378         u8 bpf_src;
379
380         BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
381         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
382
383         if (len <= 0 || len > BPF_MAXINSNS)
384                 return -EINVAL;
385
386         if (new_prog) {
387                 first_insn = new_prog->insnsi;
388                 addrs = kcalloc(len, sizeof(*addrs),
389                                 GFP_KERNEL | __GFP_NOWARN);
390                 if (!addrs)
391                         return -ENOMEM;
392         }
393
394 do_pass:
395         new_insn = first_insn;
396         fp = prog;
397
398         /* Classic BPF related prologue emission. */
399         if (new_prog) {
400                 /* Classic BPF expects A and X to be reset first. These need
401                  * to be guaranteed to be the first two instructions.
402                  */
403                 *new_insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
404                 *new_insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
405
406                 /* All programs must keep CTX in callee saved BPF_REG_CTX.
407                  * In eBPF case it's done by the compiler, here we need to
408                  * do this ourself. Initial CTX is present in BPF_REG_ARG1.
409                  */
410                 *new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
411         } else {
412                 new_insn += 3;
413         }
414
415         for (i = 0; i < len; fp++, i++) {
416                 struct bpf_insn tmp_insns[6] = { };
417                 struct bpf_insn *insn = tmp_insns;
418
419                 if (addrs)
420                         addrs[i] = new_insn - first_insn;
421
422                 switch (fp->code) {
423                 /* All arithmetic insns and skb loads map as-is. */
424                 case BPF_ALU | BPF_ADD | BPF_X:
425                 case BPF_ALU | BPF_ADD | BPF_K:
426                 case BPF_ALU | BPF_SUB | BPF_X:
427                 case BPF_ALU | BPF_SUB | BPF_K:
428                 case BPF_ALU | BPF_AND | BPF_X:
429                 case BPF_ALU | BPF_AND | BPF_K:
430                 case BPF_ALU | BPF_OR | BPF_X:
431                 case BPF_ALU | BPF_OR | BPF_K:
432                 case BPF_ALU | BPF_LSH | BPF_X:
433                 case BPF_ALU | BPF_LSH | BPF_K:
434                 case BPF_ALU | BPF_RSH | BPF_X:
435                 case BPF_ALU | BPF_RSH | BPF_K:
436                 case BPF_ALU | BPF_XOR | BPF_X:
437                 case BPF_ALU | BPF_XOR | BPF_K:
438                 case BPF_ALU | BPF_MUL | BPF_X:
439                 case BPF_ALU | BPF_MUL | BPF_K:
440                 case BPF_ALU | BPF_DIV | BPF_X:
441                 case BPF_ALU | BPF_DIV | BPF_K:
442                 case BPF_ALU | BPF_MOD | BPF_X:
443                 case BPF_ALU | BPF_MOD | BPF_K:
444                 case BPF_ALU | BPF_NEG:
445                 case BPF_LD | BPF_ABS | BPF_W:
446                 case BPF_LD | BPF_ABS | BPF_H:
447                 case BPF_LD | BPF_ABS | BPF_B:
448                 case BPF_LD | BPF_IND | BPF_W:
449                 case BPF_LD | BPF_IND | BPF_H:
450                 case BPF_LD | BPF_IND | BPF_B:
451                         /* Check for overloaded BPF extension and
452                          * directly convert it if found, otherwise
453                          * just move on with mapping.
454                          */
455                         if (BPF_CLASS(fp->code) == BPF_LD &&
456                             BPF_MODE(fp->code) == BPF_ABS &&
457                             convert_bpf_extensions(fp, &insn))
458                                 break;
459
460                         *insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
461                         break;
462
463                 /* Jump transformation cannot use BPF block macros
464                  * everywhere as offset calculation and target updates
465                  * require a bit more work than the rest, i.e. jump
466                  * opcodes map as-is, but offsets need adjustment.
467                  */
468
469 #define BPF_EMIT_JMP                                                    \
470         do {                                                            \
471                 if (target >= len || target < 0)                        \
472                         goto err;                                       \
473                 insn->off = addrs ? addrs[target] - addrs[i] - 1 : 0;   \
474                 /* Adjust pc relative offset for 2nd or 3rd insn. */    \
475                 insn->off -= insn - tmp_insns;                          \
476         } while (0)
477
478                 case BPF_JMP | BPF_JA:
479                         target = i + fp->k + 1;
480                         insn->code = fp->code;
481                         BPF_EMIT_JMP;
482                         break;
483
484                 case BPF_JMP | BPF_JEQ | BPF_K:
485                 case BPF_JMP | BPF_JEQ | BPF_X:
486                 case BPF_JMP | BPF_JSET | BPF_K:
487                 case BPF_JMP | BPF_JSET | BPF_X:
488                 case BPF_JMP | BPF_JGT | BPF_K:
489                 case BPF_JMP | BPF_JGT | BPF_X:
490                 case BPF_JMP | BPF_JGE | BPF_K:
491                 case BPF_JMP | BPF_JGE | BPF_X:
492                         if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
493                                 /* BPF immediates are signed, zero extend
494                                  * immediate into tmp register and use it
495                                  * in compare insn.
496                                  */
497                                 *insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
498
499                                 insn->dst_reg = BPF_REG_A;
500                                 insn->src_reg = BPF_REG_TMP;
501                                 bpf_src = BPF_X;
502                         } else {
503                                 insn->dst_reg = BPF_REG_A;
504                                 insn->imm = fp->k;
505                                 bpf_src = BPF_SRC(fp->code);
506                                 insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
507                         }
508
509                         /* Common case where 'jump_false' is next insn. */
510                         if (fp->jf == 0) {
511                                 insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
512                                 target = i + fp->jt + 1;
513                                 BPF_EMIT_JMP;
514                                 break;
515                         }
516
517                         /* Convert some jumps when 'jump_true' is next insn. */
518                         if (fp->jt == 0) {
519                                 switch (BPF_OP(fp->code)) {
520                                 case BPF_JEQ:
521                                         insn->code = BPF_JMP | BPF_JNE | bpf_src;
522                                         break;
523                                 case BPF_JGT:
524                                         insn->code = BPF_JMP | BPF_JLE | bpf_src;
525                                         break;
526                                 case BPF_JGE:
527                                         insn->code = BPF_JMP | BPF_JLT | bpf_src;
528                                         break;
529                                 default:
530                                         goto jmp_rest;
531                                 }
532
533                                 target = i + fp->jf + 1;
534                                 BPF_EMIT_JMP;
535                                 break;
536                         }
537 jmp_rest:
538                         /* Other jumps are mapped into two insns: Jxx and JA. */
539                         target = i + fp->jt + 1;
540                         insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
541                         BPF_EMIT_JMP;
542                         insn++;
543
544                         insn->code = BPF_JMP | BPF_JA;
545                         target = i + fp->jf + 1;
546                         BPF_EMIT_JMP;
547                         break;
548
549                 /* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
550                 case BPF_LDX | BPF_MSH | BPF_B:
551                         /* tmp = A */
552                         *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_A);
553                         /* A = BPF_R0 = *(u8 *) (skb->data + K) */
554                         *insn++ = BPF_LD_ABS(BPF_B, fp->k);
555                         /* A &= 0xf */
556                         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
557                         /* A <<= 2 */
558                         *insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
559                         /* X = A */
560                         *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
561                         /* A = tmp */
562                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
563                         break;
564
565                 /* RET_K is remaped into 2 insns. RET_A case doesn't need an
566                  * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
567                  */
568                 case BPF_RET | BPF_A:
569                 case BPF_RET | BPF_K:
570                         if (BPF_RVAL(fp->code) == BPF_K)
571                                 *insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
572                                                         0, fp->k);
573                         *insn = BPF_EXIT_INSN();
574                         break;
575
576                 /* Store to stack. */
577                 case BPF_ST:
578                 case BPF_STX:
579                         stack_off = fp->k * 4  + 4;
580                         *insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
581                                             BPF_ST ? BPF_REG_A : BPF_REG_X,
582                                             -stack_off);
583                         /* check_load_and_stores() verifies that classic BPF can
584                          * load from stack only after write, so tracking
585                          * stack_depth for ST|STX insns is enough
586                          */
587                         if (new_prog && new_prog->aux->stack_depth < stack_off)
588                                 new_prog->aux->stack_depth = stack_off;
589                         break;
590
591                 /* Load from stack. */
592                 case BPF_LD | BPF_MEM:
593                 case BPF_LDX | BPF_MEM:
594                         stack_off = fp->k * 4  + 4;
595                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
596                                             BPF_REG_A : BPF_REG_X, BPF_REG_FP,
597                                             -stack_off);
598                         break;
599
600                 /* A = K or X = K */
601                 case BPF_LD | BPF_IMM:
602                 case BPF_LDX | BPF_IMM:
603                         *insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
604                                               BPF_REG_A : BPF_REG_X, fp->k);
605                         break;
606
607                 /* X = A */
608                 case BPF_MISC | BPF_TAX:
609                         *insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
610                         break;
611
612                 /* A = X */
613                 case BPF_MISC | BPF_TXA:
614                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
615                         break;
616
617                 /* A = skb->len or X = skb->len */
618                 case BPF_LD | BPF_W | BPF_LEN:
619                 case BPF_LDX | BPF_W | BPF_LEN:
620                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
621                                             BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
622                                             offsetof(struct sk_buff, len));
623                         break;
624
625                 /* Access seccomp_data fields. */
626                 case BPF_LDX | BPF_ABS | BPF_W:
627                         /* A = *(u32 *) (ctx + K) */
628                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
629                         break;
630
631                 /* Unknown instruction. */
632                 default:
633                         goto err;
634                 }
635
636                 insn++;
637                 if (new_prog)
638                         memcpy(new_insn, tmp_insns,
639                                sizeof(*insn) * (insn - tmp_insns));
640                 new_insn += insn - tmp_insns;
641         }
642
643         if (!new_prog) {
644                 /* Only calculating new length. */
645                 *new_len = new_insn - first_insn;
646                 return 0;
647         }
648
649         pass++;
650         if (new_flen != new_insn - first_insn) {
651                 new_flen = new_insn - first_insn;
652                 if (pass > 2)
653                         goto err;
654                 goto do_pass;
655         }
656
657         kfree(addrs);
658         BUG_ON(*new_len != new_flen);
659         return 0;
660 err:
661         kfree(addrs);
662         return -EINVAL;
663 }
664
665 /* Security:
666  *
667  * As we dont want to clear mem[] array for each packet going through
668  * __bpf_prog_run(), we check that filter loaded by user never try to read
669  * a cell if not previously written, and we check all branches to be sure
670  * a malicious user doesn't try to abuse us.
671  */
672 static int check_load_and_stores(const struct sock_filter *filter, int flen)
673 {
674         u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
675         int pc, ret = 0;
676
677         BUILD_BUG_ON(BPF_MEMWORDS > 16);
678
679         masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
680         if (!masks)
681                 return -ENOMEM;
682
683         memset(masks, 0xff, flen * sizeof(*masks));
684
685         for (pc = 0; pc < flen; pc++) {
686                 memvalid &= masks[pc];
687
688                 switch (filter[pc].code) {
689                 case BPF_ST:
690                 case BPF_STX:
691                         memvalid |= (1 << filter[pc].k);
692                         break;
693                 case BPF_LD | BPF_MEM:
694                 case BPF_LDX | BPF_MEM:
695                         if (!(memvalid & (1 << filter[pc].k))) {
696                                 ret = -EINVAL;
697                                 goto error;
698                         }
699                         break;
700                 case BPF_JMP | BPF_JA:
701                         /* A jump must set masks on target */
702                         masks[pc + 1 + filter[pc].k] &= memvalid;
703                         memvalid = ~0;
704                         break;
705                 case BPF_JMP | BPF_JEQ | BPF_K:
706                 case BPF_JMP | BPF_JEQ | BPF_X:
707                 case BPF_JMP | BPF_JGE | BPF_K:
708                 case BPF_JMP | BPF_JGE | BPF_X:
709                 case BPF_JMP | BPF_JGT | BPF_K:
710                 case BPF_JMP | BPF_JGT | BPF_X:
711                 case BPF_JMP | BPF_JSET | BPF_K:
712                 case BPF_JMP | BPF_JSET | BPF_X:
713                         /* A jump must set masks on targets */
714                         masks[pc + 1 + filter[pc].jt] &= memvalid;
715                         masks[pc + 1 + filter[pc].jf] &= memvalid;
716                         memvalid = ~0;
717                         break;
718                 }
719         }
720 error:
721         kfree(masks);
722         return ret;
723 }
724
725 static bool chk_code_allowed(u16 code_to_probe)
726 {
727         static const bool codes[] = {
728                 /* 32 bit ALU operations */
729                 [BPF_ALU | BPF_ADD | BPF_K] = true,
730                 [BPF_ALU | BPF_ADD | BPF_X] = true,
731                 [BPF_ALU | BPF_SUB | BPF_K] = true,
732                 [BPF_ALU | BPF_SUB | BPF_X] = true,
733                 [BPF_ALU | BPF_MUL | BPF_K] = true,
734                 [BPF_ALU | BPF_MUL | BPF_X] = true,
735                 [BPF_ALU | BPF_DIV | BPF_K] = true,
736                 [BPF_ALU | BPF_DIV | BPF_X] = true,
737                 [BPF_ALU | BPF_MOD | BPF_K] = true,
738                 [BPF_ALU | BPF_MOD | BPF_X] = true,
739                 [BPF_ALU | BPF_AND | BPF_K] = true,
740                 [BPF_ALU | BPF_AND | BPF_X] = true,
741                 [BPF_ALU | BPF_OR | BPF_K] = true,
742                 [BPF_ALU | BPF_OR | BPF_X] = true,
743                 [BPF_ALU | BPF_XOR | BPF_K] = true,
744                 [BPF_ALU | BPF_XOR | BPF_X] = true,
745                 [BPF_ALU | BPF_LSH | BPF_K] = true,
746                 [BPF_ALU | BPF_LSH | BPF_X] = true,
747                 [BPF_ALU | BPF_RSH | BPF_K] = true,
748                 [BPF_ALU | BPF_RSH | BPF_X] = true,
749                 [BPF_ALU | BPF_NEG] = true,
750                 /* Load instructions */
751                 [BPF_LD | BPF_W | BPF_ABS] = true,
752                 [BPF_LD | BPF_H | BPF_ABS] = true,
753                 [BPF_LD | BPF_B | BPF_ABS] = true,
754                 [BPF_LD | BPF_W | BPF_LEN] = true,
755                 [BPF_LD | BPF_W | BPF_IND] = true,
756                 [BPF_LD | BPF_H | BPF_IND] = true,
757                 [BPF_LD | BPF_B | BPF_IND] = true,
758                 [BPF_LD | BPF_IMM] = true,
759                 [BPF_LD | BPF_MEM] = true,
760                 [BPF_LDX | BPF_W | BPF_LEN] = true,
761                 [BPF_LDX | BPF_B | BPF_MSH] = true,
762                 [BPF_LDX | BPF_IMM] = true,
763                 [BPF_LDX | BPF_MEM] = true,
764                 /* Store instructions */
765                 [BPF_ST] = true,
766                 [BPF_STX] = true,
767                 /* Misc instructions */
768                 [BPF_MISC | BPF_TAX] = true,
769                 [BPF_MISC | BPF_TXA] = true,
770                 /* Return instructions */
771                 [BPF_RET | BPF_K] = true,
772                 [BPF_RET | BPF_A] = true,
773                 /* Jump instructions */
774                 [BPF_JMP | BPF_JA] = true,
775                 [BPF_JMP | BPF_JEQ | BPF_K] = true,
776                 [BPF_JMP | BPF_JEQ | BPF_X] = true,
777                 [BPF_JMP | BPF_JGE | BPF_K] = true,
778                 [BPF_JMP | BPF_JGE | BPF_X] = true,
779                 [BPF_JMP | BPF_JGT | BPF_K] = true,
780                 [BPF_JMP | BPF_JGT | BPF_X] = true,
781                 [BPF_JMP | BPF_JSET | BPF_K] = true,
782                 [BPF_JMP | BPF_JSET | BPF_X] = true,
783         };
784
785         if (code_to_probe >= ARRAY_SIZE(codes))
786                 return false;
787
788         return codes[code_to_probe];
789 }
790
791 static bool bpf_check_basics_ok(const struct sock_filter *filter,
792                                 unsigned int flen)
793 {
794         if (filter == NULL)
795                 return false;
796         if (flen == 0 || flen > BPF_MAXINSNS)
797                 return false;
798
799         return true;
800 }
801
802 /**
803  *      bpf_check_classic - verify socket filter code
804  *      @filter: filter to verify
805  *      @flen: length of filter
806  *
807  * Check the user's filter code. If we let some ugly
808  * filter code slip through kaboom! The filter must contain
809  * no references or jumps that are out of range, no illegal
810  * instructions, and must end with a RET instruction.
811  *
812  * All jumps are forward as they are not signed.
813  *
814  * Returns 0 if the rule set is legal or -EINVAL if not.
815  */
816 static int bpf_check_classic(const struct sock_filter *filter,
817                              unsigned int flen)
818 {
819         bool anc_found;
820         int pc;
821
822         /* Check the filter code now */
823         for (pc = 0; pc < flen; pc++) {
824                 const struct sock_filter *ftest = &filter[pc];
825
826                 /* May we actually operate on this code? */
827                 if (!chk_code_allowed(ftest->code))
828                         return -EINVAL;
829
830                 /* Some instructions need special checks */
831                 switch (ftest->code) {
832                 case BPF_ALU | BPF_DIV | BPF_K:
833                 case BPF_ALU | BPF_MOD | BPF_K:
834                         /* Check for division by zero */
835                         if (ftest->k == 0)
836                                 return -EINVAL;
837                         break;
838                 case BPF_ALU | BPF_LSH | BPF_K:
839                 case BPF_ALU | BPF_RSH | BPF_K:
840                         if (ftest->k >= 32)
841                                 return -EINVAL;
842                         break;
843                 case BPF_LD | BPF_MEM:
844                 case BPF_LDX | BPF_MEM:
845                 case BPF_ST:
846                 case BPF_STX:
847                         /* Check for invalid memory addresses */
848                         if (ftest->k >= BPF_MEMWORDS)
849                                 return -EINVAL;
850                         break;
851                 case BPF_JMP | BPF_JA:
852                         /* Note, the large ftest->k might cause loops.
853                          * Compare this with conditional jumps below,
854                          * where offsets are limited. --ANK (981016)
855                          */
856                         if (ftest->k >= (unsigned int)(flen - pc - 1))
857                                 return -EINVAL;
858                         break;
859                 case BPF_JMP | BPF_JEQ | BPF_K:
860                 case BPF_JMP | BPF_JEQ | BPF_X:
861                 case BPF_JMP | BPF_JGE | BPF_K:
862                 case BPF_JMP | BPF_JGE | BPF_X:
863                 case BPF_JMP | BPF_JGT | BPF_K:
864                 case BPF_JMP | BPF_JGT | BPF_X:
865                 case BPF_JMP | BPF_JSET | BPF_K:
866                 case BPF_JMP | BPF_JSET | BPF_X:
867                         /* Both conditionals must be safe */
868                         if (pc + ftest->jt + 1 >= flen ||
869                             pc + ftest->jf + 1 >= flen)
870                                 return -EINVAL;
871                         break;
872                 case BPF_LD | BPF_W | BPF_ABS:
873                 case BPF_LD | BPF_H | BPF_ABS:
874                 case BPF_LD | BPF_B | BPF_ABS:
875                         anc_found = false;
876                         if (bpf_anc_helper(ftest) & BPF_ANC)
877                                 anc_found = true;
878                         /* Ancillary operation unknown or unsupported */
879                         if (anc_found == false && ftest->k >= SKF_AD_OFF)
880                                 return -EINVAL;
881                 }
882         }
883
884         /* Last instruction must be a RET code */
885         switch (filter[flen - 1].code) {
886         case BPF_RET | BPF_K:
887         case BPF_RET | BPF_A:
888                 return check_load_and_stores(filter, flen);
889         }
890
891         return -EINVAL;
892 }
893
894 static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
895                                       const struct sock_fprog *fprog)
896 {
897         unsigned int fsize = bpf_classic_proglen(fprog);
898         struct sock_fprog_kern *fkprog;
899
900         fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
901         if (!fp->orig_prog)
902                 return -ENOMEM;
903
904         fkprog = fp->orig_prog;
905         fkprog->len = fprog->len;
906
907         fkprog->filter = kmemdup(fp->insns, fsize,
908                                  GFP_KERNEL | __GFP_NOWARN);
909         if (!fkprog->filter) {
910                 kfree(fp->orig_prog);
911                 return -ENOMEM;
912         }
913
914         return 0;
915 }
916
917 static void bpf_release_orig_filter(struct bpf_prog *fp)
918 {
919         struct sock_fprog_kern *fprog = fp->orig_prog;
920
921         if (fprog) {
922                 kfree(fprog->filter);
923                 kfree(fprog);
924         }
925 }
926
927 static void __bpf_prog_release(struct bpf_prog *prog)
928 {
929         if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
930                 bpf_prog_put(prog);
931         } else {
932                 bpf_release_orig_filter(prog);
933                 bpf_prog_free(prog);
934         }
935 }
936
937 static void __sk_filter_release(struct sk_filter *fp)
938 {
939         __bpf_prog_release(fp->prog);
940         kfree(fp);
941 }
942
943 /**
944  *      sk_filter_release_rcu - Release a socket filter by rcu_head
945  *      @rcu: rcu_head that contains the sk_filter to free
946  */
947 static void sk_filter_release_rcu(struct rcu_head *rcu)
948 {
949         struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
950
951         __sk_filter_release(fp);
952 }
953
954 /**
955  *      sk_filter_release - release a socket filter
956  *      @fp: filter to remove
957  *
958  *      Remove a filter from a socket and release its resources.
959  */
960 static void sk_filter_release(struct sk_filter *fp)
961 {
962         if (refcount_dec_and_test(&fp->refcnt))
963                 call_rcu(&fp->rcu, sk_filter_release_rcu);
964 }
965
966 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
967 {
968         u32 filter_size = bpf_prog_size(fp->prog->len);
969
970         atomic_sub(filter_size, &sk->sk_omem_alloc);
971         sk_filter_release(fp);
972 }
973
974 /* try to charge the socket memory if there is space available
975  * return true on success
976  */
977 static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
978 {
979         u32 filter_size = bpf_prog_size(fp->prog->len);
980
981         /* same check as in sock_kmalloc() */
982         if (filter_size <= sysctl_optmem_max &&
983             atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
984                 atomic_add(filter_size, &sk->sk_omem_alloc);
985                 return true;
986         }
987         return false;
988 }
989
990 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
991 {
992         bool ret = __sk_filter_charge(sk, fp);
993         if (ret)
994                 refcount_inc(&fp->refcnt);
995         return ret;
996 }
997
998 static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
999 {
1000         struct sock_filter *old_prog;
1001         struct bpf_prog *old_fp;
1002         int err, new_len, old_len = fp->len;
1003
1004         /* We are free to overwrite insns et al right here as it
1005          * won't be used at this point in time anymore internally
1006          * after the migration to the internal BPF instruction
1007          * representation.
1008          */
1009         BUILD_BUG_ON(sizeof(struct sock_filter) !=
1010                      sizeof(struct bpf_insn));
1011
1012         /* Conversion cannot happen on overlapping memory areas,
1013          * so we need to keep the user BPF around until the 2nd
1014          * pass. At this time, the user BPF is stored in fp->insns.
1015          */
1016         old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
1017                            GFP_KERNEL | __GFP_NOWARN);
1018         if (!old_prog) {
1019                 err = -ENOMEM;
1020                 goto out_err;
1021         }
1022
1023         /* 1st pass: calculate the new program length. */
1024         err = bpf_convert_filter(old_prog, old_len, NULL, &new_len);
1025         if (err)
1026                 goto out_err_free;
1027
1028         /* Expand fp for appending the new filter representation. */
1029         old_fp = fp;
1030         fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1031         if (!fp) {
1032                 /* The old_fp is still around in case we couldn't
1033                  * allocate new memory, so uncharge on that one.
1034                  */
1035                 fp = old_fp;
1036                 err = -ENOMEM;
1037                 goto out_err_free;
1038         }
1039
1040         fp->len = new_len;
1041
1042         /* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1043         err = bpf_convert_filter(old_prog, old_len, fp, &new_len);
1044         if (err)
1045                 /* 2nd bpf_convert_filter() can fail only if it fails
1046                  * to allocate memory, remapping must succeed. Note,
1047                  * that at this time old_fp has already been released
1048                  * by krealloc().
1049                  */
1050                 goto out_err_free;
1051
1052         /* We are guaranteed to never error here with cBPF to eBPF
1053          * transitions, since there's no issue with type compatibility
1054          * checks on program arrays.
1055          */
1056         fp = bpf_prog_select_runtime(fp, &err);
1057
1058         kfree(old_prog);
1059         return fp;
1060
1061 out_err_free:
1062         kfree(old_prog);
1063 out_err:
1064         __bpf_prog_release(fp);
1065         return ERR_PTR(err);
1066 }
1067
1068 static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
1069                                            bpf_aux_classic_check_t trans)
1070 {
1071         int err;
1072
1073         fp->bpf_func = NULL;
1074         fp->jited = 0;
1075
1076         err = bpf_check_classic(fp->insns, fp->len);
1077         if (err) {
1078                 __bpf_prog_release(fp);
1079                 return ERR_PTR(err);
1080         }
1081
1082         /* There might be additional checks and transformations
1083          * needed on classic filters, f.e. in case of seccomp.
1084          */
1085         if (trans) {
1086                 err = trans(fp->insns, fp->len);
1087                 if (err) {
1088                         __bpf_prog_release(fp);
1089                         return ERR_PTR(err);
1090                 }
1091         }
1092
1093         /* Probe if we can JIT compile the filter and if so, do
1094          * the compilation of the filter.
1095          */
1096         bpf_jit_compile(fp);
1097
1098         /* JIT compiler couldn't process this filter, so do the
1099          * internal BPF translation for the optimized interpreter.
1100          */
1101         if (!fp->jited)
1102                 fp = bpf_migrate_filter(fp);
1103
1104         return fp;
1105 }
1106
1107 /**
1108  *      bpf_prog_create - create an unattached filter
1109  *      @pfp: the unattached filter that is created
1110  *      @fprog: the filter program
1111  *
1112  * Create a filter independent of any socket. We first run some
1113  * sanity checks on it to make sure it does not explode on us later.
1114  * If an error occurs or there is insufficient memory for the filter
1115  * a negative errno code is returned. On success the return is zero.
1116  */
1117 int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1118 {
1119         unsigned int fsize = bpf_classic_proglen(fprog);
1120         struct bpf_prog *fp;
1121
1122         /* Make sure new filter is there and in the right amounts. */
1123         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1124                 return -EINVAL;
1125
1126         fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1127         if (!fp)
1128                 return -ENOMEM;
1129
1130         memcpy(fp->insns, fprog->filter, fsize);
1131
1132         fp->len = fprog->len;
1133         /* Since unattached filters are not copied back to user
1134          * space through sk_get_filter(), we do not need to hold
1135          * a copy here, and can spare us the work.
1136          */
1137         fp->orig_prog = NULL;
1138
1139         /* bpf_prepare_filter() already takes care of freeing
1140          * memory in case something goes wrong.
1141          */
1142         fp = bpf_prepare_filter(fp, NULL);
1143         if (IS_ERR(fp))
1144                 return PTR_ERR(fp);
1145
1146         *pfp = fp;
1147         return 0;
1148 }
1149 EXPORT_SYMBOL_GPL(bpf_prog_create);
1150
1151 /**
1152  *      bpf_prog_create_from_user - create an unattached filter from user buffer
1153  *      @pfp: the unattached filter that is created
1154  *      @fprog: the filter program
1155  *      @trans: post-classic verifier transformation handler
1156  *      @save_orig: save classic BPF program
1157  *
1158  * This function effectively does the same as bpf_prog_create(), only
1159  * that it builds up its insns buffer from user space provided buffer.
1160  * It also allows for passing a bpf_aux_classic_check_t handler.
1161  */
1162 int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1163                               bpf_aux_classic_check_t trans, bool save_orig)
1164 {
1165         unsigned int fsize = bpf_classic_proglen(fprog);
1166         struct bpf_prog *fp;
1167         int err;
1168
1169         /* Make sure new filter is there and in the right amounts. */
1170         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1171                 return -EINVAL;
1172
1173         fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1174         if (!fp)
1175                 return -ENOMEM;
1176
1177         if (copy_from_user(fp->insns, fprog->filter, fsize)) {
1178                 __bpf_prog_free(fp);
1179                 return -EFAULT;
1180         }
1181
1182         fp->len = fprog->len;
1183         fp->orig_prog = NULL;
1184
1185         if (save_orig) {
1186                 err = bpf_prog_store_orig_filter(fp, fprog);
1187                 if (err) {
1188                         __bpf_prog_free(fp);
1189                         return -ENOMEM;
1190                 }
1191         }
1192
1193         /* bpf_prepare_filter() already takes care of freeing
1194          * memory in case something goes wrong.
1195          */
1196         fp = bpf_prepare_filter(fp, trans);
1197         if (IS_ERR(fp))
1198                 return PTR_ERR(fp);
1199
1200         *pfp = fp;
1201         return 0;
1202 }
1203 EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1204
1205 void bpf_prog_destroy(struct bpf_prog *fp)
1206 {
1207         __bpf_prog_release(fp);
1208 }
1209 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1210
1211 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1212 {
1213         struct sk_filter *fp, *old_fp;
1214
1215         fp = kmalloc(sizeof(*fp), GFP_KERNEL);
1216         if (!fp)
1217                 return -ENOMEM;
1218
1219         fp->prog = prog;
1220
1221         if (!__sk_filter_charge(sk, fp)) {
1222                 kfree(fp);
1223                 return -ENOMEM;
1224         }
1225         refcount_set(&fp->refcnt, 1);
1226
1227         old_fp = rcu_dereference_protected(sk->sk_filter,
1228                                            lockdep_sock_is_held(sk));
1229         rcu_assign_pointer(sk->sk_filter, fp);
1230
1231         if (old_fp)
1232                 sk_filter_uncharge(sk, old_fp);
1233
1234         return 0;
1235 }
1236
1237 static int __reuseport_attach_prog(struct bpf_prog *prog, struct sock *sk)
1238 {
1239         struct bpf_prog *old_prog;
1240         int err;
1241
1242         if (bpf_prog_size(prog->len) > sysctl_optmem_max)
1243                 return -ENOMEM;
1244
1245         if (sk_unhashed(sk) && sk->sk_reuseport) {
1246                 err = reuseport_alloc(sk);
1247                 if (err)
1248                         return err;
1249         } else if (!rcu_access_pointer(sk->sk_reuseport_cb)) {
1250                 /* The socket wasn't bound with SO_REUSEPORT */
1251                 return -EINVAL;
1252         }
1253
1254         old_prog = reuseport_attach_prog(sk, prog);
1255         if (old_prog)
1256                 bpf_prog_destroy(old_prog);
1257
1258         return 0;
1259 }
1260
1261 static
1262 struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
1263 {
1264         unsigned int fsize = bpf_classic_proglen(fprog);
1265         struct bpf_prog *prog;
1266         int err;
1267
1268         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1269                 return ERR_PTR(-EPERM);
1270
1271         /* Make sure new filter is there and in the right amounts. */
1272         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1273                 return ERR_PTR(-EINVAL);
1274
1275         prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1276         if (!prog)
1277                 return ERR_PTR(-ENOMEM);
1278
1279         if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1280                 __bpf_prog_free(prog);
1281                 return ERR_PTR(-EFAULT);
1282         }
1283
1284         prog->len = fprog->len;
1285
1286         err = bpf_prog_store_orig_filter(prog, fprog);
1287         if (err) {
1288                 __bpf_prog_free(prog);
1289                 return ERR_PTR(-ENOMEM);
1290         }
1291
1292         /* bpf_prepare_filter() already takes care of freeing
1293          * memory in case something goes wrong.
1294          */
1295         return bpf_prepare_filter(prog, NULL);
1296 }
1297
1298 /**
1299  *      sk_attach_filter - attach a socket filter
1300  *      @fprog: the filter program
1301  *      @sk: the socket to use
1302  *
1303  * Attach the user's filter code. We first run some sanity checks on
1304  * it to make sure it does not explode on us later. If an error
1305  * occurs or there is insufficient memory for the filter a negative
1306  * errno code is returned. On success the return is zero.
1307  */
1308 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1309 {
1310         struct bpf_prog *prog = __get_filter(fprog, sk);
1311         int err;
1312
1313         if (IS_ERR(prog))
1314                 return PTR_ERR(prog);
1315
1316         err = __sk_attach_prog(prog, sk);
1317         if (err < 0) {
1318                 __bpf_prog_release(prog);
1319                 return err;
1320         }
1321
1322         return 0;
1323 }
1324 EXPORT_SYMBOL_GPL(sk_attach_filter);
1325
1326 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1327 {
1328         struct bpf_prog *prog = __get_filter(fprog, sk);
1329         int err;
1330
1331         if (IS_ERR(prog))
1332                 return PTR_ERR(prog);
1333
1334         err = __reuseport_attach_prog(prog, sk);
1335         if (err < 0) {
1336                 __bpf_prog_release(prog);
1337                 return err;
1338         }
1339
1340         return 0;
1341 }
1342
1343 static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
1344 {
1345         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1346                 return ERR_PTR(-EPERM);
1347
1348         return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1349 }
1350
1351 int sk_attach_bpf(u32 ufd, struct sock *sk)
1352 {
1353         struct bpf_prog *prog = __get_bpf(ufd, sk);
1354         int err;
1355
1356         if (IS_ERR(prog))
1357                 return PTR_ERR(prog);
1358
1359         err = __sk_attach_prog(prog, sk);
1360         if (err < 0) {
1361                 bpf_prog_put(prog);
1362                 return err;
1363         }
1364
1365         return 0;
1366 }
1367
1368 int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
1369 {
1370         struct bpf_prog *prog = __get_bpf(ufd, sk);
1371         int err;
1372
1373         if (IS_ERR(prog))
1374                 return PTR_ERR(prog);
1375
1376         err = __reuseport_attach_prog(prog, sk);
1377         if (err < 0) {
1378                 bpf_prog_put(prog);
1379                 return err;
1380         }
1381
1382         return 0;
1383 }
1384
1385 struct bpf_scratchpad {
1386         union {
1387                 __be32 diff[MAX_BPF_STACK / sizeof(__be32)];
1388                 u8     buff[MAX_BPF_STACK];
1389         };
1390 };
1391
1392 static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp);
1393
1394 static inline int __bpf_try_make_writable(struct sk_buff *skb,
1395                                           unsigned int write_len)
1396 {
1397         return skb_ensure_writable(skb, write_len);
1398 }
1399
1400 static inline int bpf_try_make_writable(struct sk_buff *skb,
1401                                         unsigned int write_len)
1402 {
1403         int err = __bpf_try_make_writable(skb, write_len);
1404
1405         bpf_compute_data_end(skb);
1406         return err;
1407 }
1408
1409 static int bpf_try_make_head_writable(struct sk_buff *skb)
1410 {
1411         return bpf_try_make_writable(skb, skb_headlen(skb));
1412 }
1413
1414 static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
1415 {
1416         if (skb_at_tc_ingress(skb))
1417                 skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1418 }
1419
1420 static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
1421 {
1422         if (skb_at_tc_ingress(skb))
1423                 skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1424 }
1425
1426 BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
1427            const void *, from, u32, len, u64, flags)
1428 {
1429         void *ptr;
1430
1431         if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1432                 return -EINVAL;
1433         if (unlikely(offset > 0xffff))
1434                 return -EFAULT;
1435         if (unlikely(bpf_try_make_writable(skb, offset + len)))
1436                 return -EFAULT;
1437
1438         ptr = skb->data + offset;
1439         if (flags & BPF_F_RECOMPUTE_CSUM)
1440                 __skb_postpull_rcsum(skb, ptr, len, offset);
1441
1442         memcpy(ptr, from, len);
1443
1444         if (flags & BPF_F_RECOMPUTE_CSUM)
1445                 __skb_postpush_rcsum(skb, ptr, len, offset);
1446         if (flags & BPF_F_INVALIDATE_HASH)
1447                 skb_clear_hash(skb);
1448
1449         return 0;
1450 }
1451
1452 static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1453         .func           = bpf_skb_store_bytes,
1454         .gpl_only       = false,
1455         .ret_type       = RET_INTEGER,
1456         .arg1_type      = ARG_PTR_TO_CTX,
1457         .arg2_type      = ARG_ANYTHING,
1458         .arg3_type      = ARG_PTR_TO_MEM,
1459         .arg4_type      = ARG_CONST_SIZE,
1460         .arg5_type      = ARG_ANYTHING,
1461 };
1462
1463 BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
1464            void *, to, u32, len)
1465 {
1466         void *ptr;
1467
1468         if (unlikely(offset > 0xffff))
1469                 goto err_clear;
1470
1471         ptr = skb_header_pointer(skb, offset, len, to);
1472         if (unlikely(!ptr))
1473                 goto err_clear;
1474         if (ptr != to)
1475                 memcpy(to, ptr, len);
1476
1477         return 0;
1478 err_clear:
1479         memset(to, 0, len);
1480         return -EFAULT;
1481 }
1482
1483 static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1484         .func           = bpf_skb_load_bytes,
1485         .gpl_only       = false,
1486         .ret_type       = RET_INTEGER,
1487         .arg1_type      = ARG_PTR_TO_CTX,
1488         .arg2_type      = ARG_ANYTHING,
1489         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1490         .arg4_type      = ARG_CONST_SIZE,
1491 };
1492
1493 BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
1494 {
1495         /* Idea is the following: should the needed direct read/write
1496          * test fail during runtime, we can pull in more data and redo
1497          * again, since implicitly, we invalidate previous checks here.
1498          *
1499          * Or, since we know how much we need to make read/writeable,
1500          * this can be done once at the program beginning for direct
1501          * access case. By this we overcome limitations of only current
1502          * headroom being accessible.
1503          */
1504         return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
1505 }
1506
1507 static const struct bpf_func_proto bpf_skb_pull_data_proto = {
1508         .func           = bpf_skb_pull_data,
1509         .gpl_only       = false,
1510         .ret_type       = RET_INTEGER,
1511         .arg1_type      = ARG_PTR_TO_CTX,
1512         .arg2_type      = ARG_ANYTHING,
1513 };
1514
1515 BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
1516            u64, from, u64, to, u64, flags)
1517 {
1518         __sum16 *ptr;
1519
1520         if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
1521                 return -EINVAL;
1522         if (unlikely(offset > 0xffff || offset & 1))
1523                 return -EFAULT;
1524         if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1525                 return -EFAULT;
1526
1527         ptr = (__sum16 *)(skb->data + offset);
1528         switch (flags & BPF_F_HDR_FIELD_MASK) {
1529         case 0:
1530                 if (unlikely(from != 0))
1531                         return -EINVAL;
1532
1533                 csum_replace_by_diff(ptr, to);
1534                 break;
1535         case 2:
1536                 csum_replace2(ptr, from, to);
1537                 break;
1538         case 4:
1539                 csum_replace4(ptr, from, to);
1540                 break;
1541         default:
1542                 return -EINVAL;
1543         }
1544
1545         return 0;
1546 }
1547
1548 static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1549         .func           = bpf_l3_csum_replace,
1550         .gpl_only       = false,
1551         .ret_type       = RET_INTEGER,
1552         .arg1_type      = ARG_PTR_TO_CTX,
1553         .arg2_type      = ARG_ANYTHING,
1554         .arg3_type      = ARG_ANYTHING,
1555         .arg4_type      = ARG_ANYTHING,
1556         .arg5_type      = ARG_ANYTHING,
1557 };
1558
1559 BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
1560            u64, from, u64, to, u64, flags)
1561 {
1562         bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1563         bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1564         bool do_mforce = flags & BPF_F_MARK_ENFORCE;
1565         __sum16 *ptr;
1566
1567         if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
1568                                BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK)))
1569                 return -EINVAL;
1570         if (unlikely(offset > 0xffff || offset & 1))
1571                 return -EFAULT;
1572         if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1573                 return -EFAULT;
1574
1575         ptr = (__sum16 *)(skb->data + offset);
1576         if (is_mmzero && !do_mforce && !*ptr)
1577                 return 0;
1578
1579         switch (flags & BPF_F_HDR_FIELD_MASK) {
1580         case 0:
1581                 if (unlikely(from != 0))
1582                         return -EINVAL;
1583
1584                 inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
1585                 break;
1586         case 2:
1587                 inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
1588                 break;
1589         case 4:
1590                 inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
1591                 break;
1592         default:
1593                 return -EINVAL;
1594         }
1595
1596         if (is_mmzero && !*ptr)
1597                 *ptr = CSUM_MANGLED_0;
1598         return 0;
1599 }
1600
1601 static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1602         .func           = bpf_l4_csum_replace,
1603         .gpl_only       = false,
1604         .ret_type       = RET_INTEGER,
1605         .arg1_type      = ARG_PTR_TO_CTX,
1606         .arg2_type      = ARG_ANYTHING,
1607         .arg3_type      = ARG_ANYTHING,
1608         .arg4_type      = ARG_ANYTHING,
1609         .arg5_type      = ARG_ANYTHING,
1610 };
1611
1612 BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
1613            __be32 *, to, u32, to_size, __wsum, seed)
1614 {
1615         struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1616         u32 diff_size = from_size + to_size;
1617         int i, j = 0;
1618
1619         /* This is quite flexible, some examples:
1620          *
1621          * from_size == 0, to_size > 0,  seed := csum --> pushing data
1622          * from_size > 0,  to_size == 0, seed := csum --> pulling data
1623          * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
1624          *
1625          * Even for diffing, from_size and to_size don't need to be equal.
1626          */
1627         if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) ||
1628                      diff_size > sizeof(sp->diff)))
1629                 return -EINVAL;
1630
1631         for (i = 0; i < from_size / sizeof(__be32); i++, j++)
1632                 sp->diff[j] = ~from[i];
1633         for (i = 0; i <   to_size / sizeof(__be32); i++, j++)
1634                 sp->diff[j] = to[i];
1635
1636         return csum_partial(sp->diff, diff_size, seed);
1637 }
1638
1639 static const struct bpf_func_proto bpf_csum_diff_proto = {
1640         .func           = bpf_csum_diff,
1641         .gpl_only       = false,
1642         .pkt_access     = true,
1643         .ret_type       = RET_INTEGER,
1644         .arg1_type      = ARG_PTR_TO_MEM,
1645         .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
1646         .arg3_type      = ARG_PTR_TO_MEM,
1647         .arg4_type      = ARG_CONST_SIZE_OR_ZERO,
1648         .arg5_type      = ARG_ANYTHING,
1649 };
1650
1651 BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
1652 {
1653         /* The interface is to be used in combination with bpf_csum_diff()
1654          * for direct packet writes. csum rotation for alignment as well
1655          * as emulating csum_sub() can be done from the eBPF program.
1656          */
1657         if (skb->ip_summed == CHECKSUM_COMPLETE)
1658                 return (skb->csum = csum_add(skb->csum, csum));
1659
1660         return -ENOTSUPP;
1661 }
1662
1663 static const struct bpf_func_proto bpf_csum_update_proto = {
1664         .func           = bpf_csum_update,
1665         .gpl_only       = false,
1666         .ret_type       = RET_INTEGER,
1667         .arg1_type      = ARG_PTR_TO_CTX,
1668         .arg2_type      = ARG_ANYTHING,
1669 };
1670
1671 static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
1672 {
1673         return dev_forward_skb(dev, skb);
1674 }
1675
1676 static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
1677                                       struct sk_buff *skb)
1678 {
1679         int ret = ____dev_forward_skb(dev, skb);
1680
1681         if (likely(!ret)) {
1682                 skb->dev = dev;
1683                 ret = netif_rx(skb);
1684         }
1685
1686         return ret;
1687 }
1688
1689 static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
1690 {
1691         int ret;
1692
1693         if (unlikely(__this_cpu_read(xmit_recursion) > XMIT_RECURSION_LIMIT)) {
1694                 net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
1695                 kfree_skb(skb);
1696                 return -ENETDOWN;
1697         }
1698
1699         skb->dev = dev;
1700
1701         __this_cpu_inc(xmit_recursion);
1702         ret = dev_queue_xmit(skb);
1703         __this_cpu_dec(xmit_recursion);
1704
1705         return ret;
1706 }
1707
1708 static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
1709                                  u32 flags)
1710 {
1711         /* skb->mac_len is not set on normal egress */
1712         unsigned int mlen = skb->network_header - skb->mac_header;
1713
1714         __skb_pull(skb, mlen);
1715
1716         /* At ingress, the mac header has already been pulled once.
1717          * At egress, skb_pospull_rcsum has to be done in case that
1718          * the skb is originated from ingress (i.e. a forwarded skb)
1719          * to ensure that rcsum starts at net header.
1720          */
1721         if (!skb_at_tc_ingress(skb))
1722                 skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
1723         skb_pop_mac_header(skb);
1724         skb_reset_mac_len(skb);
1725         return flags & BPF_F_INGRESS ?
1726                __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
1727 }
1728
1729 static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
1730                                  u32 flags)
1731 {
1732         /* Verify that a link layer header is carried */
1733         if (unlikely(skb->mac_header >= skb->network_header)) {
1734                 kfree_skb(skb);
1735                 return -ERANGE;
1736         }
1737
1738         bpf_push_mac_rcsum(skb);
1739         return flags & BPF_F_INGRESS ?
1740                __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
1741 }
1742
1743 static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
1744                           u32 flags)
1745 {
1746         if (dev_is_mac_header_xmit(dev))
1747                 return __bpf_redirect_common(skb, dev, flags);
1748         else
1749                 return __bpf_redirect_no_mac(skb, dev, flags);
1750 }
1751
1752 BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
1753 {
1754         struct net_device *dev;
1755         struct sk_buff *clone;
1756         int ret;
1757
1758         if (unlikely(flags & ~(BPF_F_INGRESS)))
1759                 return -EINVAL;
1760
1761         dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
1762         if (unlikely(!dev))
1763                 return -EINVAL;
1764
1765         clone = skb_clone(skb, GFP_ATOMIC);
1766         if (unlikely(!clone))
1767                 return -ENOMEM;
1768
1769         /* For direct write, we need to keep the invariant that the skbs
1770          * we're dealing with need to be uncloned. Should uncloning fail
1771          * here, we need to free the just generated clone to unclone once
1772          * again.
1773          */
1774         ret = bpf_try_make_head_writable(skb);
1775         if (unlikely(ret)) {
1776                 kfree_skb(clone);
1777                 return -ENOMEM;
1778         }
1779
1780         return __bpf_redirect(clone, dev, flags);
1781 }
1782
1783 static const struct bpf_func_proto bpf_clone_redirect_proto = {
1784         .func           = bpf_clone_redirect,
1785         .gpl_only       = false,
1786         .ret_type       = RET_INTEGER,
1787         .arg1_type      = ARG_PTR_TO_CTX,
1788         .arg2_type      = ARG_ANYTHING,
1789         .arg3_type      = ARG_ANYTHING,
1790 };
1791
1792 struct redirect_info {
1793         u32 ifindex;
1794         u32 flags;
1795         struct bpf_map *map;
1796         struct bpf_map *map_to_flush;
1797 };
1798
1799 static DEFINE_PER_CPU(struct redirect_info, redirect_info);
1800
1801 BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
1802 {
1803         struct redirect_info *ri = this_cpu_ptr(&redirect_info);
1804
1805         if (unlikely(flags & ~(BPF_F_INGRESS)))
1806                 return TC_ACT_SHOT;
1807
1808         ri->ifindex = ifindex;
1809         ri->flags = flags;
1810         ri->map = NULL;
1811
1812         return TC_ACT_REDIRECT;
1813 }
1814
1815 int skb_do_redirect(struct sk_buff *skb)
1816 {
1817         struct redirect_info *ri = this_cpu_ptr(&redirect_info);
1818         struct net_device *dev;
1819
1820         dev = dev_get_by_index_rcu(dev_net(skb->dev), ri->ifindex);
1821         ri->ifindex = 0;
1822         if (unlikely(!dev)) {
1823                 kfree_skb(skb);
1824                 return -EINVAL;
1825         }
1826
1827         return __bpf_redirect(skb, dev, ri->flags);
1828 }
1829
1830 static const struct bpf_func_proto bpf_redirect_proto = {
1831         .func           = bpf_redirect,
1832         .gpl_only       = false,
1833         .ret_type       = RET_INTEGER,
1834         .arg1_type      = ARG_ANYTHING,
1835         .arg2_type      = ARG_ANYTHING,
1836 };
1837
1838 BPF_CALL_3(bpf_redirect_map, struct bpf_map *, map, u32, ifindex, u64, flags)
1839 {
1840         struct redirect_info *ri = this_cpu_ptr(&redirect_info);
1841
1842         if (unlikely(flags))
1843                 return XDP_ABORTED;
1844
1845         ri->ifindex = ifindex;
1846         ri->flags = flags;
1847         ri->map = map;
1848
1849         return XDP_REDIRECT;
1850 }
1851
1852 static const struct bpf_func_proto bpf_redirect_map_proto = {
1853         .func           = bpf_redirect_map,
1854         .gpl_only       = false,
1855         .ret_type       = RET_INTEGER,
1856         .arg1_type      = ARG_CONST_MAP_PTR,
1857         .arg2_type      = ARG_ANYTHING,
1858         .arg3_type      = ARG_ANYTHING,
1859 };
1860
1861 BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
1862 {
1863         return task_get_classid(skb);
1864 }
1865
1866 static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
1867         .func           = bpf_get_cgroup_classid,
1868         .gpl_only       = false,
1869         .ret_type       = RET_INTEGER,
1870         .arg1_type      = ARG_PTR_TO_CTX,
1871 };
1872
1873 BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
1874 {
1875         return dst_tclassid(skb);
1876 }
1877
1878 static const struct bpf_func_proto bpf_get_route_realm_proto = {
1879         .func           = bpf_get_route_realm,
1880         .gpl_only       = false,
1881         .ret_type       = RET_INTEGER,
1882         .arg1_type      = ARG_PTR_TO_CTX,
1883 };
1884
1885 BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
1886 {
1887         /* If skb_clear_hash() was called due to mangling, we can
1888          * trigger SW recalculation here. Later access to hash
1889          * can then use the inline skb->hash via context directly
1890          * instead of calling this helper again.
1891          */
1892         return skb_get_hash(skb);
1893 }
1894
1895 static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
1896         .func           = bpf_get_hash_recalc,
1897         .gpl_only       = false,
1898         .ret_type       = RET_INTEGER,
1899         .arg1_type      = ARG_PTR_TO_CTX,
1900 };
1901
1902 BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
1903 {
1904         /* After all direct packet write, this can be used once for
1905          * triggering a lazy recalc on next skb_get_hash() invocation.
1906          */
1907         skb_clear_hash(skb);
1908         return 0;
1909 }
1910
1911 static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
1912         .func           = bpf_set_hash_invalid,
1913         .gpl_only       = false,
1914         .ret_type       = RET_INTEGER,
1915         .arg1_type      = ARG_PTR_TO_CTX,
1916 };
1917
1918 BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
1919 {
1920         /* Set user specified hash as L4(+), so that it gets returned
1921          * on skb_get_hash() call unless BPF prog later on triggers a
1922          * skb_clear_hash().
1923          */
1924         __skb_set_sw_hash(skb, hash, true);
1925         return 0;
1926 }
1927
1928 static const struct bpf_func_proto bpf_set_hash_proto = {
1929         .func           = bpf_set_hash,
1930         .gpl_only       = false,
1931         .ret_type       = RET_INTEGER,
1932         .arg1_type      = ARG_PTR_TO_CTX,
1933         .arg2_type      = ARG_ANYTHING,
1934 };
1935
1936 BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
1937            u16, vlan_tci)
1938 {
1939         int ret;
1940
1941         if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
1942                      vlan_proto != htons(ETH_P_8021AD)))
1943                 vlan_proto = htons(ETH_P_8021Q);
1944
1945         bpf_push_mac_rcsum(skb);
1946         ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
1947         bpf_pull_mac_rcsum(skb);
1948
1949         bpf_compute_data_end(skb);
1950         return ret;
1951 }
1952
1953 const struct bpf_func_proto bpf_skb_vlan_push_proto = {
1954         .func           = bpf_skb_vlan_push,
1955         .gpl_only       = false,
1956         .ret_type       = RET_INTEGER,
1957         .arg1_type      = ARG_PTR_TO_CTX,
1958         .arg2_type      = ARG_ANYTHING,
1959         .arg3_type      = ARG_ANYTHING,
1960 };
1961 EXPORT_SYMBOL_GPL(bpf_skb_vlan_push_proto);
1962
1963 BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
1964 {
1965         int ret;
1966
1967         bpf_push_mac_rcsum(skb);
1968         ret = skb_vlan_pop(skb);
1969         bpf_pull_mac_rcsum(skb);
1970
1971         bpf_compute_data_end(skb);
1972         return ret;
1973 }
1974
1975 const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
1976         .func           = bpf_skb_vlan_pop,
1977         .gpl_only       = false,
1978         .ret_type       = RET_INTEGER,
1979         .arg1_type      = ARG_PTR_TO_CTX,
1980 };
1981 EXPORT_SYMBOL_GPL(bpf_skb_vlan_pop_proto);
1982
1983 static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
1984 {
1985         /* Caller already did skb_cow() with len as headroom,
1986          * so no need to do it here.
1987          */
1988         skb_push(skb, len);
1989         memmove(skb->data, skb->data + len, off);
1990         memset(skb->data + off, 0, len);
1991
1992         /* No skb_postpush_rcsum(skb, skb->data + off, len)
1993          * needed here as it does not change the skb->csum
1994          * result for checksum complete when summing over
1995          * zeroed blocks.
1996          */
1997         return 0;
1998 }
1999
2000 static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
2001 {
2002         /* skb_ensure_writable() is not needed here, as we're
2003          * already working on an uncloned skb.
2004          */
2005         if (unlikely(!pskb_may_pull(skb, off + len)))
2006                 return -ENOMEM;
2007
2008         skb_postpull_rcsum(skb, skb->data + off, len);
2009         memmove(skb->data + len, skb->data, off);
2010         __skb_pull(skb, len);
2011
2012         return 0;
2013 }
2014
2015 static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
2016 {
2017         bool trans_same = skb->transport_header == skb->network_header;
2018         int ret;
2019
2020         /* There's no need for __skb_push()/__skb_pull() pair to
2021          * get to the start of the mac header as we're guaranteed
2022          * to always start from here under eBPF.
2023          */
2024         ret = bpf_skb_generic_push(skb, off, len);
2025         if (likely(!ret)) {
2026                 skb->mac_header -= len;
2027                 skb->network_header -= len;
2028                 if (trans_same)
2029                         skb->transport_header = skb->network_header;
2030         }
2031
2032         return ret;
2033 }
2034
2035 static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
2036 {
2037         bool trans_same = skb->transport_header == skb->network_header;
2038         int ret;
2039
2040         /* Same here, __skb_push()/__skb_pull() pair not needed. */
2041         ret = bpf_skb_generic_pop(skb, off, len);
2042         if (likely(!ret)) {
2043                 skb->mac_header += len;
2044                 skb->network_header += len;
2045                 if (trans_same)
2046                         skb->transport_header = skb->network_header;
2047         }
2048
2049         return ret;
2050 }
2051
2052 static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
2053 {
2054         const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2055         u32 off = skb_mac_header_len(skb);
2056         int ret;
2057
2058         ret = skb_cow(skb, len_diff);
2059         if (unlikely(ret < 0))
2060                 return ret;
2061
2062         ret = bpf_skb_net_hdr_push(skb, off, len_diff);
2063         if (unlikely(ret < 0))
2064                 return ret;
2065
2066         if (skb_is_gso(skb)) {
2067                 /* SKB_GSO_TCPV4 needs to be changed into
2068                  * SKB_GSO_TCPV6.
2069                  */
2070                 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
2071                         skb_shinfo(skb)->gso_type &= ~SKB_GSO_TCPV4;
2072                         skb_shinfo(skb)->gso_type |=  SKB_GSO_TCPV6;
2073                 }
2074
2075                 /* Due to IPv6 header, MSS needs to be downgraded. */
2076                 skb_shinfo(skb)->gso_size -= len_diff;
2077                 /* Header must be checked, and gso_segs recomputed. */
2078                 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2079                 skb_shinfo(skb)->gso_segs = 0;
2080         }
2081
2082         skb->protocol = htons(ETH_P_IPV6);
2083         skb_clear_hash(skb);
2084
2085         return 0;
2086 }
2087
2088 static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
2089 {
2090         const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2091         u32 off = skb_mac_header_len(skb);
2092         int ret;
2093
2094         ret = skb_unclone(skb, GFP_ATOMIC);
2095         if (unlikely(ret < 0))
2096                 return ret;
2097
2098         ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
2099         if (unlikely(ret < 0))
2100                 return ret;
2101
2102         if (skb_is_gso(skb)) {
2103                 /* SKB_GSO_TCPV6 needs to be changed into
2104                  * SKB_GSO_TCPV4.
2105                  */
2106                 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) {
2107                         skb_shinfo(skb)->gso_type &= ~SKB_GSO_TCPV6;
2108                         skb_shinfo(skb)->gso_type |=  SKB_GSO_TCPV4;
2109                 }
2110
2111                 /* Due to IPv4 header, MSS can be upgraded. */
2112                 skb_shinfo(skb)->gso_size += len_diff;
2113                 /* Header must be checked, and gso_segs recomputed. */
2114                 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2115                 skb_shinfo(skb)->gso_segs = 0;
2116         }
2117
2118         skb->protocol = htons(ETH_P_IP);
2119         skb_clear_hash(skb);
2120
2121         return 0;
2122 }
2123
2124 static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
2125 {
2126         __be16 from_proto = skb->protocol;
2127
2128         if (from_proto == htons(ETH_P_IP) &&
2129               to_proto == htons(ETH_P_IPV6))
2130                 return bpf_skb_proto_4_to_6(skb);
2131
2132         if (from_proto == htons(ETH_P_IPV6) &&
2133               to_proto == htons(ETH_P_IP))
2134                 return bpf_skb_proto_6_to_4(skb);
2135
2136         return -ENOTSUPP;
2137 }
2138
2139 BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
2140            u64, flags)
2141 {
2142         int ret;
2143
2144         if (unlikely(flags))
2145                 return -EINVAL;
2146
2147         /* General idea is that this helper does the basic groundwork
2148          * needed for changing the protocol, and eBPF program fills the
2149          * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
2150          * and other helpers, rather than passing a raw buffer here.
2151          *
2152          * The rationale is to keep this minimal and without a need to
2153          * deal with raw packet data. F.e. even if we would pass buffers
2154          * here, the program still needs to call the bpf_lX_csum_replace()
2155          * helpers anyway. Plus, this way we keep also separation of
2156          * concerns, since f.e. bpf_skb_store_bytes() should only take
2157          * care of stores.
2158          *
2159          * Currently, additional options and extension header space are
2160          * not supported, but flags register is reserved so we can adapt
2161          * that. For offloads, we mark packet as dodgy, so that headers
2162          * need to be verified first.
2163          */
2164         ret = bpf_skb_proto_xlat(skb, proto);
2165         bpf_compute_data_end(skb);
2166         return ret;
2167 }
2168
2169 static const struct bpf_func_proto bpf_skb_change_proto_proto = {
2170         .func           = bpf_skb_change_proto,
2171         .gpl_only       = false,
2172         .ret_type       = RET_INTEGER,
2173         .arg1_type      = ARG_PTR_TO_CTX,
2174         .arg2_type      = ARG_ANYTHING,
2175         .arg3_type      = ARG_ANYTHING,
2176 };
2177
2178 BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
2179 {
2180         /* We only allow a restricted subset to be changed for now. */
2181         if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
2182                      !skb_pkt_type_ok(pkt_type)))
2183                 return -EINVAL;
2184
2185         skb->pkt_type = pkt_type;
2186         return 0;
2187 }
2188
2189 static const struct bpf_func_proto bpf_skb_change_type_proto = {
2190         .func           = bpf_skb_change_type,
2191         .gpl_only       = false,
2192         .ret_type       = RET_INTEGER,
2193         .arg1_type      = ARG_PTR_TO_CTX,
2194         .arg2_type      = ARG_ANYTHING,
2195 };
2196
2197 static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
2198 {
2199         switch (skb->protocol) {
2200         case htons(ETH_P_IP):
2201                 return sizeof(struct iphdr);
2202         case htons(ETH_P_IPV6):
2203                 return sizeof(struct ipv6hdr);
2204         default:
2205                 return ~0U;
2206         }
2207 }
2208
2209 static int bpf_skb_net_grow(struct sk_buff *skb, u32 len_diff)
2210 {
2211         u32 off = skb_mac_header_len(skb) + bpf_skb_net_base_len(skb);
2212         int ret;
2213
2214         ret = skb_cow(skb, len_diff);
2215         if (unlikely(ret < 0))
2216                 return ret;
2217
2218         ret = bpf_skb_net_hdr_push(skb, off, len_diff);
2219         if (unlikely(ret < 0))
2220                 return ret;
2221
2222         if (skb_is_gso(skb)) {
2223                 /* Due to header grow, MSS needs to be downgraded. */
2224                 skb_shinfo(skb)->gso_size -= len_diff;
2225                 /* Header must be checked, and gso_segs recomputed. */
2226                 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2227                 skb_shinfo(skb)->gso_segs = 0;
2228         }
2229
2230         return 0;
2231 }
2232
2233 static int bpf_skb_net_shrink(struct sk_buff *skb, u32 len_diff)
2234 {
2235         u32 off = skb_mac_header_len(skb) + bpf_skb_net_base_len(skb);
2236         int ret;
2237
2238         ret = skb_unclone(skb, GFP_ATOMIC);
2239         if (unlikely(ret < 0))
2240                 return ret;
2241
2242         ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
2243         if (unlikely(ret < 0))
2244                 return ret;
2245
2246         if (skb_is_gso(skb)) {
2247                 /* Due to header shrink, MSS can be upgraded. */
2248                 skb_shinfo(skb)->gso_size += len_diff;
2249                 /* Header must be checked, and gso_segs recomputed. */
2250                 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2251                 skb_shinfo(skb)->gso_segs = 0;
2252         }
2253
2254         return 0;
2255 }
2256
2257 static u32 __bpf_skb_max_len(const struct sk_buff *skb)
2258 {
2259         return skb->dev->mtu + skb->dev->hard_header_len;
2260 }
2261
2262 static int bpf_skb_adjust_net(struct sk_buff *skb, s32 len_diff)
2263 {
2264         bool trans_same = skb->transport_header == skb->network_header;
2265         u32 len_cur, len_diff_abs = abs(len_diff);
2266         u32 len_min = bpf_skb_net_base_len(skb);
2267         u32 len_max = __bpf_skb_max_len(skb);
2268         __be16 proto = skb->protocol;
2269         bool shrink = len_diff < 0;
2270         int ret;
2271
2272         if (unlikely(len_diff_abs > 0xfffU))
2273                 return -EFAULT;
2274         if (unlikely(proto != htons(ETH_P_IP) &&
2275                      proto != htons(ETH_P_IPV6)))
2276                 return -ENOTSUPP;
2277
2278         len_cur = skb->len - skb_network_offset(skb);
2279         if (skb_transport_header_was_set(skb) && !trans_same)
2280                 len_cur = skb_network_header_len(skb);
2281         if ((shrink && (len_diff_abs >= len_cur ||
2282                         len_cur - len_diff_abs < len_min)) ||
2283             (!shrink && (skb->len + len_diff_abs > len_max &&
2284                          !skb_is_gso(skb))))
2285                 return -ENOTSUPP;
2286
2287         ret = shrink ? bpf_skb_net_shrink(skb, len_diff_abs) :
2288                        bpf_skb_net_grow(skb, len_diff_abs);
2289
2290         bpf_compute_data_end(skb);
2291         return ret;
2292 }
2293
2294 BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
2295            u32, mode, u64, flags)
2296 {
2297         if (unlikely(flags))
2298                 return -EINVAL;
2299         if (likely(mode == BPF_ADJ_ROOM_NET))
2300                 return bpf_skb_adjust_net(skb, len_diff);
2301
2302         return -ENOTSUPP;
2303 }
2304
2305 static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
2306         .func           = bpf_skb_adjust_room,
2307         .gpl_only       = false,
2308         .ret_type       = RET_INTEGER,
2309         .arg1_type      = ARG_PTR_TO_CTX,
2310         .arg2_type      = ARG_ANYTHING,
2311         .arg3_type      = ARG_ANYTHING,
2312         .arg4_type      = ARG_ANYTHING,
2313 };
2314
2315 static u32 __bpf_skb_min_len(const struct sk_buff *skb)
2316 {
2317         u32 min_len = skb_network_offset(skb);
2318
2319         if (skb_transport_header_was_set(skb))
2320                 min_len = skb_transport_offset(skb);
2321         if (skb->ip_summed == CHECKSUM_PARTIAL)
2322                 min_len = skb_checksum_start_offset(skb) +
2323                           skb->csum_offset + sizeof(__sum16);
2324         return min_len;
2325 }
2326
2327 static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
2328 {
2329         unsigned int old_len = skb->len;
2330         int ret;
2331
2332         ret = __skb_grow_rcsum(skb, new_len);
2333         if (!ret)
2334                 memset(skb->data + old_len, 0, new_len - old_len);
2335         return ret;
2336 }
2337
2338 static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
2339 {
2340         return __skb_trim_rcsum(skb, new_len);
2341 }
2342
2343 BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
2344            u64, flags)
2345 {
2346         u32 max_len = __bpf_skb_max_len(skb);
2347         u32 min_len = __bpf_skb_min_len(skb);
2348         int ret;
2349
2350         if (unlikely(flags || new_len > max_len || new_len < min_len))
2351                 return -EINVAL;
2352         if (skb->encapsulation)
2353                 return -ENOTSUPP;
2354
2355         /* The basic idea of this helper is that it's performing the
2356          * needed work to either grow or trim an skb, and eBPF program
2357          * rewrites the rest via helpers like bpf_skb_store_bytes(),
2358          * bpf_lX_csum_replace() and others rather than passing a raw
2359          * buffer here. This one is a slow path helper and intended
2360          * for replies with control messages.
2361          *
2362          * Like in bpf_skb_change_proto(), we want to keep this rather
2363          * minimal and without protocol specifics so that we are able
2364          * to separate concerns as in bpf_skb_store_bytes() should only
2365          * be the one responsible for writing buffers.
2366          *
2367          * It's really expected to be a slow path operation here for
2368          * control message replies, so we're implicitly linearizing,
2369          * uncloning and drop offloads from the skb by this.
2370          */
2371         ret = __bpf_try_make_writable(skb, skb->len);
2372         if (!ret) {
2373                 if (new_len > skb->len)
2374                         ret = bpf_skb_grow_rcsum(skb, new_len);
2375                 else if (new_len < skb->len)
2376                         ret = bpf_skb_trim_rcsum(skb, new_len);
2377                 if (!ret && skb_is_gso(skb))
2378                         skb_gso_reset(skb);
2379         }
2380
2381         bpf_compute_data_end(skb);
2382         return ret;
2383 }
2384
2385 static const struct bpf_func_proto bpf_skb_change_tail_proto = {
2386         .func           = bpf_skb_change_tail,
2387         .gpl_only       = false,
2388         .ret_type       = RET_INTEGER,
2389         .arg1_type      = ARG_PTR_TO_CTX,
2390         .arg2_type      = ARG_ANYTHING,
2391         .arg3_type      = ARG_ANYTHING,
2392 };
2393
2394 BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
2395            u64, flags)
2396 {
2397         u32 max_len = __bpf_skb_max_len(skb);
2398         u32 new_len = skb->len + head_room;
2399         int ret;
2400
2401         if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
2402                      new_len < skb->len))
2403                 return -EINVAL;
2404
2405         ret = skb_cow(skb, head_room);
2406         if (likely(!ret)) {
2407                 /* Idea for this helper is that we currently only
2408                  * allow to expand on mac header. This means that
2409                  * skb->protocol network header, etc, stay as is.
2410                  * Compared to bpf_skb_change_tail(), we're more
2411                  * flexible due to not needing to linearize or
2412                  * reset GSO. Intention for this helper is to be
2413                  * used by an L3 skb that needs to push mac header
2414                  * for redirection into L2 device.
2415                  */
2416                 __skb_push(skb, head_room);
2417                 memset(skb->data, 0, head_room);
2418                 skb_reset_mac_header(skb);
2419         }
2420
2421         bpf_compute_data_end(skb);
2422         return 0;
2423 }
2424
2425 static const struct bpf_func_proto bpf_skb_change_head_proto = {
2426         .func           = bpf_skb_change_head,
2427         .gpl_only       = false,
2428         .ret_type       = RET_INTEGER,
2429         .arg1_type      = ARG_PTR_TO_CTX,
2430         .arg2_type      = ARG_ANYTHING,
2431         .arg3_type      = ARG_ANYTHING,
2432 };
2433
2434 BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
2435 {
2436         void *data = xdp->data + offset;
2437
2438         if (unlikely(data < xdp->data_hard_start ||
2439                      data > xdp->data_end - ETH_HLEN))
2440                 return -EINVAL;
2441
2442         xdp->data = data;
2443
2444         return 0;
2445 }
2446
2447 static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
2448         .func           = bpf_xdp_adjust_head,
2449         .gpl_only       = false,
2450         .ret_type       = RET_INTEGER,
2451         .arg1_type      = ARG_PTR_TO_CTX,
2452         .arg2_type      = ARG_ANYTHING,
2453 };
2454
2455 static int __bpf_tx_xdp(struct net_device *dev,
2456                         struct bpf_map *map,
2457                         struct xdp_buff *xdp,
2458                         u32 index)
2459 {
2460         int err;
2461
2462         if (!dev->netdev_ops->ndo_xdp_xmit) {
2463                 bpf_warn_invalid_xdp_redirect(dev->ifindex);
2464                 return -EOPNOTSUPP;
2465         }
2466
2467         err = dev->netdev_ops->ndo_xdp_xmit(dev, xdp);
2468         if (err)
2469                 return err;
2470
2471         if (map)
2472                 __dev_map_insert_ctx(map, index);
2473         else
2474                 dev->netdev_ops->ndo_xdp_flush(dev);
2475
2476         return err;
2477 }
2478
2479 void xdp_do_flush_map(void)
2480 {
2481         struct redirect_info *ri = this_cpu_ptr(&redirect_info);
2482         struct bpf_map *map = ri->map_to_flush;
2483
2484         ri->map = NULL;
2485         ri->map_to_flush = NULL;
2486
2487         if (map)
2488                 __dev_map_flush(map);
2489 }
2490 EXPORT_SYMBOL_GPL(xdp_do_flush_map);
2491
2492 int xdp_do_redirect_map(struct net_device *dev, struct xdp_buff *xdp,
2493                         struct bpf_prog *xdp_prog)
2494 {
2495         struct redirect_info *ri = this_cpu_ptr(&redirect_info);
2496         struct bpf_map *map = ri->map;
2497         u32 index = ri->ifindex;
2498         struct net_device *fwd;
2499         int err = -EINVAL;
2500
2501         ri->ifindex = 0;
2502         ri->map = NULL;
2503
2504         fwd = __dev_map_lookup_elem(map, index);
2505         if (!fwd)
2506                 goto out;
2507
2508         if (ri->map_to_flush && (ri->map_to_flush != map))
2509                 xdp_do_flush_map();
2510
2511         err = __bpf_tx_xdp(fwd, map, xdp, index);
2512         if (likely(!err))
2513                 ri->map_to_flush = map;
2514
2515 out:
2516         trace_xdp_redirect(dev, fwd, xdp_prog, XDP_REDIRECT);
2517         return err;
2518 }
2519
2520 int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
2521                     struct bpf_prog *xdp_prog)
2522 {
2523         struct redirect_info *ri = this_cpu_ptr(&redirect_info);
2524         struct net_device *fwd;
2525         u32 index = ri->ifindex;
2526
2527         if (ri->map)
2528                 return xdp_do_redirect_map(dev, xdp, xdp_prog);
2529
2530         fwd = dev_get_by_index_rcu(dev_net(dev), index);
2531         ri->ifindex = 0;
2532         ri->map = NULL;
2533         if (unlikely(!fwd)) {
2534                 bpf_warn_invalid_xdp_redirect(index);
2535                 return -EINVAL;
2536         }
2537
2538         trace_xdp_redirect(dev, fwd, xdp_prog, XDP_REDIRECT);
2539
2540         return __bpf_tx_xdp(fwd, NULL, xdp, 0);
2541 }
2542 EXPORT_SYMBOL_GPL(xdp_do_redirect);
2543
2544 int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb)
2545 {
2546         struct redirect_info *ri = this_cpu_ptr(&redirect_info);
2547         unsigned int len;
2548         u32 index = ri->ifindex;
2549
2550         dev = dev_get_by_index_rcu(dev_net(dev), index);
2551         ri->ifindex = 0;
2552         if (unlikely(!dev)) {
2553                 bpf_warn_invalid_xdp_redirect(index);
2554                 goto err;
2555         }
2556
2557         if (unlikely(!(dev->flags & IFF_UP)))
2558                 goto err;
2559
2560         len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
2561         if (skb->len > len)
2562                 goto err;
2563
2564         skb->dev = dev;
2565         return 0;
2566 err:
2567         return -EINVAL;
2568 }
2569 EXPORT_SYMBOL_GPL(xdp_do_generic_redirect);
2570
2571 BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
2572 {
2573         struct redirect_info *ri = this_cpu_ptr(&redirect_info);
2574
2575         if (unlikely(flags))
2576                 return XDP_ABORTED;
2577
2578         ri->ifindex = ifindex;
2579         ri->flags = flags;
2580         return XDP_REDIRECT;
2581 }
2582
2583 static const struct bpf_func_proto bpf_xdp_redirect_proto = {
2584         .func           = bpf_xdp_redirect,
2585         .gpl_only       = false,
2586         .ret_type       = RET_INTEGER,
2587         .arg1_type      = ARG_ANYTHING,
2588         .arg2_type      = ARG_ANYTHING,
2589 };
2590
2591 bool bpf_helper_changes_pkt_data(void *func)
2592 {
2593         if (func == bpf_skb_vlan_push ||
2594             func == bpf_skb_vlan_pop ||
2595             func == bpf_skb_store_bytes ||
2596             func == bpf_skb_change_proto ||
2597             func == bpf_skb_change_head ||
2598             func == bpf_skb_change_tail ||
2599             func == bpf_skb_adjust_room ||
2600             func == bpf_skb_pull_data ||
2601             func == bpf_clone_redirect ||
2602             func == bpf_l3_csum_replace ||
2603             func == bpf_l4_csum_replace ||
2604             func == bpf_xdp_adjust_head)
2605                 return true;
2606
2607         return false;
2608 }
2609
2610 static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
2611                                   unsigned long off, unsigned long len)
2612 {
2613         void *ptr = skb_header_pointer(skb, off, len, dst_buff);
2614
2615         if (unlikely(!ptr))
2616                 return len;
2617         if (ptr != dst_buff)
2618                 memcpy(dst_buff, ptr, len);
2619
2620         return 0;
2621 }
2622
2623 BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
2624            u64, flags, void *, meta, u64, meta_size)
2625 {
2626         u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
2627
2628         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
2629                 return -EINVAL;
2630         if (unlikely(skb_size > skb->len))
2631                 return -EFAULT;
2632
2633         return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
2634                                 bpf_skb_copy);
2635 }
2636
2637 static const struct bpf_func_proto bpf_skb_event_output_proto = {
2638         .func           = bpf_skb_event_output,
2639         .gpl_only       = true,
2640         .ret_type       = RET_INTEGER,
2641         .arg1_type      = ARG_PTR_TO_CTX,
2642         .arg2_type      = ARG_CONST_MAP_PTR,
2643         .arg3_type      = ARG_ANYTHING,
2644         .arg4_type      = ARG_PTR_TO_MEM,
2645         .arg5_type      = ARG_CONST_SIZE,
2646 };
2647
2648 static unsigned short bpf_tunnel_key_af(u64 flags)
2649 {
2650         return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
2651 }
2652
2653 BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
2654            u32, size, u64, flags)
2655 {
2656         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
2657         u8 compat[sizeof(struct bpf_tunnel_key)];
2658         void *to_orig = to;
2659         int err;
2660
2661         if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) {
2662                 err = -EINVAL;
2663                 goto err_clear;
2664         }
2665         if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
2666                 err = -EPROTO;
2667                 goto err_clear;
2668         }
2669         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
2670                 err = -EINVAL;
2671                 switch (size) {
2672                 case offsetof(struct bpf_tunnel_key, tunnel_label):
2673                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
2674                         goto set_compat;
2675                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
2676                         /* Fixup deprecated structure layouts here, so we have
2677                          * a common path later on.
2678                          */
2679                         if (ip_tunnel_info_af(info) != AF_INET)
2680                                 goto err_clear;
2681 set_compat:
2682                         to = (struct bpf_tunnel_key *)compat;
2683                         break;
2684                 default:
2685                         goto err_clear;
2686                 }
2687         }
2688
2689         to->tunnel_id = be64_to_cpu(info->key.tun_id);
2690         to->tunnel_tos = info->key.tos;
2691         to->tunnel_ttl = info->key.ttl;
2692
2693         if (flags & BPF_F_TUNINFO_IPV6) {
2694                 memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
2695                        sizeof(to->remote_ipv6));
2696                 to->tunnel_label = be32_to_cpu(info->key.label);
2697         } else {
2698                 to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
2699         }
2700
2701         if (unlikely(size != sizeof(struct bpf_tunnel_key)))
2702                 memcpy(to_orig, to, size);
2703
2704         return 0;
2705 err_clear:
2706         memset(to_orig, 0, size);
2707         return err;
2708 }
2709
2710 static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
2711         .func           = bpf_skb_get_tunnel_key,
2712         .gpl_only       = false,
2713         .ret_type       = RET_INTEGER,
2714         .arg1_type      = ARG_PTR_TO_CTX,
2715         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
2716         .arg3_type      = ARG_CONST_SIZE,
2717         .arg4_type      = ARG_ANYTHING,
2718 };
2719
2720 BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
2721 {
2722         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
2723         int err;
2724
2725         if (unlikely(!info ||
2726                      !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
2727                 err = -ENOENT;
2728                 goto err_clear;
2729         }
2730         if (unlikely(size < info->options_len)) {
2731                 err = -ENOMEM;
2732                 goto err_clear;
2733         }
2734
2735         ip_tunnel_info_opts_get(to, info);
2736         if (size > info->options_len)
2737                 memset(to + info->options_len, 0, size - info->options_len);
2738
2739         return info->options_len;
2740 err_clear:
2741         memset(to, 0, size);
2742         return err;
2743 }
2744
2745 static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
2746         .func           = bpf_skb_get_tunnel_opt,
2747         .gpl_only       = false,
2748         .ret_type       = RET_INTEGER,
2749         .arg1_type      = ARG_PTR_TO_CTX,
2750         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
2751         .arg3_type      = ARG_CONST_SIZE,
2752 };
2753
2754 static struct metadata_dst __percpu *md_dst;
2755
2756 BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
2757            const struct bpf_tunnel_key *, from, u32, size, u64, flags)
2758 {
2759         struct metadata_dst *md = this_cpu_ptr(md_dst);
2760         u8 compat[sizeof(struct bpf_tunnel_key)];
2761         struct ip_tunnel_info *info;
2762
2763         if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
2764                                BPF_F_DONT_FRAGMENT)))
2765                 return -EINVAL;
2766         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
2767                 switch (size) {
2768                 case offsetof(struct bpf_tunnel_key, tunnel_label):
2769                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
2770                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
2771                         /* Fixup deprecated structure layouts here, so we have
2772                          * a common path later on.
2773                          */
2774                         memcpy(compat, from, size);
2775                         memset(compat + size, 0, sizeof(compat) - size);
2776                         from = (const struct bpf_tunnel_key *) compat;
2777                         break;
2778                 default:
2779                         return -EINVAL;
2780                 }
2781         }
2782         if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
2783                      from->tunnel_ext))
2784                 return -EINVAL;
2785
2786         skb_dst_drop(skb);
2787         dst_hold((struct dst_entry *) md);
2788         skb_dst_set(skb, (struct dst_entry *) md);
2789
2790         info = &md->u.tun_info;
2791         info->mode = IP_TUNNEL_INFO_TX;
2792
2793         info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
2794         if (flags & BPF_F_DONT_FRAGMENT)
2795                 info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;
2796
2797         info->key.tun_id = cpu_to_be64(from->tunnel_id);
2798         info->key.tos = from->tunnel_tos;
2799         info->key.ttl = from->tunnel_ttl;
2800
2801         if (flags & BPF_F_TUNINFO_IPV6) {
2802                 info->mode |= IP_TUNNEL_INFO_IPV6;
2803                 memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
2804                        sizeof(from->remote_ipv6));
2805                 info->key.label = cpu_to_be32(from->tunnel_label) &
2806                                   IPV6_FLOWLABEL_MASK;
2807         } else {
2808                 info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
2809                 if (flags & BPF_F_ZERO_CSUM_TX)
2810                         info->key.tun_flags &= ~TUNNEL_CSUM;
2811         }
2812
2813         return 0;
2814 }
2815
2816 static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
2817         .func           = bpf_skb_set_tunnel_key,
2818         .gpl_only       = false,
2819         .ret_type       = RET_INTEGER,
2820         .arg1_type      = ARG_PTR_TO_CTX,
2821         .arg2_type      = ARG_PTR_TO_MEM,
2822         .arg3_type      = ARG_CONST_SIZE,
2823         .arg4_type      = ARG_ANYTHING,
2824 };
2825
2826 BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
2827            const u8 *, from, u32, size)
2828 {
2829         struct ip_tunnel_info *info = skb_tunnel_info(skb);
2830         const struct metadata_dst *md = this_cpu_ptr(md_dst);
2831
2832         if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
2833                 return -EINVAL;
2834         if (unlikely(size > IP_TUNNEL_OPTS_MAX))
2835                 return -ENOMEM;
2836
2837         ip_tunnel_info_opts_set(info, from, size);
2838
2839         return 0;
2840 }
2841
2842 static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
2843         .func           = bpf_skb_set_tunnel_opt,
2844         .gpl_only       = false,
2845         .ret_type       = RET_INTEGER,
2846         .arg1_type      = ARG_PTR_TO_CTX,
2847         .arg2_type      = ARG_PTR_TO_MEM,
2848         .arg3_type      = ARG_CONST_SIZE,
2849 };
2850
2851 static const struct bpf_func_proto *
2852 bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
2853 {
2854         if (!md_dst) {
2855                 /* Race is not possible, since it's called from verifier
2856                  * that is holding verifier mutex.
2857                  */
2858                 md_dst = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
2859                                                    METADATA_IP_TUNNEL,
2860                                                    GFP_KERNEL);
2861                 if (!md_dst)
2862                         return NULL;
2863         }
2864
2865         switch (which) {
2866         case BPF_FUNC_skb_set_tunnel_key:
2867                 return &bpf_skb_set_tunnel_key_proto;
2868         case BPF_FUNC_skb_set_tunnel_opt:
2869                 return &bpf_skb_set_tunnel_opt_proto;
2870         default:
2871                 return NULL;
2872         }
2873 }
2874
2875 BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
2876            u32, idx)
2877 {
2878         struct bpf_array *array = container_of(map, struct bpf_array, map);
2879         struct cgroup *cgrp;
2880         struct sock *sk;
2881
2882         sk = skb_to_full_sk(skb);
2883         if (!sk || !sk_fullsock(sk))
2884                 return -ENOENT;
2885         if (unlikely(idx >= array->map.max_entries))
2886                 return -E2BIG;
2887
2888         cgrp = READ_ONCE(array->ptrs[idx]);
2889         if (unlikely(!cgrp))
2890                 return -EAGAIN;
2891
2892         return sk_under_cgroup_hierarchy(sk, cgrp);
2893 }
2894
2895 static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
2896         .func           = bpf_skb_under_cgroup,
2897         .gpl_only       = false,
2898         .ret_type       = RET_INTEGER,
2899         .arg1_type      = ARG_PTR_TO_CTX,
2900         .arg2_type      = ARG_CONST_MAP_PTR,
2901         .arg3_type      = ARG_ANYTHING,
2902 };
2903
2904 static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff,
2905                                   unsigned long off, unsigned long len)
2906 {
2907         memcpy(dst_buff, src_buff + off, len);
2908         return 0;
2909 }
2910
2911 BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
2912            u64, flags, void *, meta, u64, meta_size)
2913 {
2914         u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
2915
2916         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
2917                 return -EINVAL;
2918         if (unlikely(xdp_size > (unsigned long)(xdp->data_end - xdp->data)))
2919                 return -EFAULT;
2920
2921         return bpf_event_output(map, flags, meta, meta_size, xdp->data,
2922                                 xdp_size, bpf_xdp_copy);
2923 }
2924
2925 static const struct bpf_func_proto bpf_xdp_event_output_proto = {
2926         .func           = bpf_xdp_event_output,
2927         .gpl_only       = true,
2928         .ret_type       = RET_INTEGER,
2929         .arg1_type      = ARG_PTR_TO_CTX,
2930         .arg2_type      = ARG_CONST_MAP_PTR,
2931         .arg3_type      = ARG_ANYTHING,
2932         .arg4_type      = ARG_PTR_TO_MEM,
2933         .arg5_type      = ARG_CONST_SIZE,
2934 };
2935
2936 BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
2937 {
2938         return skb->sk ? sock_gen_cookie(skb->sk) : 0;
2939 }
2940
2941 static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
2942         .func           = bpf_get_socket_cookie,
2943         .gpl_only       = false,
2944         .ret_type       = RET_INTEGER,
2945         .arg1_type      = ARG_PTR_TO_CTX,
2946 };
2947
2948 BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
2949 {
2950         struct sock *sk = sk_to_full_sk(skb->sk);
2951         kuid_t kuid;
2952
2953         if (!sk || !sk_fullsock(sk))
2954                 return overflowuid;
2955         kuid = sock_net_uid(sock_net(sk), sk);
2956         return from_kuid_munged(sock_net(sk)->user_ns, kuid);
2957 }
2958
2959 static const struct bpf_func_proto bpf_get_socket_uid_proto = {
2960         .func           = bpf_get_socket_uid,
2961         .gpl_only       = false,
2962         .ret_type       = RET_INTEGER,
2963         .arg1_type      = ARG_PTR_TO_CTX,
2964 };
2965
2966 BPF_CALL_5(bpf_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
2967            int, level, int, optname, char *, optval, int, optlen)
2968 {
2969         struct sock *sk = bpf_sock->sk;
2970         int ret = 0;
2971         int val;
2972
2973         if (!sk_fullsock(sk))
2974                 return -EINVAL;
2975
2976         if (level == SOL_SOCKET) {
2977                 if (optlen != sizeof(int))
2978                         return -EINVAL;
2979                 val = *((int *)optval);
2980
2981                 /* Only some socketops are supported */
2982                 switch (optname) {
2983                 case SO_RCVBUF:
2984                         sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
2985                         sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);
2986                         break;
2987                 case SO_SNDBUF:
2988                         sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
2989                         sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
2990                         break;
2991                 case SO_MAX_PACING_RATE:
2992                         sk->sk_max_pacing_rate = val;
2993                         sk->sk_pacing_rate = min(sk->sk_pacing_rate,
2994                                                  sk->sk_max_pacing_rate);
2995                         break;
2996                 case SO_PRIORITY:
2997                         sk->sk_priority = val;
2998                         break;
2999                 case SO_RCVLOWAT:
3000                         if (val < 0)
3001                                 val = INT_MAX;
3002                         sk->sk_rcvlowat = val ? : 1;
3003                         break;
3004                 case SO_MARK:
3005                         sk->sk_mark = val;
3006                         break;
3007                 default:
3008                         ret = -EINVAL;
3009                 }
3010 #ifdef CONFIG_INET
3011         } else if (level == SOL_TCP &&
3012                    sk->sk_prot->setsockopt == tcp_setsockopt) {
3013                 if (optname == TCP_CONGESTION) {
3014                         char name[TCP_CA_NAME_MAX];
3015
3016                         strncpy(name, optval, min_t(long, optlen,
3017                                                     TCP_CA_NAME_MAX-1));
3018                         name[TCP_CA_NAME_MAX-1] = 0;
3019                         ret = tcp_set_congestion_control(sk, name, false);
3020                         if (!ret && bpf_sock->op > BPF_SOCK_OPS_NEEDS_ECN)
3021                                 /* replacing an existing ca */
3022                                 tcp_reinit_congestion_control(sk,
3023                                         inet_csk(sk)->icsk_ca_ops);
3024                 } else {
3025                         struct tcp_sock *tp = tcp_sk(sk);
3026
3027                         if (optlen != sizeof(int))
3028                                 return -EINVAL;
3029
3030                         val = *((int *)optval);
3031                         /* Only some options are supported */
3032                         switch (optname) {
3033                         case TCP_BPF_IW:
3034                                 if (val <= 0 || tp->data_segs_out > 0)
3035                                         ret = -EINVAL;
3036                                 else
3037                                         tp->snd_cwnd = val;
3038                                 break;
3039                         case TCP_BPF_SNDCWND_CLAMP:
3040                                 if (val <= 0) {
3041                                         ret = -EINVAL;
3042                                 } else {
3043                                         tp->snd_cwnd_clamp = val;
3044                                         tp->snd_ssthresh = val;
3045                                 }
3046                                 break;
3047                         default:
3048                                 ret = -EINVAL;
3049                         }
3050                 }
3051                 ret = -EINVAL;
3052 #endif
3053         } else {
3054                 ret = -EINVAL;
3055         }
3056         return ret;
3057 }
3058
3059 static const struct bpf_func_proto bpf_setsockopt_proto = {
3060         .func           = bpf_setsockopt,
3061         .gpl_only       = true,
3062         .ret_type       = RET_INTEGER,
3063         .arg1_type      = ARG_PTR_TO_CTX,
3064         .arg2_type      = ARG_ANYTHING,
3065         .arg3_type      = ARG_ANYTHING,
3066         .arg4_type      = ARG_PTR_TO_MEM,
3067         .arg5_type      = ARG_CONST_SIZE,
3068 };
3069
3070 static const struct bpf_func_proto *
3071 bpf_base_func_proto(enum bpf_func_id func_id)
3072 {
3073         switch (func_id) {
3074         case BPF_FUNC_map_lookup_elem:
3075                 return &bpf_map_lookup_elem_proto;
3076         case BPF_FUNC_map_update_elem:
3077                 return &bpf_map_update_elem_proto;
3078         case BPF_FUNC_map_delete_elem:
3079                 return &bpf_map_delete_elem_proto;
3080         case BPF_FUNC_get_prandom_u32:
3081                 return &bpf_get_prandom_u32_proto;
3082         case BPF_FUNC_get_smp_processor_id:
3083                 return &bpf_get_raw_smp_processor_id_proto;
3084         case BPF_FUNC_get_numa_node_id:
3085                 return &bpf_get_numa_node_id_proto;
3086         case BPF_FUNC_tail_call:
3087                 return &bpf_tail_call_proto;
3088         case BPF_FUNC_ktime_get_ns:
3089                 return &bpf_ktime_get_ns_proto;
3090         case BPF_FUNC_trace_printk:
3091                 if (capable(CAP_SYS_ADMIN))
3092                         return bpf_get_trace_printk_proto();
3093         default:
3094                 return NULL;
3095         }
3096 }
3097
3098 static const struct bpf_func_proto *
3099 sk_filter_func_proto(enum bpf_func_id func_id)
3100 {
3101         switch (func_id) {
3102         case BPF_FUNC_skb_load_bytes:
3103                 return &bpf_skb_load_bytes_proto;
3104         case BPF_FUNC_get_socket_cookie:
3105                 return &bpf_get_socket_cookie_proto;
3106         case BPF_FUNC_get_socket_uid:
3107                 return &bpf_get_socket_uid_proto;
3108         default:
3109                 return bpf_base_func_proto(func_id);
3110         }
3111 }
3112
3113 static const struct bpf_func_proto *
3114 tc_cls_act_func_proto(enum bpf_func_id func_id)
3115 {
3116         switch (func_id) {
3117         case BPF_FUNC_skb_store_bytes:
3118                 return &bpf_skb_store_bytes_proto;
3119         case BPF_FUNC_skb_load_bytes:
3120                 return &bpf_skb_load_bytes_proto;
3121         case BPF_FUNC_skb_pull_data:
3122                 return &bpf_skb_pull_data_proto;
3123         case BPF_FUNC_csum_diff:
3124                 return &bpf_csum_diff_proto;
3125         case BPF_FUNC_csum_update:
3126                 return &bpf_csum_update_proto;
3127         case BPF_FUNC_l3_csum_replace:
3128                 return &bpf_l3_csum_replace_proto;
3129         case BPF_FUNC_l4_csum_replace:
3130                 return &bpf_l4_csum_replace_proto;
3131         case BPF_FUNC_clone_redirect:
3132                 return &bpf_clone_redirect_proto;
3133         case BPF_FUNC_get_cgroup_classid:
3134                 return &bpf_get_cgroup_classid_proto;
3135         case BPF_FUNC_skb_vlan_push:
3136                 return &bpf_skb_vlan_push_proto;
3137         case BPF_FUNC_skb_vlan_pop:
3138                 return &bpf_skb_vlan_pop_proto;
3139         case BPF_FUNC_skb_change_proto:
3140                 return &bpf_skb_change_proto_proto;
3141         case BPF_FUNC_skb_change_type:
3142                 return &bpf_skb_change_type_proto;
3143         case BPF_FUNC_skb_adjust_room:
3144                 return &bpf_skb_adjust_room_proto;
3145         case BPF_FUNC_skb_change_tail:
3146                 return &bpf_skb_change_tail_proto;
3147         case BPF_FUNC_skb_get_tunnel_key:
3148                 return &bpf_skb_get_tunnel_key_proto;
3149         case BPF_FUNC_skb_set_tunnel_key:
3150                 return bpf_get_skb_set_tunnel_proto(func_id);
3151         case BPF_FUNC_skb_get_tunnel_opt:
3152                 return &bpf_skb_get_tunnel_opt_proto;
3153         case BPF_FUNC_skb_set_tunnel_opt:
3154                 return bpf_get_skb_set_tunnel_proto(func_id);
3155         case BPF_FUNC_redirect:
3156                 return &bpf_redirect_proto;
3157         case BPF_FUNC_get_route_realm:
3158                 return &bpf_get_route_realm_proto;
3159         case BPF_FUNC_get_hash_recalc:
3160                 return &bpf_get_hash_recalc_proto;
3161         case BPF_FUNC_set_hash_invalid:
3162                 return &bpf_set_hash_invalid_proto;
3163         case BPF_FUNC_set_hash:
3164                 return &bpf_set_hash_proto;
3165         case BPF_FUNC_perf_event_output:
3166                 return &bpf_skb_event_output_proto;
3167         case BPF_FUNC_get_smp_processor_id:
3168                 return &bpf_get_smp_processor_id_proto;
3169         case BPF_FUNC_skb_under_cgroup:
3170                 return &bpf_skb_under_cgroup_proto;
3171         case BPF_FUNC_get_socket_cookie:
3172                 return &bpf_get_socket_cookie_proto;
3173         case BPF_FUNC_get_socket_uid:
3174                 return &bpf_get_socket_uid_proto;
3175         default:
3176                 return bpf_base_func_proto(func_id);
3177         }
3178 }
3179
3180 static const struct bpf_func_proto *
3181 xdp_func_proto(enum bpf_func_id func_id)
3182 {
3183         switch (func_id) {
3184         case BPF_FUNC_perf_event_output:
3185                 return &bpf_xdp_event_output_proto;
3186         case BPF_FUNC_get_smp_processor_id:
3187                 return &bpf_get_smp_processor_id_proto;
3188         case BPF_FUNC_xdp_adjust_head:
3189                 return &bpf_xdp_adjust_head_proto;
3190         case BPF_FUNC_redirect:
3191                 return &bpf_xdp_redirect_proto;
3192         case BPF_FUNC_redirect_map:
3193                 return &bpf_redirect_map_proto;
3194         default:
3195                 return bpf_base_func_proto(func_id);
3196         }
3197 }
3198
3199 static const struct bpf_func_proto *
3200 lwt_inout_func_proto(enum bpf_func_id func_id)
3201 {
3202         switch (func_id) {
3203         case BPF_FUNC_skb_load_bytes:
3204                 return &bpf_skb_load_bytes_proto;
3205         case BPF_FUNC_skb_pull_data:
3206                 return &bpf_skb_pull_data_proto;
3207         case BPF_FUNC_csum_diff:
3208                 return &bpf_csum_diff_proto;
3209         case BPF_FUNC_get_cgroup_classid:
3210                 return &bpf_get_cgroup_classid_proto;
3211         case BPF_FUNC_get_route_realm:
3212                 return &bpf_get_route_realm_proto;
3213         case BPF_FUNC_get_hash_recalc:
3214                 return &bpf_get_hash_recalc_proto;
3215         case BPF_FUNC_perf_event_output:
3216                 return &bpf_skb_event_output_proto;
3217         case BPF_FUNC_get_smp_processor_id:
3218                 return &bpf_get_smp_processor_id_proto;
3219         case BPF_FUNC_skb_under_cgroup:
3220                 return &bpf_skb_under_cgroup_proto;
3221         default:
3222                 return bpf_base_func_proto(func_id);
3223         }
3224 }
3225
3226 static const struct bpf_func_proto *
3227         sock_ops_func_proto(enum bpf_func_id func_id)
3228 {
3229         switch (func_id) {
3230         case BPF_FUNC_setsockopt:
3231                 return &bpf_setsockopt_proto;
3232         default:
3233                 return bpf_base_func_proto(func_id);
3234         }
3235 }
3236
3237 static const struct bpf_func_proto *sk_skb_func_proto(enum bpf_func_id func_id)
3238 {
3239         switch (func_id) {
3240         case BPF_FUNC_skb_load_bytes:
3241                 return &bpf_skb_load_bytes_proto;
3242         case BPF_FUNC_get_socket_cookie:
3243                 return &bpf_get_socket_cookie_proto;
3244         case BPF_FUNC_get_socket_uid:
3245                 return &bpf_get_socket_uid_proto;
3246         default:
3247                 return bpf_base_func_proto(func_id);
3248         }
3249 }
3250
3251 static const struct bpf_func_proto *
3252 lwt_xmit_func_proto(enum bpf_func_id func_id)
3253 {
3254         switch (func_id) {
3255         case BPF_FUNC_skb_get_tunnel_key:
3256                 return &bpf_skb_get_tunnel_key_proto;
3257         case BPF_FUNC_skb_set_tunnel_key:
3258                 return bpf_get_skb_set_tunnel_proto(func_id);
3259         case BPF_FUNC_skb_get_tunnel_opt:
3260                 return &bpf_skb_get_tunnel_opt_proto;
3261         case BPF_FUNC_skb_set_tunnel_opt:
3262                 return bpf_get_skb_set_tunnel_proto(func_id);
3263         case BPF_FUNC_redirect:
3264                 return &bpf_redirect_proto;
3265         case BPF_FUNC_clone_redirect:
3266                 return &bpf_clone_redirect_proto;
3267         case BPF_FUNC_skb_change_tail:
3268                 return &bpf_skb_change_tail_proto;
3269         case BPF_FUNC_skb_change_head:
3270                 return &bpf_skb_change_head_proto;
3271         case BPF_FUNC_skb_store_bytes:
3272                 return &bpf_skb_store_bytes_proto;
3273         case BPF_FUNC_csum_update:
3274                 return &bpf_csum_update_proto;
3275         case BPF_FUNC_l3_csum_replace:
3276                 return &bpf_l3_csum_replace_proto;
3277         case BPF_FUNC_l4_csum_replace:
3278                 return &bpf_l4_csum_replace_proto;
3279         case BPF_FUNC_set_hash_invalid:
3280                 return &bpf_set_hash_invalid_proto;
3281         default:
3282                 return lwt_inout_func_proto(func_id);
3283         }
3284 }
3285
3286 static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
3287                                     struct bpf_insn_access_aux *info)
3288 {
3289         const int size_default = sizeof(__u32);
3290
3291         if (off < 0 || off >= sizeof(struct __sk_buff))
3292                 return false;
3293
3294         /* The verifier guarantees that size > 0. */
3295         if (off % size != 0)
3296                 return false;
3297
3298         switch (off) {
3299         case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
3300                 if (off + size > offsetofend(struct __sk_buff, cb[4]))
3301                         return false;
3302                 break;
3303         case bpf_ctx_range(struct __sk_buff, data):
3304         case bpf_ctx_range(struct __sk_buff, data_end):
3305                 if (size != size_default)
3306                         return false;
3307                 break;
3308         default:
3309                 /* Only narrow read access allowed for now. */
3310                 if (type == BPF_WRITE) {
3311                         if (size != size_default)
3312                                 return false;
3313                 } else {
3314                         bpf_ctx_record_field_size(info, size_default);
3315                         if (!bpf_ctx_narrow_access_ok(off, size, size_default))
3316                                 return false;
3317                 }
3318         }
3319
3320         return true;
3321 }
3322
3323 static bool sk_filter_is_valid_access(int off, int size,
3324                                       enum bpf_access_type type,
3325                                       struct bpf_insn_access_aux *info)
3326 {
3327         switch (off) {
3328         case bpf_ctx_range(struct __sk_buff, tc_classid):
3329         case bpf_ctx_range(struct __sk_buff, data):
3330         case bpf_ctx_range(struct __sk_buff, data_end):
3331                 return false;
3332         }
3333
3334         if (type == BPF_WRITE) {
3335                 switch (off) {
3336                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
3337                         break;
3338                 default:
3339                         return false;
3340                 }
3341         }
3342
3343         return bpf_skb_is_valid_access(off, size, type, info);
3344 }
3345
3346 static bool lwt_is_valid_access(int off, int size,
3347                                 enum bpf_access_type type,
3348                                 struct bpf_insn_access_aux *info)
3349 {
3350         switch (off) {
3351         case bpf_ctx_range(struct __sk_buff, tc_classid):
3352                 return false;
3353         }
3354
3355         if (type == BPF_WRITE) {
3356                 switch (off) {
3357                 case bpf_ctx_range(struct __sk_buff, mark):
3358                 case bpf_ctx_range(struct __sk_buff, priority):
3359                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
3360                         break;
3361                 default:
3362                         return false;
3363                 }
3364         }
3365
3366         switch (off) {
3367         case bpf_ctx_range(struct __sk_buff, data):
3368                 info->reg_type = PTR_TO_PACKET;
3369                 break;
3370         case bpf_ctx_range(struct __sk_buff, data_end):
3371                 info->reg_type = PTR_TO_PACKET_END;
3372                 break;
3373         }
3374
3375         return bpf_skb_is_valid_access(off, size, type, info);
3376 }
3377
3378 static bool sock_filter_is_valid_access(int off, int size,
3379                                         enum bpf_access_type type,
3380                                         struct bpf_insn_access_aux *info)
3381 {
3382         if (type == BPF_WRITE) {
3383                 switch (off) {
3384                 case offsetof(struct bpf_sock, bound_dev_if):
3385                         break;
3386                 default:
3387                         return false;
3388                 }
3389         }
3390
3391         if (off < 0 || off + size > sizeof(struct bpf_sock))
3392                 return false;
3393         /* The verifier guarantees that size > 0. */
3394         if (off % size != 0)
3395                 return false;
3396         if (size != sizeof(__u32))
3397                 return false;
3398
3399         return true;
3400 }
3401
3402 static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
3403                                const struct bpf_prog *prog)
3404 {
3405         struct bpf_insn *insn = insn_buf;
3406
3407         if (!direct_write)
3408                 return 0;
3409
3410         /* if (!skb->cloned)
3411          *       goto start;
3412          *
3413          * (Fast-path, otherwise approximation that we might be
3414          *  a clone, do the rest in helper.)
3415          */
3416         *insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET());
3417         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
3418         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
3419
3420         /* ret = bpf_skb_pull_data(skb, 0); */
3421         *insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
3422         *insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
3423         *insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
3424                                BPF_FUNC_skb_pull_data);
3425         /* if (!ret)
3426          *      goto restore;
3427          * return TC_ACT_SHOT;
3428          */
3429         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
3430         *insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, TC_ACT_SHOT);
3431         *insn++ = BPF_EXIT_INSN();
3432
3433         /* restore: */
3434         *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
3435         /* start: */
3436         *insn++ = prog->insnsi[0];
3437
3438         return insn - insn_buf;
3439 }
3440
3441 static bool tc_cls_act_is_valid_access(int off, int size,
3442                                        enum bpf_access_type type,
3443                                        struct bpf_insn_access_aux *info)
3444 {
3445         if (type == BPF_WRITE) {
3446                 switch (off) {
3447                 case bpf_ctx_range(struct __sk_buff, mark):
3448                 case bpf_ctx_range(struct __sk_buff, tc_index):
3449                 case bpf_ctx_range(struct __sk_buff, priority):
3450                 case bpf_ctx_range(struct __sk_buff, tc_classid):
3451                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
3452                         break;
3453                 default:
3454                         return false;
3455                 }
3456         }
3457
3458         switch (off) {
3459         case bpf_ctx_range(struct __sk_buff, data):
3460                 info->reg_type = PTR_TO_PACKET;
3461                 break;
3462         case bpf_ctx_range(struct __sk_buff, data_end):
3463                 info->reg_type = PTR_TO_PACKET_END;
3464                 break;
3465         }
3466
3467         return bpf_skb_is_valid_access(off, size, type, info);
3468 }
3469
3470 static bool __is_valid_xdp_access(int off, int size)
3471 {
3472         if (off < 0 || off >= sizeof(struct xdp_md))
3473                 return false;
3474         if (off % size != 0)
3475                 return false;
3476         if (size != sizeof(__u32))
3477                 return false;
3478
3479         return true;
3480 }
3481
3482 static bool xdp_is_valid_access(int off, int size,
3483                                 enum bpf_access_type type,
3484                                 struct bpf_insn_access_aux *info)
3485 {
3486         if (type == BPF_WRITE)
3487                 return false;
3488
3489         switch (off) {
3490         case offsetof(struct xdp_md, data):
3491                 info->reg_type = PTR_TO_PACKET;
3492                 break;
3493         case offsetof(struct xdp_md, data_end):
3494                 info->reg_type = PTR_TO_PACKET_END;
3495                 break;
3496         }
3497
3498         return __is_valid_xdp_access(off, size);
3499 }
3500
3501 void bpf_warn_invalid_xdp_action(u32 act)
3502 {
3503         WARN_ONCE(1, "Illegal XDP return value %u, expect packet loss\n", act);
3504 }
3505 EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
3506
3507 void bpf_warn_invalid_xdp_redirect(u32 ifindex)
3508 {
3509         WARN_ONCE(1, "Illegal XDP redirect to unsupported device ifindex(%i)\n", ifindex);
3510 }
3511
3512 static bool __is_valid_sock_ops_access(int off, int size)
3513 {
3514         if (off < 0 || off >= sizeof(struct bpf_sock_ops))
3515                 return false;
3516         /* The verifier guarantees that size > 0. */
3517         if (off % size != 0)
3518                 return false;
3519         if (size != sizeof(__u32))
3520                 return false;
3521
3522         return true;
3523 }
3524
3525 static bool sock_ops_is_valid_access(int off, int size,
3526                                      enum bpf_access_type type,
3527                                      struct bpf_insn_access_aux *info)
3528 {
3529         if (type == BPF_WRITE) {
3530                 switch (off) {
3531                 case offsetof(struct bpf_sock_ops, op) ...
3532                      offsetof(struct bpf_sock_ops, replylong[3]):
3533                         break;
3534                 default:
3535                         return false;
3536                 }
3537         }
3538
3539         return __is_valid_sock_ops_access(off, size);
3540 }
3541
3542 static bool sk_skb_is_valid_access(int off, int size,
3543                                    enum bpf_access_type type,
3544                                    struct bpf_insn_access_aux *info)
3545 {
3546         switch (off) {
3547         case bpf_ctx_range(struct __sk_buff, data):
3548                 info->reg_type = PTR_TO_PACKET;
3549                 break;
3550         case bpf_ctx_range(struct __sk_buff, data_end):
3551                 info->reg_type = PTR_TO_PACKET_END;
3552                 break;
3553         }
3554
3555         return bpf_skb_is_valid_access(off, size, type, info);
3556 }
3557
3558 static u32 bpf_convert_ctx_access(enum bpf_access_type type,
3559                                   const struct bpf_insn *si,
3560                                   struct bpf_insn *insn_buf,
3561                                   struct bpf_prog *prog, u32 *target_size)
3562 {
3563         struct bpf_insn *insn = insn_buf;
3564         int off;
3565
3566         switch (si->off) {
3567         case offsetof(struct __sk_buff, len):
3568                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3569                                       bpf_target_off(struct sk_buff, len, 4,
3570                                                      target_size));
3571                 break;
3572
3573         case offsetof(struct __sk_buff, protocol):
3574                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
3575                                       bpf_target_off(struct sk_buff, protocol, 2,
3576                                                      target_size));
3577                 break;
3578
3579         case offsetof(struct __sk_buff, vlan_proto):
3580                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
3581                                       bpf_target_off(struct sk_buff, vlan_proto, 2,
3582                                                      target_size));
3583                 break;
3584
3585         case offsetof(struct __sk_buff, priority):
3586                 if (type == BPF_WRITE)
3587                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
3588                                               bpf_target_off(struct sk_buff, priority, 4,
3589                                                              target_size));
3590                 else
3591                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3592                                               bpf_target_off(struct sk_buff, priority, 4,
3593                                                              target_size));
3594                 break;
3595
3596         case offsetof(struct __sk_buff, ingress_ifindex):
3597                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3598                                       bpf_target_off(struct sk_buff, skb_iif, 4,
3599                                                      target_size));
3600                 break;
3601
3602         case offsetof(struct __sk_buff, ifindex):
3603                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
3604                                       si->dst_reg, si->src_reg,
3605                                       offsetof(struct sk_buff, dev));
3606                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
3607                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
3608                                       bpf_target_off(struct net_device, ifindex, 4,
3609                                                      target_size));
3610                 break;
3611
3612         case offsetof(struct __sk_buff, hash):
3613                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3614                                       bpf_target_off(struct sk_buff, hash, 4,
3615                                                      target_size));
3616                 break;
3617
3618         case offsetof(struct __sk_buff, mark):
3619                 if (type == BPF_WRITE)
3620                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
3621                                               bpf_target_off(struct sk_buff, mark, 4,
3622                                                              target_size));
3623                 else
3624                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3625                                               bpf_target_off(struct sk_buff, mark, 4,
3626                                                              target_size));
3627                 break;
3628
3629         case offsetof(struct __sk_buff, pkt_type):
3630                 *target_size = 1;
3631                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
3632                                       PKT_TYPE_OFFSET());
3633                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
3634 #ifdef __BIG_ENDIAN_BITFIELD
3635                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
3636 #endif
3637                 break;
3638
3639         case offsetof(struct __sk_buff, queue_mapping):
3640                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
3641                                       bpf_target_off(struct sk_buff, queue_mapping, 2,
3642                                                      target_size));
3643                 break;
3644
3645         case offsetof(struct __sk_buff, vlan_present):
3646         case offsetof(struct __sk_buff, vlan_tci):
3647                 BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);
3648
3649                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
3650                                       bpf_target_off(struct sk_buff, vlan_tci, 2,
3651                                                      target_size));
3652                 if (si->off == offsetof(struct __sk_buff, vlan_tci)) {
3653                         *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg,
3654                                                 ~VLAN_TAG_PRESENT);
3655                 } else {
3656                         *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 12);
3657                         *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1);
3658                 }
3659                 break;
3660
3661         case offsetof(struct __sk_buff, cb[0]) ...
3662              offsetofend(struct __sk_buff, cb[4]) - 1:
3663                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);
3664                 BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
3665                               offsetof(struct qdisc_skb_cb, data)) %
3666                              sizeof(__u64));
3667
3668                 prog->cb_access = 1;
3669                 off  = si->off;
3670                 off -= offsetof(struct __sk_buff, cb[0]);
3671                 off += offsetof(struct sk_buff, cb);
3672                 off += offsetof(struct qdisc_skb_cb, data);
3673                 if (type == BPF_WRITE)
3674                         *insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
3675                                               si->src_reg, off);
3676                 else
3677                         *insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
3678                                               si->src_reg, off);
3679                 break;
3680
3681         case offsetof(struct __sk_buff, tc_classid):
3682                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, tc_classid) != 2);
3683
3684                 off  = si->off;
3685                 off -= offsetof(struct __sk_buff, tc_classid);
3686                 off += offsetof(struct sk_buff, cb);
3687                 off += offsetof(struct qdisc_skb_cb, tc_classid);
3688                 *target_size = 2;
3689                 if (type == BPF_WRITE)
3690                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg,
3691                                               si->src_reg, off);
3692                 else
3693                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
3694                                               si->src_reg, off);
3695                 break;
3696
3697         case offsetof(struct __sk_buff, data):
3698                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
3699                                       si->dst_reg, si->src_reg,
3700                                       offsetof(struct sk_buff, data));
3701                 break;
3702
3703         case offsetof(struct __sk_buff, data_end):
3704                 off  = si->off;
3705                 off -= offsetof(struct __sk_buff, data_end);
3706                 off += offsetof(struct sk_buff, cb);
3707                 off += offsetof(struct bpf_skb_data_end, data_end);
3708                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
3709                                       si->src_reg, off);
3710                 break;
3711
3712         case offsetof(struct __sk_buff, tc_index):
3713 #ifdef CONFIG_NET_SCHED
3714                 if (type == BPF_WRITE)
3715                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
3716                                               bpf_target_off(struct sk_buff, tc_index, 2,
3717                                                              target_size));
3718                 else
3719                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
3720                                               bpf_target_off(struct sk_buff, tc_index, 2,
3721                                                              target_size));
3722 #else
3723                 *target_size = 2;
3724                 if (type == BPF_WRITE)
3725                         *insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
3726                 else
3727                         *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
3728 #endif
3729                 break;
3730
3731         case offsetof(struct __sk_buff, napi_id):
3732 #if defined(CONFIG_NET_RX_BUSY_POLL)
3733                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3734                                       bpf_target_off(struct sk_buff, napi_id, 4,
3735                                                      target_size));
3736                 *insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
3737                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
3738 #else
3739                 *target_size = 4;
3740                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
3741 #endif
3742                 break;
3743         }
3744
3745         return insn - insn_buf;
3746 }
3747
3748 static u32 sock_filter_convert_ctx_access(enum bpf_access_type type,
3749                                           const struct bpf_insn *si,
3750                                           struct bpf_insn *insn_buf,
3751                                           struct bpf_prog *prog, u32 *target_size)
3752 {
3753         struct bpf_insn *insn = insn_buf;
3754
3755         switch (si->off) {
3756         case offsetof(struct bpf_sock, bound_dev_if):
3757                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_bound_dev_if) != 4);
3758
3759                 if (type == BPF_WRITE)
3760                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
3761                                         offsetof(struct sock, sk_bound_dev_if));
3762                 else
3763                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3764                                       offsetof(struct sock, sk_bound_dev_if));
3765                 break;
3766
3767         case offsetof(struct bpf_sock, family):
3768                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_family) != 2);
3769
3770                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
3771                                       offsetof(struct sock, sk_family));
3772                 break;
3773
3774         case offsetof(struct bpf_sock, type):
3775                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3776                                       offsetof(struct sock, __sk_flags_offset));
3777                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
3778                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
3779                 break;
3780
3781         case offsetof(struct bpf_sock, protocol):
3782                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3783                                       offsetof(struct sock, __sk_flags_offset));
3784                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
3785                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT);
3786                 break;
3787         }
3788
3789         return insn - insn_buf;
3790 }
3791
3792 static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
3793                                          const struct bpf_insn *si,
3794                                          struct bpf_insn *insn_buf,
3795                                          struct bpf_prog *prog, u32 *target_size)
3796 {
3797         struct bpf_insn *insn = insn_buf;
3798
3799         switch (si->off) {
3800         case offsetof(struct __sk_buff, ifindex):
3801                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
3802                                       si->dst_reg, si->src_reg,
3803                                       offsetof(struct sk_buff, dev));
3804                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
3805                                       bpf_target_off(struct net_device, ifindex, 4,
3806                                                      target_size));
3807                 break;
3808         default:
3809                 return bpf_convert_ctx_access(type, si, insn_buf, prog,
3810                                               target_size);
3811         }
3812
3813         return insn - insn_buf;
3814 }
3815
3816 static u32 xdp_convert_ctx_access(enum bpf_access_type type,
3817                                   const struct bpf_insn *si,
3818                                   struct bpf_insn *insn_buf,
3819                                   struct bpf_prog *prog, u32 *target_size)
3820 {
3821         struct bpf_insn *insn = insn_buf;
3822
3823         switch (si->off) {
3824         case offsetof(struct xdp_md, data):
3825                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
3826                                       si->dst_reg, si->src_reg,
3827                                       offsetof(struct xdp_buff, data));
3828                 break;
3829         case offsetof(struct xdp_md, data_end):
3830                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
3831                                       si->dst_reg, si->src_reg,
3832                                       offsetof(struct xdp_buff, data_end));
3833                 break;
3834         }
3835
3836         return insn - insn_buf;
3837 }
3838
3839 static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
3840                                        const struct bpf_insn *si,
3841                                        struct bpf_insn *insn_buf,
3842                                        struct bpf_prog *prog,
3843                                        u32 *target_size)
3844 {
3845         struct bpf_insn *insn = insn_buf;
3846         int off;
3847
3848         switch (si->off) {
3849         case offsetof(struct bpf_sock_ops, op) ...
3850              offsetof(struct bpf_sock_ops, replylong[3]):
3851                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, op) !=
3852                              FIELD_SIZEOF(struct bpf_sock_ops_kern, op));
3853                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, reply) !=
3854                              FIELD_SIZEOF(struct bpf_sock_ops_kern, reply));
3855                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, replylong) !=
3856                              FIELD_SIZEOF(struct bpf_sock_ops_kern, replylong));
3857                 off = si->off;
3858                 off -= offsetof(struct bpf_sock_ops, op);
3859                 off += offsetof(struct bpf_sock_ops_kern, op);
3860                 if (type == BPF_WRITE)
3861                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
3862                                               off);
3863                 else
3864                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3865                                               off);
3866                 break;
3867
3868         case offsetof(struct bpf_sock_ops, family):
3869                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
3870
3871                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
3872                                               struct bpf_sock_ops_kern, sk),
3873                                       si->dst_reg, si->src_reg,
3874                                       offsetof(struct bpf_sock_ops_kern, sk));
3875                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
3876                                       offsetof(struct sock_common, skc_family));
3877                 break;
3878
3879         case offsetof(struct bpf_sock_ops, remote_ip4):
3880                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
3881
3882                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
3883                                                 struct bpf_sock_ops_kern, sk),
3884                                       si->dst_reg, si->src_reg,
3885                                       offsetof(struct bpf_sock_ops_kern, sk));
3886                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
3887                                       offsetof(struct sock_common, skc_daddr));
3888                 break;
3889
3890         case offsetof(struct bpf_sock_ops, local_ip4):
3891                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_rcv_saddr) != 4);
3892
3893                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
3894                                               struct bpf_sock_ops_kern, sk),
3895                                       si->dst_reg, si->src_reg,
3896                                       offsetof(struct bpf_sock_ops_kern, sk));
3897                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
3898                                       offsetof(struct sock_common,
3899                                                skc_rcv_saddr));
3900                 break;
3901
3902         case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
3903              offsetof(struct bpf_sock_ops, remote_ip6[3]):
3904 #if IS_ENABLED(CONFIG_IPV6)
3905                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
3906                                           skc_v6_daddr.s6_addr32[0]) != 4);
3907
3908                 off = si->off;
3909                 off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
3910                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
3911                                                 struct bpf_sock_ops_kern, sk),
3912                                       si->dst_reg, si->src_reg,
3913                                       offsetof(struct bpf_sock_ops_kern, sk));
3914                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
3915                                       offsetof(struct sock_common,
3916                                                skc_v6_daddr.s6_addr32[0]) +
3917                                       off);
3918 #else
3919                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
3920 #endif
3921                 break;
3922
3923         case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
3924              offsetof(struct bpf_sock_ops, local_ip6[3]):
3925 #if IS_ENABLED(CONFIG_IPV6)
3926                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
3927                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
3928
3929                 off = si->off;
3930                 off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
3931                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
3932                                                 struct bpf_sock_ops_kern, sk),
3933                                       si->dst_reg, si->src_reg,
3934                                       offsetof(struct bpf_sock_ops_kern, sk));
3935                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
3936                                       offsetof(struct sock_common,
3937                                                skc_v6_rcv_saddr.s6_addr32[0]) +
3938                                       off);
3939 #else
3940                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
3941 #endif
3942                 break;
3943
3944         case offsetof(struct bpf_sock_ops, remote_port):
3945                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
3946
3947                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
3948                                                 struct bpf_sock_ops_kern, sk),
3949                                       si->dst_reg, si->src_reg,
3950                                       offsetof(struct bpf_sock_ops_kern, sk));
3951                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
3952                                       offsetof(struct sock_common, skc_dport));
3953 #ifndef __BIG_ENDIAN_BITFIELD
3954                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
3955 #endif
3956                 break;
3957
3958         case offsetof(struct bpf_sock_ops, local_port):
3959                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
3960
3961                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
3962                                                 struct bpf_sock_ops_kern, sk),
3963                                       si->dst_reg, si->src_reg,
3964                                       offsetof(struct bpf_sock_ops_kern, sk));
3965                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
3966                                       offsetof(struct sock_common, skc_num));
3967                 break;
3968         }
3969         return insn - insn_buf;
3970 }
3971
3972 const struct bpf_verifier_ops sk_filter_prog_ops = {
3973         .get_func_proto         = sk_filter_func_proto,
3974         .is_valid_access        = sk_filter_is_valid_access,
3975         .convert_ctx_access     = bpf_convert_ctx_access,
3976 };
3977
3978 const struct bpf_verifier_ops tc_cls_act_prog_ops = {
3979         .get_func_proto         = tc_cls_act_func_proto,
3980         .is_valid_access        = tc_cls_act_is_valid_access,
3981         .convert_ctx_access     = tc_cls_act_convert_ctx_access,
3982         .gen_prologue           = tc_cls_act_prologue,
3983         .test_run               = bpf_prog_test_run_skb,
3984 };
3985
3986 const struct bpf_verifier_ops xdp_prog_ops = {
3987         .get_func_proto         = xdp_func_proto,
3988         .is_valid_access        = xdp_is_valid_access,
3989         .convert_ctx_access     = xdp_convert_ctx_access,
3990         .test_run               = bpf_prog_test_run_xdp,
3991 };
3992
3993 const struct bpf_verifier_ops cg_skb_prog_ops = {
3994         .get_func_proto         = sk_filter_func_proto,
3995         .is_valid_access        = sk_filter_is_valid_access,
3996         .convert_ctx_access     = bpf_convert_ctx_access,
3997         .test_run               = bpf_prog_test_run_skb,
3998 };
3999
4000 const struct bpf_verifier_ops lwt_inout_prog_ops = {
4001         .get_func_proto         = lwt_inout_func_proto,
4002         .is_valid_access        = lwt_is_valid_access,
4003         .convert_ctx_access     = bpf_convert_ctx_access,
4004         .test_run               = bpf_prog_test_run_skb,
4005 };
4006
4007 const struct bpf_verifier_ops lwt_xmit_prog_ops = {
4008         .get_func_proto         = lwt_xmit_func_proto,
4009         .is_valid_access        = lwt_is_valid_access,
4010         .convert_ctx_access     = bpf_convert_ctx_access,
4011         .gen_prologue           = tc_cls_act_prologue,
4012         .test_run               = bpf_prog_test_run_skb,
4013 };
4014
4015 const struct bpf_verifier_ops cg_sock_prog_ops = {
4016         .get_func_proto         = bpf_base_func_proto,
4017         .is_valid_access        = sock_filter_is_valid_access,
4018         .convert_ctx_access     = sock_filter_convert_ctx_access,
4019 };
4020
4021 const struct bpf_verifier_ops sock_ops_prog_ops = {
4022         .get_func_proto         = sock_ops_func_proto,
4023         .is_valid_access        = sock_ops_is_valid_access,
4024         .convert_ctx_access     = sock_ops_convert_ctx_access,
4025 };
4026
4027 const struct bpf_verifier_ops sk_skb_prog_ops = {
4028         .get_func_proto         = sk_skb_func_proto,
4029         .is_valid_access        = sk_skb_is_valid_access,
4030         .convert_ctx_access     = bpf_convert_ctx_access,
4031 };
4032
4033 int sk_detach_filter(struct sock *sk)
4034 {
4035         int ret = -ENOENT;
4036         struct sk_filter *filter;
4037
4038         if (sock_flag(sk, SOCK_FILTER_LOCKED))
4039                 return -EPERM;
4040
4041         filter = rcu_dereference_protected(sk->sk_filter,
4042                                            lockdep_sock_is_held(sk));
4043         if (filter) {
4044                 RCU_INIT_POINTER(sk->sk_filter, NULL);
4045                 sk_filter_uncharge(sk, filter);
4046                 ret = 0;
4047         }
4048
4049         return ret;
4050 }
4051 EXPORT_SYMBOL_GPL(sk_detach_filter);
4052
4053 int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
4054                   unsigned int len)
4055 {
4056         struct sock_fprog_kern *fprog;
4057         struct sk_filter *filter;
4058         int ret = 0;
4059
4060         lock_sock(sk);
4061         filter = rcu_dereference_protected(sk->sk_filter,
4062                                            lockdep_sock_is_held(sk));
4063         if (!filter)
4064                 goto out;
4065
4066         /* We're copying the filter that has been originally attached,
4067          * so no conversion/decode needed anymore. eBPF programs that
4068          * have no original program cannot be dumped through this.
4069          */
4070         ret = -EACCES;
4071         fprog = filter->prog->orig_prog;
4072         if (!fprog)
4073                 goto out;
4074
4075         ret = fprog->len;
4076         if (!len)
4077                 /* User space only enquires number of filter blocks. */
4078                 goto out;
4079
4080         ret = -EINVAL;
4081         if (len < fprog->len)
4082                 goto out;
4083
4084         ret = -EFAULT;
4085         if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
4086                 goto out;
4087
4088         /* Instead of bytes, the API requests to return the number
4089          * of filter blocks.
4090          */
4091         ret = fprog->len;
4092 out:
4093         release_sock(sk);
4094         return ret;
4095 }