bpf: add BPF_CALL_x macros for declaring helpers
[cascardo/linux.git] / net / core / filter.c
1 /*
2  * Linux Socket Filter - Kernel level socket filtering
3  *
4  * Based on the design of the Berkeley Packet Filter. The new
5  * internal format has been designed by PLUMgrid:
6  *
7  *      Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
8  *
9  * Authors:
10  *
11  *      Jay Schulist <jschlst@samba.org>
12  *      Alexei Starovoitov <ast@plumgrid.com>
13  *      Daniel Borkmann <dborkman@redhat.com>
14  *
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * as published by the Free Software Foundation; either version
18  * 2 of the License, or (at your option) any later version.
19  *
20  * Andi Kleen - Fix a few bad bugs and races.
21  * Kris Katterjohn - Added many additional checks in bpf_check_classic()
22  */
23
24 #include <linux/module.h>
25 #include <linux/types.h>
26 #include <linux/mm.h>
27 #include <linux/fcntl.h>
28 #include <linux/socket.h>
29 #include <linux/in.h>
30 #include <linux/inet.h>
31 #include <linux/netdevice.h>
32 #include <linux/if_packet.h>
33 #include <linux/gfp.h>
34 #include <net/ip.h>
35 #include <net/protocol.h>
36 #include <net/netlink.h>
37 #include <linux/skbuff.h>
38 #include <net/sock.h>
39 #include <net/flow_dissector.h>
40 #include <linux/errno.h>
41 #include <linux/timer.h>
42 #include <asm/uaccess.h>
43 #include <asm/unaligned.h>
44 #include <linux/filter.h>
45 #include <linux/ratelimit.h>
46 #include <linux/seccomp.h>
47 #include <linux/if_vlan.h>
48 #include <linux/bpf.h>
49 #include <net/sch_generic.h>
50 #include <net/cls_cgroup.h>
51 #include <net/dst_metadata.h>
52 #include <net/dst.h>
53 #include <net/sock_reuseport.h>
54
55 /**
56  *      sk_filter_trim_cap - run a packet through a socket filter
57  *      @sk: sock associated with &sk_buff
58  *      @skb: buffer to filter
59  *      @cap: limit on how short the eBPF program may trim the packet
60  *
61  * Run the eBPF program and then cut skb->data to correct size returned by
62  * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
63  * than pkt_len we keep whole skb->data. This is the socket level
64  * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
65  * be accepted or -EPERM if the packet should be tossed.
66  *
67  */
68 int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
69 {
70         int err;
71         struct sk_filter *filter;
72
73         /*
74          * If the skb was allocated from pfmemalloc reserves, only
75          * allow SOCK_MEMALLOC sockets to use it as this socket is
76          * helping free memory
77          */
78         if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC))
79                 return -ENOMEM;
80
81         err = security_sock_rcv_skb(sk, skb);
82         if (err)
83                 return err;
84
85         rcu_read_lock();
86         filter = rcu_dereference(sk->sk_filter);
87         if (filter) {
88                 unsigned int pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
89                 err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
90         }
91         rcu_read_unlock();
92
93         return err;
94 }
95 EXPORT_SYMBOL(sk_filter_trim_cap);
96
97 BPF_CALL_1(__skb_get_pay_offset, struct sk_buff *, skb)
98 {
99         return skb_get_poff(skb);
100 }
101
102 BPF_CALL_3(__skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
103 {
104         struct nlattr *nla;
105
106         if (skb_is_nonlinear(skb))
107                 return 0;
108
109         if (skb->len < sizeof(struct nlattr))
110                 return 0;
111
112         if (a > skb->len - sizeof(struct nlattr))
113                 return 0;
114
115         nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
116         if (nla)
117                 return (void *) nla - (void *) skb->data;
118
119         return 0;
120 }
121
122 BPF_CALL_3(__skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
123 {
124         struct nlattr *nla;
125
126         if (skb_is_nonlinear(skb))
127                 return 0;
128
129         if (skb->len < sizeof(struct nlattr))
130                 return 0;
131
132         if (a > skb->len - sizeof(struct nlattr))
133                 return 0;
134
135         nla = (struct nlattr *) &skb->data[a];
136         if (nla->nla_len > skb->len - a)
137                 return 0;
138
139         nla = nla_find_nested(nla, x);
140         if (nla)
141                 return (void *) nla - (void *) skb->data;
142
143         return 0;
144 }
145
146 BPF_CALL_0(__get_raw_cpu_id)
147 {
148         return raw_smp_processor_id();
149 }
150
151 static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
152         .func           = __get_raw_cpu_id,
153         .gpl_only       = false,
154         .ret_type       = RET_INTEGER,
155 };
156
157 static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
158                               struct bpf_insn *insn_buf)
159 {
160         struct bpf_insn *insn = insn_buf;
161
162         switch (skb_field) {
163         case SKF_AD_MARK:
164                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);
165
166                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
167                                       offsetof(struct sk_buff, mark));
168                 break;
169
170         case SKF_AD_PKTTYPE:
171                 *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET());
172                 *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
173 #ifdef __BIG_ENDIAN_BITFIELD
174                 *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
175 #endif
176                 break;
177
178         case SKF_AD_QUEUE:
179                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2);
180
181                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
182                                       offsetof(struct sk_buff, queue_mapping));
183                 break;
184
185         case SKF_AD_VLAN_TAG:
186         case SKF_AD_VLAN_TAG_PRESENT:
187                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_tci) != 2);
188                 BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);
189
190                 /* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
191                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
192                                       offsetof(struct sk_buff, vlan_tci));
193                 if (skb_field == SKF_AD_VLAN_TAG) {
194                         *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg,
195                                                 ~VLAN_TAG_PRESENT);
196                 } else {
197                         /* dst_reg >>= 12 */
198                         *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 12);
199                         /* dst_reg &= 1 */
200                         *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1);
201                 }
202                 break;
203         }
204
205         return insn - insn_buf;
206 }
207
208 static bool convert_bpf_extensions(struct sock_filter *fp,
209                                    struct bpf_insn **insnp)
210 {
211         struct bpf_insn *insn = *insnp;
212         u32 cnt;
213
214         switch (fp->k) {
215         case SKF_AD_OFF + SKF_AD_PROTOCOL:
216                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);
217
218                 /* A = *(u16 *) (CTX + offsetof(protocol)) */
219                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
220                                       offsetof(struct sk_buff, protocol));
221                 /* A = ntohs(A) [emitting a nop or swap16] */
222                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
223                 break;
224
225         case SKF_AD_OFF + SKF_AD_PKTTYPE:
226                 cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
227                 insn += cnt - 1;
228                 break;
229
230         case SKF_AD_OFF + SKF_AD_IFINDEX:
231         case SKF_AD_OFF + SKF_AD_HATYPE:
232                 BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
233                 BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, type) != 2);
234
235                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
236                                       BPF_REG_TMP, BPF_REG_CTX,
237                                       offsetof(struct sk_buff, dev));
238                 /* if (tmp != 0) goto pc + 1 */
239                 *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
240                 *insn++ = BPF_EXIT_INSN();
241                 if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
242                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
243                                             offsetof(struct net_device, ifindex));
244                 else
245                         *insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
246                                             offsetof(struct net_device, type));
247                 break;
248
249         case SKF_AD_OFF + SKF_AD_MARK:
250                 cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
251                 insn += cnt - 1;
252                 break;
253
254         case SKF_AD_OFF + SKF_AD_RXHASH:
255                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);
256
257                 *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
258                                     offsetof(struct sk_buff, hash));
259                 break;
260
261         case SKF_AD_OFF + SKF_AD_QUEUE:
262                 cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
263                 insn += cnt - 1;
264                 break;
265
266         case SKF_AD_OFF + SKF_AD_VLAN_TAG:
267                 cnt = convert_skb_access(SKF_AD_VLAN_TAG,
268                                          BPF_REG_A, BPF_REG_CTX, insn);
269                 insn += cnt - 1;
270                 break;
271
272         case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
273                 cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
274                                          BPF_REG_A, BPF_REG_CTX, insn);
275                 insn += cnt - 1;
276                 break;
277
278         case SKF_AD_OFF + SKF_AD_VLAN_TPID:
279                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);
280
281                 /* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
282                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
283                                       offsetof(struct sk_buff, vlan_proto));
284                 /* A = ntohs(A) [emitting a nop or swap16] */
285                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
286                 break;
287
288         case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
289         case SKF_AD_OFF + SKF_AD_NLATTR:
290         case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
291         case SKF_AD_OFF + SKF_AD_CPU:
292         case SKF_AD_OFF + SKF_AD_RANDOM:
293                 /* arg1 = CTX */
294                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
295                 /* arg2 = A */
296                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
297                 /* arg3 = X */
298                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
299                 /* Emit call(arg1=CTX, arg2=A, arg3=X) */
300                 switch (fp->k) {
301                 case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
302                         *insn = BPF_EMIT_CALL(__skb_get_pay_offset);
303                         break;
304                 case SKF_AD_OFF + SKF_AD_NLATTR:
305                         *insn = BPF_EMIT_CALL(__skb_get_nlattr);
306                         break;
307                 case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
308                         *insn = BPF_EMIT_CALL(__skb_get_nlattr_nest);
309                         break;
310                 case SKF_AD_OFF + SKF_AD_CPU:
311                         *insn = BPF_EMIT_CALL(__get_raw_cpu_id);
312                         break;
313                 case SKF_AD_OFF + SKF_AD_RANDOM:
314                         *insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
315                         bpf_user_rnd_init_once();
316                         break;
317                 }
318                 break;
319
320         case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
321                 /* A ^= X */
322                 *insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
323                 break;
324
325         default:
326                 /* This is just a dummy call to avoid letting the compiler
327                  * evict __bpf_call_base() as an optimization. Placed here
328                  * where no-one bothers.
329                  */
330                 BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
331                 return false;
332         }
333
334         *insnp = insn;
335         return true;
336 }
337
338 /**
339  *      bpf_convert_filter - convert filter program
340  *      @prog: the user passed filter program
341  *      @len: the length of the user passed filter program
342  *      @new_prog: buffer where converted program will be stored
343  *      @new_len: pointer to store length of converted program
344  *
345  * Remap 'sock_filter' style BPF instruction set to 'sock_filter_ext' style.
346  * Conversion workflow:
347  *
348  * 1) First pass for calculating the new program length:
349  *   bpf_convert_filter(old_prog, old_len, NULL, &new_len)
350  *
351  * 2) 2nd pass to remap in two passes: 1st pass finds new
352  *    jump offsets, 2nd pass remapping:
353  *   new_prog = kmalloc(sizeof(struct bpf_insn) * new_len);
354  *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len);
355  */
356 static int bpf_convert_filter(struct sock_filter *prog, int len,
357                               struct bpf_insn *new_prog, int *new_len)
358 {
359         int new_flen = 0, pass = 0, target, i;
360         struct bpf_insn *new_insn;
361         struct sock_filter *fp;
362         int *addrs = NULL;
363         u8 bpf_src;
364
365         BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
366         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
367
368         if (len <= 0 || len > BPF_MAXINSNS)
369                 return -EINVAL;
370
371         if (new_prog) {
372                 addrs = kcalloc(len, sizeof(*addrs),
373                                 GFP_KERNEL | __GFP_NOWARN);
374                 if (!addrs)
375                         return -ENOMEM;
376         }
377
378 do_pass:
379         new_insn = new_prog;
380         fp = prog;
381
382         /* Classic BPF related prologue emission. */
383         if (new_insn) {
384                 /* Classic BPF expects A and X to be reset first. These need
385                  * to be guaranteed to be the first two instructions.
386                  */
387                 *new_insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
388                 *new_insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
389
390                 /* All programs must keep CTX in callee saved BPF_REG_CTX.
391                  * In eBPF case it's done by the compiler, here we need to
392                  * do this ourself. Initial CTX is present in BPF_REG_ARG1.
393                  */
394                 *new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
395         } else {
396                 new_insn += 3;
397         }
398
399         for (i = 0; i < len; fp++, i++) {
400                 struct bpf_insn tmp_insns[6] = { };
401                 struct bpf_insn *insn = tmp_insns;
402
403                 if (addrs)
404                         addrs[i] = new_insn - new_prog;
405
406                 switch (fp->code) {
407                 /* All arithmetic insns and skb loads map as-is. */
408                 case BPF_ALU | BPF_ADD | BPF_X:
409                 case BPF_ALU | BPF_ADD | BPF_K:
410                 case BPF_ALU | BPF_SUB | BPF_X:
411                 case BPF_ALU | BPF_SUB | BPF_K:
412                 case BPF_ALU | BPF_AND | BPF_X:
413                 case BPF_ALU | BPF_AND | BPF_K:
414                 case BPF_ALU | BPF_OR | BPF_X:
415                 case BPF_ALU | BPF_OR | BPF_K:
416                 case BPF_ALU | BPF_LSH | BPF_X:
417                 case BPF_ALU | BPF_LSH | BPF_K:
418                 case BPF_ALU | BPF_RSH | BPF_X:
419                 case BPF_ALU | BPF_RSH | BPF_K:
420                 case BPF_ALU | BPF_XOR | BPF_X:
421                 case BPF_ALU | BPF_XOR | BPF_K:
422                 case BPF_ALU | BPF_MUL | BPF_X:
423                 case BPF_ALU | BPF_MUL | BPF_K:
424                 case BPF_ALU | BPF_DIV | BPF_X:
425                 case BPF_ALU | BPF_DIV | BPF_K:
426                 case BPF_ALU | BPF_MOD | BPF_X:
427                 case BPF_ALU | BPF_MOD | BPF_K:
428                 case BPF_ALU | BPF_NEG:
429                 case BPF_LD | BPF_ABS | BPF_W:
430                 case BPF_LD | BPF_ABS | BPF_H:
431                 case BPF_LD | BPF_ABS | BPF_B:
432                 case BPF_LD | BPF_IND | BPF_W:
433                 case BPF_LD | BPF_IND | BPF_H:
434                 case BPF_LD | BPF_IND | BPF_B:
435                         /* Check for overloaded BPF extension and
436                          * directly convert it if found, otherwise
437                          * just move on with mapping.
438                          */
439                         if (BPF_CLASS(fp->code) == BPF_LD &&
440                             BPF_MODE(fp->code) == BPF_ABS &&
441                             convert_bpf_extensions(fp, &insn))
442                                 break;
443
444                         *insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
445                         break;
446
447                 /* Jump transformation cannot use BPF block macros
448                  * everywhere as offset calculation and target updates
449                  * require a bit more work than the rest, i.e. jump
450                  * opcodes map as-is, but offsets need adjustment.
451                  */
452
453 #define BPF_EMIT_JMP                                                    \
454         do {                                                            \
455                 if (target >= len || target < 0)                        \
456                         goto err;                                       \
457                 insn->off = addrs ? addrs[target] - addrs[i] - 1 : 0;   \
458                 /* Adjust pc relative offset for 2nd or 3rd insn. */    \
459                 insn->off -= insn - tmp_insns;                          \
460         } while (0)
461
462                 case BPF_JMP | BPF_JA:
463                         target = i + fp->k + 1;
464                         insn->code = fp->code;
465                         BPF_EMIT_JMP;
466                         break;
467
468                 case BPF_JMP | BPF_JEQ | BPF_K:
469                 case BPF_JMP | BPF_JEQ | BPF_X:
470                 case BPF_JMP | BPF_JSET | BPF_K:
471                 case BPF_JMP | BPF_JSET | BPF_X:
472                 case BPF_JMP | BPF_JGT | BPF_K:
473                 case BPF_JMP | BPF_JGT | BPF_X:
474                 case BPF_JMP | BPF_JGE | BPF_K:
475                 case BPF_JMP | BPF_JGE | BPF_X:
476                         if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
477                                 /* BPF immediates are signed, zero extend
478                                  * immediate into tmp register and use it
479                                  * in compare insn.
480                                  */
481                                 *insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
482
483                                 insn->dst_reg = BPF_REG_A;
484                                 insn->src_reg = BPF_REG_TMP;
485                                 bpf_src = BPF_X;
486                         } else {
487                                 insn->dst_reg = BPF_REG_A;
488                                 insn->imm = fp->k;
489                                 bpf_src = BPF_SRC(fp->code);
490                                 insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
491                         }
492
493                         /* Common case where 'jump_false' is next insn. */
494                         if (fp->jf == 0) {
495                                 insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
496                                 target = i + fp->jt + 1;
497                                 BPF_EMIT_JMP;
498                                 break;
499                         }
500
501                         /* Convert JEQ into JNE when 'jump_true' is next insn. */
502                         if (fp->jt == 0 && BPF_OP(fp->code) == BPF_JEQ) {
503                                 insn->code = BPF_JMP | BPF_JNE | bpf_src;
504                                 target = i + fp->jf + 1;
505                                 BPF_EMIT_JMP;
506                                 break;
507                         }
508
509                         /* Other jumps are mapped into two insns: Jxx and JA. */
510                         target = i + fp->jt + 1;
511                         insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
512                         BPF_EMIT_JMP;
513                         insn++;
514
515                         insn->code = BPF_JMP | BPF_JA;
516                         target = i + fp->jf + 1;
517                         BPF_EMIT_JMP;
518                         break;
519
520                 /* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
521                 case BPF_LDX | BPF_MSH | BPF_B:
522                         /* tmp = A */
523                         *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_A);
524                         /* A = BPF_R0 = *(u8 *) (skb->data + K) */
525                         *insn++ = BPF_LD_ABS(BPF_B, fp->k);
526                         /* A &= 0xf */
527                         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
528                         /* A <<= 2 */
529                         *insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
530                         /* X = A */
531                         *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
532                         /* A = tmp */
533                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
534                         break;
535
536                 /* RET_K is remaped into 2 insns. RET_A case doesn't need an
537                  * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
538                  */
539                 case BPF_RET | BPF_A:
540                 case BPF_RET | BPF_K:
541                         if (BPF_RVAL(fp->code) == BPF_K)
542                                 *insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
543                                                         0, fp->k);
544                         *insn = BPF_EXIT_INSN();
545                         break;
546
547                 /* Store to stack. */
548                 case BPF_ST:
549                 case BPF_STX:
550                         *insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
551                                             BPF_ST ? BPF_REG_A : BPF_REG_X,
552                                             -(BPF_MEMWORDS - fp->k) * 4);
553                         break;
554
555                 /* Load from stack. */
556                 case BPF_LD | BPF_MEM:
557                 case BPF_LDX | BPF_MEM:
558                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
559                                             BPF_REG_A : BPF_REG_X, BPF_REG_FP,
560                                             -(BPF_MEMWORDS - fp->k) * 4);
561                         break;
562
563                 /* A = K or X = K */
564                 case BPF_LD | BPF_IMM:
565                 case BPF_LDX | BPF_IMM:
566                         *insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
567                                               BPF_REG_A : BPF_REG_X, fp->k);
568                         break;
569
570                 /* X = A */
571                 case BPF_MISC | BPF_TAX:
572                         *insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
573                         break;
574
575                 /* A = X */
576                 case BPF_MISC | BPF_TXA:
577                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
578                         break;
579
580                 /* A = skb->len or X = skb->len */
581                 case BPF_LD | BPF_W | BPF_LEN:
582                 case BPF_LDX | BPF_W | BPF_LEN:
583                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
584                                             BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
585                                             offsetof(struct sk_buff, len));
586                         break;
587
588                 /* Access seccomp_data fields. */
589                 case BPF_LDX | BPF_ABS | BPF_W:
590                         /* A = *(u32 *) (ctx + K) */
591                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
592                         break;
593
594                 /* Unknown instruction. */
595                 default:
596                         goto err;
597                 }
598
599                 insn++;
600                 if (new_prog)
601                         memcpy(new_insn, tmp_insns,
602                                sizeof(*insn) * (insn - tmp_insns));
603                 new_insn += insn - tmp_insns;
604         }
605
606         if (!new_prog) {
607                 /* Only calculating new length. */
608                 *new_len = new_insn - new_prog;
609                 return 0;
610         }
611
612         pass++;
613         if (new_flen != new_insn - new_prog) {
614                 new_flen = new_insn - new_prog;
615                 if (pass > 2)
616                         goto err;
617                 goto do_pass;
618         }
619
620         kfree(addrs);
621         BUG_ON(*new_len != new_flen);
622         return 0;
623 err:
624         kfree(addrs);
625         return -EINVAL;
626 }
627
628 /* Security:
629  *
630  * As we dont want to clear mem[] array for each packet going through
631  * __bpf_prog_run(), we check that filter loaded by user never try to read
632  * a cell if not previously written, and we check all branches to be sure
633  * a malicious user doesn't try to abuse us.
634  */
635 static int check_load_and_stores(const struct sock_filter *filter, int flen)
636 {
637         u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
638         int pc, ret = 0;
639
640         BUILD_BUG_ON(BPF_MEMWORDS > 16);
641
642         masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
643         if (!masks)
644                 return -ENOMEM;
645
646         memset(masks, 0xff, flen * sizeof(*masks));
647
648         for (pc = 0; pc < flen; pc++) {
649                 memvalid &= masks[pc];
650
651                 switch (filter[pc].code) {
652                 case BPF_ST:
653                 case BPF_STX:
654                         memvalid |= (1 << filter[pc].k);
655                         break;
656                 case BPF_LD | BPF_MEM:
657                 case BPF_LDX | BPF_MEM:
658                         if (!(memvalid & (1 << filter[pc].k))) {
659                                 ret = -EINVAL;
660                                 goto error;
661                         }
662                         break;
663                 case BPF_JMP | BPF_JA:
664                         /* A jump must set masks on target */
665                         masks[pc + 1 + filter[pc].k] &= memvalid;
666                         memvalid = ~0;
667                         break;
668                 case BPF_JMP | BPF_JEQ | BPF_K:
669                 case BPF_JMP | BPF_JEQ | BPF_X:
670                 case BPF_JMP | BPF_JGE | BPF_K:
671                 case BPF_JMP | BPF_JGE | BPF_X:
672                 case BPF_JMP | BPF_JGT | BPF_K:
673                 case BPF_JMP | BPF_JGT | BPF_X:
674                 case BPF_JMP | BPF_JSET | BPF_K:
675                 case BPF_JMP | BPF_JSET | BPF_X:
676                         /* A jump must set masks on targets */
677                         masks[pc + 1 + filter[pc].jt] &= memvalid;
678                         masks[pc + 1 + filter[pc].jf] &= memvalid;
679                         memvalid = ~0;
680                         break;
681                 }
682         }
683 error:
684         kfree(masks);
685         return ret;
686 }
687
688 static bool chk_code_allowed(u16 code_to_probe)
689 {
690         static const bool codes[] = {
691                 /* 32 bit ALU operations */
692                 [BPF_ALU | BPF_ADD | BPF_K] = true,
693                 [BPF_ALU | BPF_ADD | BPF_X] = true,
694                 [BPF_ALU | BPF_SUB | BPF_K] = true,
695                 [BPF_ALU | BPF_SUB | BPF_X] = true,
696                 [BPF_ALU | BPF_MUL | BPF_K] = true,
697                 [BPF_ALU | BPF_MUL | BPF_X] = true,
698                 [BPF_ALU | BPF_DIV | BPF_K] = true,
699                 [BPF_ALU | BPF_DIV | BPF_X] = true,
700                 [BPF_ALU | BPF_MOD | BPF_K] = true,
701                 [BPF_ALU | BPF_MOD | BPF_X] = true,
702                 [BPF_ALU | BPF_AND | BPF_K] = true,
703                 [BPF_ALU | BPF_AND | BPF_X] = true,
704                 [BPF_ALU | BPF_OR | BPF_K] = true,
705                 [BPF_ALU | BPF_OR | BPF_X] = true,
706                 [BPF_ALU | BPF_XOR | BPF_K] = true,
707                 [BPF_ALU | BPF_XOR | BPF_X] = true,
708                 [BPF_ALU | BPF_LSH | BPF_K] = true,
709                 [BPF_ALU | BPF_LSH | BPF_X] = true,
710                 [BPF_ALU | BPF_RSH | BPF_K] = true,
711                 [BPF_ALU | BPF_RSH | BPF_X] = true,
712                 [BPF_ALU | BPF_NEG] = true,
713                 /* Load instructions */
714                 [BPF_LD | BPF_W | BPF_ABS] = true,
715                 [BPF_LD | BPF_H | BPF_ABS] = true,
716                 [BPF_LD | BPF_B | BPF_ABS] = true,
717                 [BPF_LD | BPF_W | BPF_LEN] = true,
718                 [BPF_LD | BPF_W | BPF_IND] = true,
719                 [BPF_LD | BPF_H | BPF_IND] = true,
720                 [BPF_LD | BPF_B | BPF_IND] = true,
721                 [BPF_LD | BPF_IMM] = true,
722                 [BPF_LD | BPF_MEM] = true,
723                 [BPF_LDX | BPF_W | BPF_LEN] = true,
724                 [BPF_LDX | BPF_B | BPF_MSH] = true,
725                 [BPF_LDX | BPF_IMM] = true,
726                 [BPF_LDX | BPF_MEM] = true,
727                 /* Store instructions */
728                 [BPF_ST] = true,
729                 [BPF_STX] = true,
730                 /* Misc instructions */
731                 [BPF_MISC | BPF_TAX] = true,
732                 [BPF_MISC | BPF_TXA] = true,
733                 /* Return instructions */
734                 [BPF_RET | BPF_K] = true,
735                 [BPF_RET | BPF_A] = true,
736                 /* Jump instructions */
737                 [BPF_JMP | BPF_JA] = true,
738                 [BPF_JMP | BPF_JEQ | BPF_K] = true,
739                 [BPF_JMP | BPF_JEQ | BPF_X] = true,
740                 [BPF_JMP | BPF_JGE | BPF_K] = true,
741                 [BPF_JMP | BPF_JGE | BPF_X] = true,
742                 [BPF_JMP | BPF_JGT | BPF_K] = true,
743                 [BPF_JMP | BPF_JGT | BPF_X] = true,
744                 [BPF_JMP | BPF_JSET | BPF_K] = true,
745                 [BPF_JMP | BPF_JSET | BPF_X] = true,
746         };
747
748         if (code_to_probe >= ARRAY_SIZE(codes))
749                 return false;
750
751         return codes[code_to_probe];
752 }
753
754 static bool bpf_check_basics_ok(const struct sock_filter *filter,
755                                 unsigned int flen)
756 {
757         if (filter == NULL)
758                 return false;
759         if (flen == 0 || flen > BPF_MAXINSNS)
760                 return false;
761
762         return true;
763 }
764
765 /**
766  *      bpf_check_classic - verify socket filter code
767  *      @filter: filter to verify
768  *      @flen: length of filter
769  *
770  * Check the user's filter code. If we let some ugly
771  * filter code slip through kaboom! The filter must contain
772  * no references or jumps that are out of range, no illegal
773  * instructions, and must end with a RET instruction.
774  *
775  * All jumps are forward as they are not signed.
776  *
777  * Returns 0 if the rule set is legal or -EINVAL if not.
778  */
779 static int bpf_check_classic(const struct sock_filter *filter,
780                              unsigned int flen)
781 {
782         bool anc_found;
783         int pc;
784
785         /* Check the filter code now */
786         for (pc = 0; pc < flen; pc++) {
787                 const struct sock_filter *ftest = &filter[pc];
788
789                 /* May we actually operate on this code? */
790                 if (!chk_code_allowed(ftest->code))
791                         return -EINVAL;
792
793                 /* Some instructions need special checks */
794                 switch (ftest->code) {
795                 case BPF_ALU | BPF_DIV | BPF_K:
796                 case BPF_ALU | BPF_MOD | BPF_K:
797                         /* Check for division by zero */
798                         if (ftest->k == 0)
799                                 return -EINVAL;
800                         break;
801                 case BPF_ALU | BPF_LSH | BPF_K:
802                 case BPF_ALU | BPF_RSH | BPF_K:
803                         if (ftest->k >= 32)
804                                 return -EINVAL;
805                         break;
806                 case BPF_LD | BPF_MEM:
807                 case BPF_LDX | BPF_MEM:
808                 case BPF_ST:
809                 case BPF_STX:
810                         /* Check for invalid memory addresses */
811                         if (ftest->k >= BPF_MEMWORDS)
812                                 return -EINVAL;
813                         break;
814                 case BPF_JMP | BPF_JA:
815                         /* Note, the large ftest->k might cause loops.
816                          * Compare this with conditional jumps below,
817                          * where offsets are limited. --ANK (981016)
818                          */
819                         if (ftest->k >= (unsigned int)(flen - pc - 1))
820                                 return -EINVAL;
821                         break;
822                 case BPF_JMP | BPF_JEQ | BPF_K:
823                 case BPF_JMP | BPF_JEQ | BPF_X:
824                 case BPF_JMP | BPF_JGE | BPF_K:
825                 case BPF_JMP | BPF_JGE | BPF_X:
826                 case BPF_JMP | BPF_JGT | BPF_K:
827                 case BPF_JMP | BPF_JGT | BPF_X:
828                 case BPF_JMP | BPF_JSET | BPF_K:
829                 case BPF_JMP | BPF_JSET | BPF_X:
830                         /* Both conditionals must be safe */
831                         if (pc + ftest->jt + 1 >= flen ||
832                             pc + ftest->jf + 1 >= flen)
833                                 return -EINVAL;
834                         break;
835                 case BPF_LD | BPF_W | BPF_ABS:
836                 case BPF_LD | BPF_H | BPF_ABS:
837                 case BPF_LD | BPF_B | BPF_ABS:
838                         anc_found = false;
839                         if (bpf_anc_helper(ftest) & BPF_ANC)
840                                 anc_found = true;
841                         /* Ancillary operation unknown or unsupported */
842                         if (anc_found == false && ftest->k >= SKF_AD_OFF)
843                                 return -EINVAL;
844                 }
845         }
846
847         /* Last instruction must be a RET code */
848         switch (filter[flen - 1].code) {
849         case BPF_RET | BPF_K:
850         case BPF_RET | BPF_A:
851                 return check_load_and_stores(filter, flen);
852         }
853
854         return -EINVAL;
855 }
856
857 static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
858                                       const struct sock_fprog *fprog)
859 {
860         unsigned int fsize = bpf_classic_proglen(fprog);
861         struct sock_fprog_kern *fkprog;
862
863         fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
864         if (!fp->orig_prog)
865                 return -ENOMEM;
866
867         fkprog = fp->orig_prog;
868         fkprog->len = fprog->len;
869
870         fkprog->filter = kmemdup(fp->insns, fsize,
871                                  GFP_KERNEL | __GFP_NOWARN);
872         if (!fkprog->filter) {
873                 kfree(fp->orig_prog);
874                 return -ENOMEM;
875         }
876
877         return 0;
878 }
879
880 static void bpf_release_orig_filter(struct bpf_prog *fp)
881 {
882         struct sock_fprog_kern *fprog = fp->orig_prog;
883
884         if (fprog) {
885                 kfree(fprog->filter);
886                 kfree(fprog);
887         }
888 }
889
890 static void __bpf_prog_release(struct bpf_prog *prog)
891 {
892         if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
893                 bpf_prog_put(prog);
894         } else {
895                 bpf_release_orig_filter(prog);
896                 bpf_prog_free(prog);
897         }
898 }
899
900 static void __sk_filter_release(struct sk_filter *fp)
901 {
902         __bpf_prog_release(fp->prog);
903         kfree(fp);
904 }
905
906 /**
907  *      sk_filter_release_rcu - Release a socket filter by rcu_head
908  *      @rcu: rcu_head that contains the sk_filter to free
909  */
910 static void sk_filter_release_rcu(struct rcu_head *rcu)
911 {
912         struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
913
914         __sk_filter_release(fp);
915 }
916
917 /**
918  *      sk_filter_release - release a socket filter
919  *      @fp: filter to remove
920  *
921  *      Remove a filter from a socket and release its resources.
922  */
923 static void sk_filter_release(struct sk_filter *fp)
924 {
925         if (atomic_dec_and_test(&fp->refcnt))
926                 call_rcu(&fp->rcu, sk_filter_release_rcu);
927 }
928
929 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
930 {
931         u32 filter_size = bpf_prog_size(fp->prog->len);
932
933         atomic_sub(filter_size, &sk->sk_omem_alloc);
934         sk_filter_release(fp);
935 }
936
937 /* try to charge the socket memory if there is space available
938  * return true on success
939  */
940 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
941 {
942         u32 filter_size = bpf_prog_size(fp->prog->len);
943
944         /* same check as in sock_kmalloc() */
945         if (filter_size <= sysctl_optmem_max &&
946             atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
947                 atomic_inc(&fp->refcnt);
948                 atomic_add(filter_size, &sk->sk_omem_alloc);
949                 return true;
950         }
951         return false;
952 }
953
954 static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
955 {
956         struct sock_filter *old_prog;
957         struct bpf_prog *old_fp;
958         int err, new_len, old_len = fp->len;
959
960         /* We are free to overwrite insns et al right here as it
961          * won't be used at this point in time anymore internally
962          * after the migration to the internal BPF instruction
963          * representation.
964          */
965         BUILD_BUG_ON(sizeof(struct sock_filter) !=
966                      sizeof(struct bpf_insn));
967
968         /* Conversion cannot happen on overlapping memory areas,
969          * so we need to keep the user BPF around until the 2nd
970          * pass. At this time, the user BPF is stored in fp->insns.
971          */
972         old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
973                            GFP_KERNEL | __GFP_NOWARN);
974         if (!old_prog) {
975                 err = -ENOMEM;
976                 goto out_err;
977         }
978
979         /* 1st pass: calculate the new program length. */
980         err = bpf_convert_filter(old_prog, old_len, NULL, &new_len);
981         if (err)
982                 goto out_err_free;
983
984         /* Expand fp for appending the new filter representation. */
985         old_fp = fp;
986         fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
987         if (!fp) {
988                 /* The old_fp is still around in case we couldn't
989                  * allocate new memory, so uncharge on that one.
990                  */
991                 fp = old_fp;
992                 err = -ENOMEM;
993                 goto out_err_free;
994         }
995
996         fp->len = new_len;
997
998         /* 2nd pass: remap sock_filter insns into bpf_insn insns. */
999         err = bpf_convert_filter(old_prog, old_len, fp->insnsi, &new_len);
1000         if (err)
1001                 /* 2nd bpf_convert_filter() can fail only if it fails
1002                  * to allocate memory, remapping must succeed. Note,
1003                  * that at this time old_fp has already been released
1004                  * by krealloc().
1005                  */
1006                 goto out_err_free;
1007
1008         /* We are guaranteed to never error here with cBPF to eBPF
1009          * transitions, since there's no issue with type compatibility
1010          * checks on program arrays.
1011          */
1012         fp = bpf_prog_select_runtime(fp, &err);
1013
1014         kfree(old_prog);
1015         return fp;
1016
1017 out_err_free:
1018         kfree(old_prog);
1019 out_err:
1020         __bpf_prog_release(fp);
1021         return ERR_PTR(err);
1022 }
1023
1024 static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
1025                                            bpf_aux_classic_check_t trans)
1026 {
1027         int err;
1028
1029         fp->bpf_func = NULL;
1030         fp->jited = 0;
1031
1032         err = bpf_check_classic(fp->insns, fp->len);
1033         if (err) {
1034                 __bpf_prog_release(fp);
1035                 return ERR_PTR(err);
1036         }
1037
1038         /* There might be additional checks and transformations
1039          * needed on classic filters, f.e. in case of seccomp.
1040          */
1041         if (trans) {
1042                 err = trans(fp->insns, fp->len);
1043                 if (err) {
1044                         __bpf_prog_release(fp);
1045                         return ERR_PTR(err);
1046                 }
1047         }
1048
1049         /* Probe if we can JIT compile the filter and if so, do
1050          * the compilation of the filter.
1051          */
1052         bpf_jit_compile(fp);
1053
1054         /* JIT compiler couldn't process this filter, so do the
1055          * internal BPF translation for the optimized interpreter.
1056          */
1057         if (!fp->jited)
1058                 fp = bpf_migrate_filter(fp);
1059
1060         return fp;
1061 }
1062
1063 /**
1064  *      bpf_prog_create - create an unattached filter
1065  *      @pfp: the unattached filter that is created
1066  *      @fprog: the filter program
1067  *
1068  * Create a filter independent of any socket. We first run some
1069  * sanity checks on it to make sure it does not explode on us later.
1070  * If an error occurs or there is insufficient memory for the filter
1071  * a negative errno code is returned. On success the return is zero.
1072  */
1073 int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1074 {
1075         unsigned int fsize = bpf_classic_proglen(fprog);
1076         struct bpf_prog *fp;
1077
1078         /* Make sure new filter is there and in the right amounts. */
1079         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1080                 return -EINVAL;
1081
1082         fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1083         if (!fp)
1084                 return -ENOMEM;
1085
1086         memcpy(fp->insns, fprog->filter, fsize);
1087
1088         fp->len = fprog->len;
1089         /* Since unattached filters are not copied back to user
1090          * space through sk_get_filter(), we do not need to hold
1091          * a copy here, and can spare us the work.
1092          */
1093         fp->orig_prog = NULL;
1094
1095         /* bpf_prepare_filter() already takes care of freeing
1096          * memory in case something goes wrong.
1097          */
1098         fp = bpf_prepare_filter(fp, NULL);
1099         if (IS_ERR(fp))
1100                 return PTR_ERR(fp);
1101
1102         *pfp = fp;
1103         return 0;
1104 }
1105 EXPORT_SYMBOL_GPL(bpf_prog_create);
1106
1107 /**
1108  *      bpf_prog_create_from_user - create an unattached filter from user buffer
1109  *      @pfp: the unattached filter that is created
1110  *      @fprog: the filter program
1111  *      @trans: post-classic verifier transformation handler
1112  *      @save_orig: save classic BPF program
1113  *
1114  * This function effectively does the same as bpf_prog_create(), only
1115  * that it builds up its insns buffer from user space provided buffer.
1116  * It also allows for passing a bpf_aux_classic_check_t handler.
1117  */
1118 int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1119                               bpf_aux_classic_check_t trans, bool save_orig)
1120 {
1121         unsigned int fsize = bpf_classic_proglen(fprog);
1122         struct bpf_prog *fp;
1123         int err;
1124
1125         /* Make sure new filter is there and in the right amounts. */
1126         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1127                 return -EINVAL;
1128
1129         fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1130         if (!fp)
1131                 return -ENOMEM;
1132
1133         if (copy_from_user(fp->insns, fprog->filter, fsize)) {
1134                 __bpf_prog_free(fp);
1135                 return -EFAULT;
1136         }
1137
1138         fp->len = fprog->len;
1139         fp->orig_prog = NULL;
1140
1141         if (save_orig) {
1142                 err = bpf_prog_store_orig_filter(fp, fprog);
1143                 if (err) {
1144                         __bpf_prog_free(fp);
1145                         return -ENOMEM;
1146                 }
1147         }
1148
1149         /* bpf_prepare_filter() already takes care of freeing
1150          * memory in case something goes wrong.
1151          */
1152         fp = bpf_prepare_filter(fp, trans);
1153         if (IS_ERR(fp))
1154                 return PTR_ERR(fp);
1155
1156         *pfp = fp;
1157         return 0;
1158 }
1159 EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1160
1161 void bpf_prog_destroy(struct bpf_prog *fp)
1162 {
1163         __bpf_prog_release(fp);
1164 }
1165 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1166
1167 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1168 {
1169         struct sk_filter *fp, *old_fp;
1170
1171         fp = kmalloc(sizeof(*fp), GFP_KERNEL);
1172         if (!fp)
1173                 return -ENOMEM;
1174
1175         fp->prog = prog;
1176         atomic_set(&fp->refcnt, 0);
1177
1178         if (!sk_filter_charge(sk, fp)) {
1179                 kfree(fp);
1180                 return -ENOMEM;
1181         }
1182
1183         old_fp = rcu_dereference_protected(sk->sk_filter,
1184                                            lockdep_sock_is_held(sk));
1185         rcu_assign_pointer(sk->sk_filter, fp);
1186
1187         if (old_fp)
1188                 sk_filter_uncharge(sk, old_fp);
1189
1190         return 0;
1191 }
1192
1193 static int __reuseport_attach_prog(struct bpf_prog *prog, struct sock *sk)
1194 {
1195         struct bpf_prog *old_prog;
1196         int err;
1197
1198         if (bpf_prog_size(prog->len) > sysctl_optmem_max)
1199                 return -ENOMEM;
1200
1201         if (sk_unhashed(sk) && sk->sk_reuseport) {
1202                 err = reuseport_alloc(sk);
1203                 if (err)
1204                         return err;
1205         } else if (!rcu_access_pointer(sk->sk_reuseport_cb)) {
1206                 /* The socket wasn't bound with SO_REUSEPORT */
1207                 return -EINVAL;
1208         }
1209
1210         old_prog = reuseport_attach_prog(sk, prog);
1211         if (old_prog)
1212                 bpf_prog_destroy(old_prog);
1213
1214         return 0;
1215 }
1216
1217 static
1218 struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
1219 {
1220         unsigned int fsize = bpf_classic_proglen(fprog);
1221         struct bpf_prog *prog;
1222         int err;
1223
1224         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1225                 return ERR_PTR(-EPERM);
1226
1227         /* Make sure new filter is there and in the right amounts. */
1228         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1229                 return ERR_PTR(-EINVAL);
1230
1231         prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1232         if (!prog)
1233                 return ERR_PTR(-ENOMEM);
1234
1235         if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1236                 __bpf_prog_free(prog);
1237                 return ERR_PTR(-EFAULT);
1238         }
1239
1240         prog->len = fprog->len;
1241
1242         err = bpf_prog_store_orig_filter(prog, fprog);
1243         if (err) {
1244                 __bpf_prog_free(prog);
1245                 return ERR_PTR(-ENOMEM);
1246         }
1247
1248         /* bpf_prepare_filter() already takes care of freeing
1249          * memory in case something goes wrong.
1250          */
1251         return bpf_prepare_filter(prog, NULL);
1252 }
1253
1254 /**
1255  *      sk_attach_filter - attach a socket filter
1256  *      @fprog: the filter program
1257  *      @sk: the socket to use
1258  *
1259  * Attach the user's filter code. We first run some sanity checks on
1260  * it to make sure it does not explode on us later. If an error
1261  * occurs or there is insufficient memory for the filter a negative
1262  * errno code is returned. On success the return is zero.
1263  */
1264 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1265 {
1266         struct bpf_prog *prog = __get_filter(fprog, sk);
1267         int err;
1268
1269         if (IS_ERR(prog))
1270                 return PTR_ERR(prog);
1271
1272         err = __sk_attach_prog(prog, sk);
1273         if (err < 0) {
1274                 __bpf_prog_release(prog);
1275                 return err;
1276         }
1277
1278         return 0;
1279 }
1280 EXPORT_SYMBOL_GPL(sk_attach_filter);
1281
1282 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1283 {
1284         struct bpf_prog *prog = __get_filter(fprog, sk);
1285         int err;
1286
1287         if (IS_ERR(prog))
1288                 return PTR_ERR(prog);
1289
1290         err = __reuseport_attach_prog(prog, sk);
1291         if (err < 0) {
1292                 __bpf_prog_release(prog);
1293                 return err;
1294         }
1295
1296         return 0;
1297 }
1298
1299 static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
1300 {
1301         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1302                 return ERR_PTR(-EPERM);
1303
1304         return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1305 }
1306
1307 int sk_attach_bpf(u32 ufd, struct sock *sk)
1308 {
1309         struct bpf_prog *prog = __get_bpf(ufd, sk);
1310         int err;
1311
1312         if (IS_ERR(prog))
1313                 return PTR_ERR(prog);
1314
1315         err = __sk_attach_prog(prog, sk);
1316         if (err < 0) {
1317                 bpf_prog_put(prog);
1318                 return err;
1319         }
1320
1321         return 0;
1322 }
1323
1324 int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
1325 {
1326         struct bpf_prog *prog = __get_bpf(ufd, sk);
1327         int err;
1328
1329         if (IS_ERR(prog))
1330                 return PTR_ERR(prog);
1331
1332         err = __reuseport_attach_prog(prog, sk);
1333         if (err < 0) {
1334                 bpf_prog_put(prog);
1335                 return err;
1336         }
1337
1338         return 0;
1339 }
1340
1341 struct bpf_scratchpad {
1342         union {
1343                 __be32 diff[MAX_BPF_STACK / sizeof(__be32)];
1344                 u8     buff[MAX_BPF_STACK];
1345         };
1346 };
1347
1348 static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp);
1349
1350 static inline int __bpf_try_make_writable(struct sk_buff *skb,
1351                                           unsigned int write_len)
1352 {
1353         return skb_ensure_writable(skb, write_len);
1354 }
1355
1356 static inline int bpf_try_make_writable(struct sk_buff *skb,
1357                                         unsigned int write_len)
1358 {
1359         int err = __bpf_try_make_writable(skb, write_len);
1360
1361         bpf_compute_data_end(skb);
1362         return err;
1363 }
1364
1365 static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
1366 {
1367         if (skb_at_tc_ingress(skb))
1368                 skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1369 }
1370
1371 static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
1372 {
1373         if (skb_at_tc_ingress(skb))
1374                 skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1375 }
1376
1377 BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
1378            const void *, from, u32, len, u64, flags)
1379 {
1380         void *ptr;
1381
1382         if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1383                 return -EINVAL;
1384         if (unlikely(offset > 0xffff))
1385                 return -EFAULT;
1386         if (unlikely(bpf_try_make_writable(skb, offset + len)))
1387                 return -EFAULT;
1388
1389         ptr = skb->data + offset;
1390         if (flags & BPF_F_RECOMPUTE_CSUM)
1391                 __skb_postpull_rcsum(skb, ptr, len, offset);
1392
1393         memcpy(ptr, from, len);
1394
1395         if (flags & BPF_F_RECOMPUTE_CSUM)
1396                 __skb_postpush_rcsum(skb, ptr, len, offset);
1397         if (flags & BPF_F_INVALIDATE_HASH)
1398                 skb_clear_hash(skb);
1399
1400         return 0;
1401 }
1402
1403 static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1404         .func           = bpf_skb_store_bytes,
1405         .gpl_only       = false,
1406         .ret_type       = RET_INTEGER,
1407         .arg1_type      = ARG_PTR_TO_CTX,
1408         .arg2_type      = ARG_ANYTHING,
1409         .arg3_type      = ARG_PTR_TO_STACK,
1410         .arg4_type      = ARG_CONST_STACK_SIZE,
1411         .arg5_type      = ARG_ANYTHING,
1412 };
1413
1414 BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
1415            void *, to, u32, len)
1416 {
1417         void *ptr;
1418
1419         if (unlikely(offset > 0xffff))
1420                 goto err_clear;
1421
1422         ptr = skb_header_pointer(skb, offset, len, to);
1423         if (unlikely(!ptr))
1424                 goto err_clear;
1425         if (ptr != to)
1426                 memcpy(to, ptr, len);
1427
1428         return 0;
1429 err_clear:
1430         memset(to, 0, len);
1431         return -EFAULT;
1432 }
1433
1434 static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1435         .func           = bpf_skb_load_bytes,
1436         .gpl_only       = false,
1437         .ret_type       = RET_INTEGER,
1438         .arg1_type      = ARG_PTR_TO_CTX,
1439         .arg2_type      = ARG_ANYTHING,
1440         .arg3_type      = ARG_PTR_TO_RAW_STACK,
1441         .arg4_type      = ARG_CONST_STACK_SIZE,
1442 };
1443
1444 BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
1445            u64, from, u64, to, u64, flags)
1446 {
1447         __sum16 *ptr;
1448
1449         if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
1450                 return -EINVAL;
1451         if (unlikely(offset > 0xffff || offset & 1))
1452                 return -EFAULT;
1453         if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1454                 return -EFAULT;
1455
1456         ptr = (__sum16 *)(skb->data + offset);
1457         switch (flags & BPF_F_HDR_FIELD_MASK) {
1458         case 0:
1459                 if (unlikely(from != 0))
1460                         return -EINVAL;
1461
1462                 csum_replace_by_diff(ptr, to);
1463                 break;
1464         case 2:
1465                 csum_replace2(ptr, from, to);
1466                 break;
1467         case 4:
1468                 csum_replace4(ptr, from, to);
1469                 break;
1470         default:
1471                 return -EINVAL;
1472         }
1473
1474         return 0;
1475 }
1476
1477 static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1478         .func           = bpf_l3_csum_replace,
1479         .gpl_only       = false,
1480         .ret_type       = RET_INTEGER,
1481         .arg1_type      = ARG_PTR_TO_CTX,
1482         .arg2_type      = ARG_ANYTHING,
1483         .arg3_type      = ARG_ANYTHING,
1484         .arg4_type      = ARG_ANYTHING,
1485         .arg5_type      = ARG_ANYTHING,
1486 };
1487
1488 BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
1489            u64, from, u64, to, u64, flags)
1490 {
1491         bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1492         bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1493         __sum16 *ptr;
1494
1495         if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_PSEUDO_HDR |
1496                                BPF_F_HDR_FIELD_MASK)))
1497                 return -EINVAL;
1498         if (unlikely(offset > 0xffff || offset & 1))
1499                 return -EFAULT;
1500         if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1501                 return -EFAULT;
1502
1503         ptr = (__sum16 *)(skb->data + offset);
1504         if (is_mmzero && !*ptr)
1505                 return 0;
1506
1507         switch (flags & BPF_F_HDR_FIELD_MASK) {
1508         case 0:
1509                 if (unlikely(from != 0))
1510                         return -EINVAL;
1511
1512                 inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
1513                 break;
1514         case 2:
1515                 inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
1516                 break;
1517         case 4:
1518                 inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
1519                 break;
1520         default:
1521                 return -EINVAL;
1522         }
1523
1524         if (is_mmzero && !*ptr)
1525                 *ptr = CSUM_MANGLED_0;
1526         return 0;
1527 }
1528
1529 static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1530         .func           = bpf_l4_csum_replace,
1531         .gpl_only       = false,
1532         .ret_type       = RET_INTEGER,
1533         .arg1_type      = ARG_PTR_TO_CTX,
1534         .arg2_type      = ARG_ANYTHING,
1535         .arg3_type      = ARG_ANYTHING,
1536         .arg4_type      = ARG_ANYTHING,
1537         .arg5_type      = ARG_ANYTHING,
1538 };
1539
1540 BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
1541            __be32 *, to, u32, to_size, __wsum, seed)
1542 {
1543         struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1544         u32 diff_size = from_size + to_size;
1545         int i, j = 0;
1546
1547         /* This is quite flexible, some examples:
1548          *
1549          * from_size == 0, to_size > 0,  seed := csum --> pushing data
1550          * from_size > 0,  to_size == 0, seed := csum --> pulling data
1551          * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
1552          *
1553          * Even for diffing, from_size and to_size don't need to be equal.
1554          */
1555         if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) ||
1556                      diff_size > sizeof(sp->diff)))
1557                 return -EINVAL;
1558
1559         for (i = 0; i < from_size / sizeof(__be32); i++, j++)
1560                 sp->diff[j] = ~from[i];
1561         for (i = 0; i <   to_size / sizeof(__be32); i++, j++)
1562                 sp->diff[j] = to[i];
1563
1564         return csum_partial(sp->diff, diff_size, seed);
1565 }
1566
1567 static const struct bpf_func_proto bpf_csum_diff_proto = {
1568         .func           = bpf_csum_diff,
1569         .gpl_only       = false,
1570         .ret_type       = RET_INTEGER,
1571         .arg1_type      = ARG_PTR_TO_STACK,
1572         .arg2_type      = ARG_CONST_STACK_SIZE_OR_ZERO,
1573         .arg3_type      = ARG_PTR_TO_STACK,
1574         .arg4_type      = ARG_CONST_STACK_SIZE_OR_ZERO,
1575         .arg5_type      = ARG_ANYTHING,
1576 };
1577
1578 static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
1579 {
1580         return dev_forward_skb(dev, skb);
1581 }
1582
1583 static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
1584 {
1585         int ret;
1586
1587         if (unlikely(__this_cpu_read(xmit_recursion) > XMIT_RECURSION_LIMIT)) {
1588                 net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
1589                 kfree_skb(skb);
1590                 return -ENETDOWN;
1591         }
1592
1593         skb->dev = dev;
1594
1595         __this_cpu_inc(xmit_recursion);
1596         ret = dev_queue_xmit(skb);
1597         __this_cpu_dec(xmit_recursion);
1598
1599         return ret;
1600 }
1601
1602 BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
1603 {
1604         struct net_device *dev;
1605
1606         if (unlikely(flags & ~(BPF_F_INGRESS)))
1607                 return -EINVAL;
1608
1609         dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
1610         if (unlikely(!dev))
1611                 return -EINVAL;
1612
1613         skb = skb_clone(skb, GFP_ATOMIC);
1614         if (unlikely(!skb))
1615                 return -ENOMEM;
1616
1617         bpf_push_mac_rcsum(skb);
1618
1619         return flags & BPF_F_INGRESS ?
1620                __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
1621 }
1622
1623 static const struct bpf_func_proto bpf_clone_redirect_proto = {
1624         .func           = bpf_clone_redirect,
1625         .gpl_only       = false,
1626         .ret_type       = RET_INTEGER,
1627         .arg1_type      = ARG_PTR_TO_CTX,
1628         .arg2_type      = ARG_ANYTHING,
1629         .arg3_type      = ARG_ANYTHING,
1630 };
1631
1632 struct redirect_info {
1633         u32 ifindex;
1634         u32 flags;
1635 };
1636
1637 static DEFINE_PER_CPU(struct redirect_info, redirect_info);
1638
1639 BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
1640 {
1641         struct redirect_info *ri = this_cpu_ptr(&redirect_info);
1642
1643         if (unlikely(flags & ~(BPF_F_INGRESS)))
1644                 return TC_ACT_SHOT;
1645
1646         ri->ifindex = ifindex;
1647         ri->flags = flags;
1648
1649         return TC_ACT_REDIRECT;
1650 }
1651
1652 int skb_do_redirect(struct sk_buff *skb)
1653 {
1654         struct redirect_info *ri = this_cpu_ptr(&redirect_info);
1655         struct net_device *dev;
1656
1657         dev = dev_get_by_index_rcu(dev_net(skb->dev), ri->ifindex);
1658         ri->ifindex = 0;
1659         if (unlikely(!dev)) {
1660                 kfree_skb(skb);
1661                 return -EINVAL;
1662         }
1663
1664         bpf_push_mac_rcsum(skb);
1665
1666         return ri->flags & BPF_F_INGRESS ?
1667                __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
1668 }
1669
1670 static const struct bpf_func_proto bpf_redirect_proto = {
1671         .func           = bpf_redirect,
1672         .gpl_only       = false,
1673         .ret_type       = RET_INTEGER,
1674         .arg1_type      = ARG_ANYTHING,
1675         .arg2_type      = ARG_ANYTHING,
1676 };
1677
1678 BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
1679 {
1680         return task_get_classid(skb);
1681 }
1682
1683 static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
1684         .func           = bpf_get_cgroup_classid,
1685         .gpl_only       = false,
1686         .ret_type       = RET_INTEGER,
1687         .arg1_type      = ARG_PTR_TO_CTX,
1688 };
1689
1690 BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
1691 {
1692         return dst_tclassid(skb);
1693 }
1694
1695 static const struct bpf_func_proto bpf_get_route_realm_proto = {
1696         .func           = bpf_get_route_realm,
1697         .gpl_only       = false,
1698         .ret_type       = RET_INTEGER,
1699         .arg1_type      = ARG_PTR_TO_CTX,
1700 };
1701
1702 BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
1703 {
1704         /* If skb_clear_hash() was called due to mangling, we can
1705          * trigger SW recalculation here. Later access to hash
1706          * can then use the inline skb->hash via context directly
1707          * instead of calling this helper again.
1708          */
1709         return skb_get_hash(skb);
1710 }
1711
1712 static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
1713         .func           = bpf_get_hash_recalc,
1714         .gpl_only       = false,
1715         .ret_type       = RET_INTEGER,
1716         .arg1_type      = ARG_PTR_TO_CTX,
1717 };
1718
1719 BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
1720            u16, vlan_tci)
1721 {
1722         int ret;
1723
1724         if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
1725                      vlan_proto != htons(ETH_P_8021AD)))
1726                 vlan_proto = htons(ETH_P_8021Q);
1727
1728         bpf_push_mac_rcsum(skb);
1729         ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
1730         bpf_pull_mac_rcsum(skb);
1731
1732         bpf_compute_data_end(skb);
1733         return ret;
1734 }
1735
1736 const struct bpf_func_proto bpf_skb_vlan_push_proto = {
1737         .func           = bpf_skb_vlan_push,
1738         .gpl_only       = false,
1739         .ret_type       = RET_INTEGER,
1740         .arg1_type      = ARG_PTR_TO_CTX,
1741         .arg2_type      = ARG_ANYTHING,
1742         .arg3_type      = ARG_ANYTHING,
1743 };
1744 EXPORT_SYMBOL_GPL(bpf_skb_vlan_push_proto);
1745
1746 BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
1747 {
1748         int ret;
1749
1750         bpf_push_mac_rcsum(skb);
1751         ret = skb_vlan_pop(skb);
1752         bpf_pull_mac_rcsum(skb);
1753
1754         bpf_compute_data_end(skb);
1755         return ret;
1756 }
1757
1758 const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
1759         .func           = bpf_skb_vlan_pop,
1760         .gpl_only       = false,
1761         .ret_type       = RET_INTEGER,
1762         .arg1_type      = ARG_PTR_TO_CTX,
1763 };
1764 EXPORT_SYMBOL_GPL(bpf_skb_vlan_pop_proto);
1765
1766 static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
1767 {
1768         /* Caller already did skb_cow() with len as headroom,
1769          * so no need to do it here.
1770          */
1771         skb_push(skb, len);
1772         memmove(skb->data, skb->data + len, off);
1773         memset(skb->data + off, 0, len);
1774
1775         /* No skb_postpush_rcsum(skb, skb->data + off, len)
1776          * needed here as it does not change the skb->csum
1777          * result for checksum complete when summing over
1778          * zeroed blocks.
1779          */
1780         return 0;
1781 }
1782
1783 static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
1784 {
1785         /* skb_ensure_writable() is not needed here, as we're
1786          * already working on an uncloned skb.
1787          */
1788         if (unlikely(!pskb_may_pull(skb, off + len)))
1789                 return -ENOMEM;
1790
1791         skb_postpull_rcsum(skb, skb->data + off, len);
1792         memmove(skb->data + len, skb->data, off);
1793         __skb_pull(skb, len);
1794
1795         return 0;
1796 }
1797
1798 static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
1799 {
1800         bool trans_same = skb->transport_header == skb->network_header;
1801         int ret;
1802
1803         /* There's no need for __skb_push()/__skb_pull() pair to
1804          * get to the start of the mac header as we're guaranteed
1805          * to always start from here under eBPF.
1806          */
1807         ret = bpf_skb_generic_push(skb, off, len);
1808         if (likely(!ret)) {
1809                 skb->mac_header -= len;
1810                 skb->network_header -= len;
1811                 if (trans_same)
1812                         skb->transport_header = skb->network_header;
1813         }
1814
1815         return ret;
1816 }
1817
1818 static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
1819 {
1820         bool trans_same = skb->transport_header == skb->network_header;
1821         int ret;
1822
1823         /* Same here, __skb_push()/__skb_pull() pair not needed. */
1824         ret = bpf_skb_generic_pop(skb, off, len);
1825         if (likely(!ret)) {
1826                 skb->mac_header += len;
1827                 skb->network_header += len;
1828                 if (trans_same)
1829                         skb->transport_header = skb->network_header;
1830         }
1831
1832         return ret;
1833 }
1834
1835 static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
1836 {
1837         const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
1838         u32 off = skb->network_header - skb->mac_header;
1839         int ret;
1840
1841         ret = skb_cow(skb, len_diff);
1842         if (unlikely(ret < 0))
1843                 return ret;
1844
1845         ret = bpf_skb_net_hdr_push(skb, off, len_diff);
1846         if (unlikely(ret < 0))
1847                 return ret;
1848
1849         if (skb_is_gso(skb)) {
1850                 /* SKB_GSO_UDP stays as is. SKB_GSO_TCPV4 needs to
1851                  * be changed into SKB_GSO_TCPV6.
1852                  */
1853                 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
1854                         skb_shinfo(skb)->gso_type &= ~SKB_GSO_TCPV4;
1855                         skb_shinfo(skb)->gso_type |=  SKB_GSO_TCPV6;
1856                 }
1857
1858                 /* Due to IPv6 header, MSS needs to be downgraded. */
1859                 skb_shinfo(skb)->gso_size -= len_diff;
1860                 /* Header must be checked, and gso_segs recomputed. */
1861                 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1862                 skb_shinfo(skb)->gso_segs = 0;
1863         }
1864
1865         skb->protocol = htons(ETH_P_IPV6);
1866         skb_clear_hash(skb);
1867
1868         return 0;
1869 }
1870
1871 static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
1872 {
1873         const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
1874         u32 off = skb->network_header - skb->mac_header;
1875         int ret;
1876
1877         ret = skb_unclone(skb, GFP_ATOMIC);
1878         if (unlikely(ret < 0))
1879                 return ret;
1880
1881         ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
1882         if (unlikely(ret < 0))
1883                 return ret;
1884
1885         if (skb_is_gso(skb)) {
1886                 /* SKB_GSO_UDP stays as is. SKB_GSO_TCPV6 needs to
1887                  * be changed into SKB_GSO_TCPV4.
1888                  */
1889                 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) {
1890                         skb_shinfo(skb)->gso_type &= ~SKB_GSO_TCPV6;
1891                         skb_shinfo(skb)->gso_type |=  SKB_GSO_TCPV4;
1892                 }
1893
1894                 /* Due to IPv4 header, MSS can be upgraded. */
1895                 skb_shinfo(skb)->gso_size += len_diff;
1896                 /* Header must be checked, and gso_segs recomputed. */
1897                 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1898                 skb_shinfo(skb)->gso_segs = 0;
1899         }
1900
1901         skb->protocol = htons(ETH_P_IP);
1902         skb_clear_hash(skb);
1903
1904         return 0;
1905 }
1906
1907 static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
1908 {
1909         __be16 from_proto = skb->protocol;
1910
1911         if (from_proto == htons(ETH_P_IP) &&
1912               to_proto == htons(ETH_P_IPV6))
1913                 return bpf_skb_proto_4_to_6(skb);
1914
1915         if (from_proto == htons(ETH_P_IPV6) &&
1916               to_proto == htons(ETH_P_IP))
1917                 return bpf_skb_proto_6_to_4(skb);
1918
1919         return -ENOTSUPP;
1920 }
1921
1922 BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
1923            u64, flags)
1924 {
1925         int ret;
1926
1927         if (unlikely(flags))
1928                 return -EINVAL;
1929
1930         /* General idea is that this helper does the basic groundwork
1931          * needed for changing the protocol, and eBPF program fills the
1932          * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
1933          * and other helpers, rather than passing a raw buffer here.
1934          *
1935          * The rationale is to keep this minimal and without a need to
1936          * deal with raw packet data. F.e. even if we would pass buffers
1937          * here, the program still needs to call the bpf_lX_csum_replace()
1938          * helpers anyway. Plus, this way we keep also separation of
1939          * concerns, since f.e. bpf_skb_store_bytes() should only take
1940          * care of stores.
1941          *
1942          * Currently, additional options and extension header space are
1943          * not supported, but flags register is reserved so we can adapt
1944          * that. For offloads, we mark packet as dodgy, so that headers
1945          * need to be verified first.
1946          */
1947         ret = bpf_skb_proto_xlat(skb, proto);
1948         bpf_compute_data_end(skb);
1949         return ret;
1950 }
1951
1952 static const struct bpf_func_proto bpf_skb_change_proto_proto = {
1953         .func           = bpf_skb_change_proto,
1954         .gpl_only       = false,
1955         .ret_type       = RET_INTEGER,
1956         .arg1_type      = ARG_PTR_TO_CTX,
1957         .arg2_type      = ARG_ANYTHING,
1958         .arg3_type      = ARG_ANYTHING,
1959 };
1960
1961 BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
1962 {
1963         /* We only allow a restricted subset to be changed for now. */
1964         if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
1965                      !skb_pkt_type_ok(pkt_type)))
1966                 return -EINVAL;
1967
1968         skb->pkt_type = pkt_type;
1969         return 0;
1970 }
1971
1972 static const struct bpf_func_proto bpf_skb_change_type_proto = {
1973         .func           = bpf_skb_change_type,
1974         .gpl_only       = false,
1975         .ret_type       = RET_INTEGER,
1976         .arg1_type      = ARG_PTR_TO_CTX,
1977         .arg2_type      = ARG_ANYTHING,
1978 };
1979
1980 static u32 __bpf_skb_min_len(const struct sk_buff *skb)
1981 {
1982         u32 min_len = skb_network_offset(skb);
1983
1984         if (skb_transport_header_was_set(skb))
1985                 min_len = skb_transport_offset(skb);
1986         if (skb->ip_summed == CHECKSUM_PARTIAL)
1987                 min_len = skb_checksum_start_offset(skb) +
1988                           skb->csum_offset + sizeof(__sum16);
1989         return min_len;
1990 }
1991
1992 static u32 __bpf_skb_max_len(const struct sk_buff *skb)
1993 {
1994         return skb->dev->mtu + skb->dev->hard_header_len;
1995 }
1996
1997 static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
1998 {
1999         unsigned int old_len = skb->len;
2000         int ret;
2001
2002         ret = __skb_grow_rcsum(skb, new_len);
2003         if (!ret)
2004                 memset(skb->data + old_len, 0, new_len - old_len);
2005         return ret;
2006 }
2007
2008 static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
2009 {
2010         return __skb_trim_rcsum(skb, new_len);
2011 }
2012
2013 BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
2014            u64, flags)
2015 {
2016         u32 max_len = __bpf_skb_max_len(skb);
2017         u32 min_len = __bpf_skb_min_len(skb);
2018         int ret;
2019
2020         if (unlikely(flags || new_len > max_len || new_len < min_len))
2021                 return -EINVAL;
2022         if (skb->encapsulation)
2023                 return -ENOTSUPP;
2024
2025         /* The basic idea of this helper is that it's performing the
2026          * needed work to either grow or trim an skb, and eBPF program
2027          * rewrites the rest via helpers like bpf_skb_store_bytes(),
2028          * bpf_lX_csum_replace() and others rather than passing a raw
2029          * buffer here. This one is a slow path helper and intended
2030          * for replies with control messages.
2031          *
2032          * Like in bpf_skb_change_proto(), we want to keep this rather
2033          * minimal and without protocol specifics so that we are able
2034          * to separate concerns as in bpf_skb_store_bytes() should only
2035          * be the one responsible for writing buffers.
2036          *
2037          * It's really expected to be a slow path operation here for
2038          * control message replies, so we're implicitly linearizing,
2039          * uncloning and drop offloads from the skb by this.
2040          */
2041         ret = __bpf_try_make_writable(skb, skb->len);
2042         if (!ret) {
2043                 if (new_len > skb->len)
2044                         ret = bpf_skb_grow_rcsum(skb, new_len);
2045                 else if (new_len < skb->len)
2046                         ret = bpf_skb_trim_rcsum(skb, new_len);
2047                 if (!ret && skb_is_gso(skb))
2048                         skb_gso_reset(skb);
2049         }
2050
2051         bpf_compute_data_end(skb);
2052         return ret;
2053 }
2054
2055 static const struct bpf_func_proto bpf_skb_change_tail_proto = {
2056         .func           = bpf_skb_change_tail,
2057         .gpl_only       = false,
2058         .ret_type       = RET_INTEGER,
2059         .arg1_type      = ARG_PTR_TO_CTX,
2060         .arg2_type      = ARG_ANYTHING,
2061         .arg3_type      = ARG_ANYTHING,
2062 };
2063
2064 bool bpf_helper_changes_skb_data(void *func)
2065 {
2066         if (func == bpf_skb_vlan_push)
2067                 return true;
2068         if (func == bpf_skb_vlan_pop)
2069                 return true;
2070         if (func == bpf_skb_store_bytes)
2071                 return true;
2072         if (func == bpf_skb_change_proto)
2073                 return true;
2074         if (func == bpf_skb_change_tail)
2075                 return true;
2076         if (func == bpf_l3_csum_replace)
2077                 return true;
2078         if (func == bpf_l4_csum_replace)
2079                 return true;
2080
2081         return false;
2082 }
2083
2084 static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
2085                                   unsigned long off, unsigned long len)
2086 {
2087         void *ptr = skb_header_pointer(skb, off, len, dst_buff);
2088
2089         if (unlikely(!ptr))
2090                 return len;
2091         if (ptr != dst_buff)
2092                 memcpy(dst_buff, ptr, len);
2093
2094         return 0;
2095 }
2096
2097 BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
2098            u64, flags, void *, meta, u64, meta_size)
2099 {
2100         u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
2101
2102         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
2103                 return -EINVAL;
2104         if (unlikely(skb_size > skb->len))
2105                 return -EFAULT;
2106
2107         return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
2108                                 bpf_skb_copy);
2109 }
2110
2111 static const struct bpf_func_proto bpf_skb_event_output_proto = {
2112         .func           = bpf_skb_event_output,
2113         .gpl_only       = true,
2114         .ret_type       = RET_INTEGER,
2115         .arg1_type      = ARG_PTR_TO_CTX,
2116         .arg2_type      = ARG_CONST_MAP_PTR,
2117         .arg3_type      = ARG_ANYTHING,
2118         .arg4_type      = ARG_PTR_TO_STACK,
2119         .arg5_type      = ARG_CONST_STACK_SIZE,
2120 };
2121
2122 static unsigned short bpf_tunnel_key_af(u64 flags)
2123 {
2124         return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
2125 }
2126
2127 BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
2128            u32, size, u64, flags)
2129 {
2130         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
2131         u8 compat[sizeof(struct bpf_tunnel_key)];
2132         void *to_orig = to;
2133         int err;
2134
2135         if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) {
2136                 err = -EINVAL;
2137                 goto err_clear;
2138         }
2139         if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
2140                 err = -EPROTO;
2141                 goto err_clear;
2142         }
2143         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
2144                 err = -EINVAL;
2145                 switch (size) {
2146                 case offsetof(struct bpf_tunnel_key, tunnel_label):
2147                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
2148                         goto set_compat;
2149                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
2150                         /* Fixup deprecated structure layouts here, so we have
2151                          * a common path later on.
2152                          */
2153                         if (ip_tunnel_info_af(info) != AF_INET)
2154                                 goto err_clear;
2155 set_compat:
2156                         to = (struct bpf_tunnel_key *)compat;
2157                         break;
2158                 default:
2159                         goto err_clear;
2160                 }
2161         }
2162
2163         to->tunnel_id = be64_to_cpu(info->key.tun_id);
2164         to->tunnel_tos = info->key.tos;
2165         to->tunnel_ttl = info->key.ttl;
2166
2167         if (flags & BPF_F_TUNINFO_IPV6) {
2168                 memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
2169                        sizeof(to->remote_ipv6));
2170                 to->tunnel_label = be32_to_cpu(info->key.label);
2171         } else {
2172                 to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
2173         }
2174
2175         if (unlikely(size != sizeof(struct bpf_tunnel_key)))
2176                 memcpy(to_orig, to, size);
2177
2178         return 0;
2179 err_clear:
2180         memset(to_orig, 0, size);
2181         return err;
2182 }
2183
2184 static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
2185         .func           = bpf_skb_get_tunnel_key,
2186         .gpl_only       = false,
2187         .ret_type       = RET_INTEGER,
2188         .arg1_type      = ARG_PTR_TO_CTX,
2189         .arg2_type      = ARG_PTR_TO_RAW_STACK,
2190         .arg3_type      = ARG_CONST_STACK_SIZE,
2191         .arg4_type      = ARG_ANYTHING,
2192 };
2193
2194 BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
2195 {
2196         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
2197         int err;
2198
2199         if (unlikely(!info ||
2200                      !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
2201                 err = -ENOENT;
2202                 goto err_clear;
2203         }
2204         if (unlikely(size < info->options_len)) {
2205                 err = -ENOMEM;
2206                 goto err_clear;
2207         }
2208
2209         ip_tunnel_info_opts_get(to, info);
2210         if (size > info->options_len)
2211                 memset(to + info->options_len, 0, size - info->options_len);
2212
2213         return info->options_len;
2214 err_clear:
2215         memset(to, 0, size);
2216         return err;
2217 }
2218
2219 static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
2220         .func           = bpf_skb_get_tunnel_opt,
2221         .gpl_only       = false,
2222         .ret_type       = RET_INTEGER,
2223         .arg1_type      = ARG_PTR_TO_CTX,
2224         .arg2_type      = ARG_PTR_TO_RAW_STACK,
2225         .arg3_type      = ARG_CONST_STACK_SIZE,
2226 };
2227
2228 static struct metadata_dst __percpu *md_dst;
2229
2230 BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
2231            const struct bpf_tunnel_key *, from, u32, size, u64, flags)
2232 {
2233         struct metadata_dst *md = this_cpu_ptr(md_dst);
2234         u8 compat[sizeof(struct bpf_tunnel_key)];
2235         struct ip_tunnel_info *info;
2236
2237         if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
2238                                BPF_F_DONT_FRAGMENT)))
2239                 return -EINVAL;
2240         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
2241                 switch (size) {
2242                 case offsetof(struct bpf_tunnel_key, tunnel_label):
2243                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
2244                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
2245                         /* Fixup deprecated structure layouts here, so we have
2246                          * a common path later on.
2247                          */
2248                         memcpy(compat, from, size);
2249                         memset(compat + size, 0, sizeof(compat) - size);
2250                         from = (const struct bpf_tunnel_key *) compat;
2251                         break;
2252                 default:
2253                         return -EINVAL;
2254                 }
2255         }
2256         if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
2257                      from->tunnel_ext))
2258                 return -EINVAL;
2259
2260         skb_dst_drop(skb);
2261         dst_hold((struct dst_entry *) md);
2262         skb_dst_set(skb, (struct dst_entry *) md);
2263
2264         info = &md->u.tun_info;
2265         info->mode = IP_TUNNEL_INFO_TX;
2266
2267         info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
2268         if (flags & BPF_F_DONT_FRAGMENT)
2269                 info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;
2270
2271         info->key.tun_id = cpu_to_be64(from->tunnel_id);
2272         info->key.tos = from->tunnel_tos;
2273         info->key.ttl = from->tunnel_ttl;
2274
2275         if (flags & BPF_F_TUNINFO_IPV6) {
2276                 info->mode |= IP_TUNNEL_INFO_IPV6;
2277                 memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
2278                        sizeof(from->remote_ipv6));
2279                 info->key.label = cpu_to_be32(from->tunnel_label) &
2280                                   IPV6_FLOWLABEL_MASK;
2281         } else {
2282                 info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
2283                 if (flags & BPF_F_ZERO_CSUM_TX)
2284                         info->key.tun_flags &= ~TUNNEL_CSUM;
2285         }
2286
2287         return 0;
2288 }
2289
2290 static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
2291         .func           = bpf_skb_set_tunnel_key,
2292         .gpl_only       = false,
2293         .ret_type       = RET_INTEGER,
2294         .arg1_type      = ARG_PTR_TO_CTX,
2295         .arg2_type      = ARG_PTR_TO_STACK,
2296         .arg3_type      = ARG_CONST_STACK_SIZE,
2297         .arg4_type      = ARG_ANYTHING,
2298 };
2299
2300 BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
2301            const u8 *, from, u32, size)
2302 {
2303         struct ip_tunnel_info *info = skb_tunnel_info(skb);
2304         const struct metadata_dst *md = this_cpu_ptr(md_dst);
2305
2306         if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
2307                 return -EINVAL;
2308         if (unlikely(size > IP_TUNNEL_OPTS_MAX))
2309                 return -ENOMEM;
2310
2311         ip_tunnel_info_opts_set(info, from, size);
2312
2313         return 0;
2314 }
2315
2316 static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
2317         .func           = bpf_skb_set_tunnel_opt,
2318         .gpl_only       = false,
2319         .ret_type       = RET_INTEGER,
2320         .arg1_type      = ARG_PTR_TO_CTX,
2321         .arg2_type      = ARG_PTR_TO_STACK,
2322         .arg3_type      = ARG_CONST_STACK_SIZE,
2323 };
2324
2325 static const struct bpf_func_proto *
2326 bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
2327 {
2328         if (!md_dst) {
2329                 /* Race is not possible, since it's called from verifier
2330                  * that is holding verifier mutex.
2331                  */
2332                 md_dst = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
2333                                                    GFP_KERNEL);
2334                 if (!md_dst)
2335                         return NULL;
2336         }
2337
2338         switch (which) {
2339         case BPF_FUNC_skb_set_tunnel_key:
2340                 return &bpf_skb_set_tunnel_key_proto;
2341         case BPF_FUNC_skb_set_tunnel_opt:
2342                 return &bpf_skb_set_tunnel_opt_proto;
2343         default:
2344                 return NULL;
2345         }
2346 }
2347
2348 BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
2349            u32, idx)
2350 {
2351         struct bpf_array *array = container_of(map, struct bpf_array, map);
2352         struct cgroup *cgrp;
2353         struct sock *sk;
2354
2355         sk = skb->sk;
2356         if (!sk || !sk_fullsock(sk))
2357                 return -ENOENT;
2358         if (unlikely(idx >= array->map.max_entries))
2359                 return -E2BIG;
2360
2361         cgrp = READ_ONCE(array->ptrs[idx]);
2362         if (unlikely(!cgrp))
2363                 return -EAGAIN;
2364
2365         return sk_under_cgroup_hierarchy(sk, cgrp);
2366 }
2367
2368 static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
2369         .func           = bpf_skb_under_cgroup,
2370         .gpl_only       = false,
2371         .ret_type       = RET_INTEGER,
2372         .arg1_type      = ARG_PTR_TO_CTX,
2373         .arg2_type      = ARG_CONST_MAP_PTR,
2374         .arg3_type      = ARG_ANYTHING,
2375 };
2376
2377 static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff,
2378                                   unsigned long off, unsigned long len)
2379 {
2380         memcpy(dst_buff, src_buff + off, len);
2381         return 0;
2382 }
2383
2384 BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
2385            u64, flags, void *, meta, u64, meta_size)
2386 {
2387         u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
2388
2389         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
2390                 return -EINVAL;
2391         if (unlikely(xdp_size > (unsigned long)(xdp->data_end - xdp->data)))
2392                 return -EFAULT;
2393
2394         return bpf_event_output(map, flags, meta, meta_size, xdp, xdp_size,
2395                                 bpf_xdp_copy);
2396 }
2397
2398 static const struct bpf_func_proto bpf_xdp_event_output_proto = {
2399         .func           = bpf_xdp_event_output,
2400         .gpl_only       = true,
2401         .ret_type       = RET_INTEGER,
2402         .arg1_type      = ARG_PTR_TO_CTX,
2403         .arg2_type      = ARG_CONST_MAP_PTR,
2404         .arg3_type      = ARG_ANYTHING,
2405         .arg4_type      = ARG_PTR_TO_STACK,
2406         .arg5_type      = ARG_CONST_STACK_SIZE,
2407 };
2408
2409 static const struct bpf_func_proto *
2410 sk_filter_func_proto(enum bpf_func_id func_id)
2411 {
2412         switch (func_id) {
2413         case BPF_FUNC_map_lookup_elem:
2414                 return &bpf_map_lookup_elem_proto;
2415         case BPF_FUNC_map_update_elem:
2416                 return &bpf_map_update_elem_proto;
2417         case BPF_FUNC_map_delete_elem:
2418                 return &bpf_map_delete_elem_proto;
2419         case BPF_FUNC_get_prandom_u32:
2420                 return &bpf_get_prandom_u32_proto;
2421         case BPF_FUNC_get_smp_processor_id:
2422                 return &bpf_get_raw_smp_processor_id_proto;
2423         case BPF_FUNC_tail_call:
2424                 return &bpf_tail_call_proto;
2425         case BPF_FUNC_ktime_get_ns:
2426                 return &bpf_ktime_get_ns_proto;
2427         case BPF_FUNC_trace_printk:
2428                 if (capable(CAP_SYS_ADMIN))
2429                         return bpf_get_trace_printk_proto();
2430         default:
2431                 return NULL;
2432         }
2433 }
2434
2435 static const struct bpf_func_proto *
2436 tc_cls_act_func_proto(enum bpf_func_id func_id)
2437 {
2438         switch (func_id) {
2439         case BPF_FUNC_skb_store_bytes:
2440                 return &bpf_skb_store_bytes_proto;
2441         case BPF_FUNC_skb_load_bytes:
2442                 return &bpf_skb_load_bytes_proto;
2443         case BPF_FUNC_csum_diff:
2444                 return &bpf_csum_diff_proto;
2445         case BPF_FUNC_l3_csum_replace:
2446                 return &bpf_l3_csum_replace_proto;
2447         case BPF_FUNC_l4_csum_replace:
2448                 return &bpf_l4_csum_replace_proto;
2449         case BPF_FUNC_clone_redirect:
2450                 return &bpf_clone_redirect_proto;
2451         case BPF_FUNC_get_cgroup_classid:
2452                 return &bpf_get_cgroup_classid_proto;
2453         case BPF_FUNC_skb_vlan_push:
2454                 return &bpf_skb_vlan_push_proto;
2455         case BPF_FUNC_skb_vlan_pop:
2456                 return &bpf_skb_vlan_pop_proto;
2457         case BPF_FUNC_skb_change_proto:
2458                 return &bpf_skb_change_proto_proto;
2459         case BPF_FUNC_skb_change_type:
2460                 return &bpf_skb_change_type_proto;
2461         case BPF_FUNC_skb_change_tail:
2462                 return &bpf_skb_change_tail_proto;
2463         case BPF_FUNC_skb_get_tunnel_key:
2464                 return &bpf_skb_get_tunnel_key_proto;
2465         case BPF_FUNC_skb_set_tunnel_key:
2466                 return bpf_get_skb_set_tunnel_proto(func_id);
2467         case BPF_FUNC_skb_get_tunnel_opt:
2468                 return &bpf_skb_get_tunnel_opt_proto;
2469         case BPF_FUNC_skb_set_tunnel_opt:
2470                 return bpf_get_skb_set_tunnel_proto(func_id);
2471         case BPF_FUNC_redirect:
2472                 return &bpf_redirect_proto;
2473         case BPF_FUNC_get_route_realm:
2474                 return &bpf_get_route_realm_proto;
2475         case BPF_FUNC_get_hash_recalc:
2476                 return &bpf_get_hash_recalc_proto;
2477         case BPF_FUNC_perf_event_output:
2478                 return &bpf_skb_event_output_proto;
2479         case BPF_FUNC_get_smp_processor_id:
2480                 return &bpf_get_smp_processor_id_proto;
2481         case BPF_FUNC_skb_under_cgroup:
2482                 return &bpf_skb_under_cgroup_proto;
2483         default:
2484                 return sk_filter_func_proto(func_id);
2485         }
2486 }
2487
2488 static const struct bpf_func_proto *
2489 xdp_func_proto(enum bpf_func_id func_id)
2490 {
2491         switch (func_id) {
2492         case BPF_FUNC_perf_event_output:
2493                 return &bpf_xdp_event_output_proto;
2494         default:
2495                 return sk_filter_func_proto(func_id);
2496         }
2497 }
2498
2499 static bool __is_valid_access(int off, int size, enum bpf_access_type type)
2500 {
2501         if (off < 0 || off >= sizeof(struct __sk_buff))
2502                 return false;
2503         /* The verifier guarantees that size > 0. */
2504         if (off % size != 0)
2505                 return false;
2506         if (size != sizeof(__u32))
2507                 return false;
2508
2509         return true;
2510 }
2511
2512 static bool sk_filter_is_valid_access(int off, int size,
2513                                       enum bpf_access_type type,
2514                                       enum bpf_reg_type *reg_type)
2515 {
2516         switch (off) {
2517         case offsetof(struct __sk_buff, tc_classid):
2518         case offsetof(struct __sk_buff, data):
2519         case offsetof(struct __sk_buff, data_end):
2520                 return false;
2521         }
2522
2523         if (type == BPF_WRITE) {
2524                 switch (off) {
2525                 case offsetof(struct __sk_buff, cb[0]) ...
2526                      offsetof(struct __sk_buff, cb[4]):
2527                         break;
2528                 default:
2529                         return false;
2530                 }
2531         }
2532
2533         return __is_valid_access(off, size, type);
2534 }
2535
2536 static bool tc_cls_act_is_valid_access(int off, int size,
2537                                        enum bpf_access_type type,
2538                                        enum bpf_reg_type *reg_type)
2539 {
2540         if (type == BPF_WRITE) {
2541                 switch (off) {
2542                 case offsetof(struct __sk_buff, mark):
2543                 case offsetof(struct __sk_buff, tc_index):
2544                 case offsetof(struct __sk_buff, priority):
2545                 case offsetof(struct __sk_buff, cb[0]) ...
2546                      offsetof(struct __sk_buff, cb[4]):
2547                 case offsetof(struct __sk_buff, tc_classid):
2548                         break;
2549                 default:
2550                         return false;
2551                 }
2552         }
2553
2554         switch (off) {
2555         case offsetof(struct __sk_buff, data):
2556                 *reg_type = PTR_TO_PACKET;
2557                 break;
2558         case offsetof(struct __sk_buff, data_end):
2559                 *reg_type = PTR_TO_PACKET_END;
2560                 break;
2561         }
2562
2563         return __is_valid_access(off, size, type);
2564 }
2565
2566 static bool __is_valid_xdp_access(int off, int size,
2567                                   enum bpf_access_type type)
2568 {
2569         if (off < 0 || off >= sizeof(struct xdp_md))
2570                 return false;
2571         if (off % size != 0)
2572                 return false;
2573         if (size != sizeof(__u32))
2574                 return false;
2575
2576         return true;
2577 }
2578
2579 static bool xdp_is_valid_access(int off, int size,
2580                                 enum bpf_access_type type,
2581                                 enum bpf_reg_type *reg_type)
2582 {
2583         if (type == BPF_WRITE)
2584                 return false;
2585
2586         switch (off) {
2587         case offsetof(struct xdp_md, data):
2588                 *reg_type = PTR_TO_PACKET;
2589                 break;
2590         case offsetof(struct xdp_md, data_end):
2591                 *reg_type = PTR_TO_PACKET_END;
2592                 break;
2593         }
2594
2595         return __is_valid_xdp_access(off, size, type);
2596 }
2597
2598 void bpf_warn_invalid_xdp_action(u32 act)
2599 {
2600         WARN_ONCE(1, "Illegal XDP return value %u, expect packet loss\n", act);
2601 }
2602 EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
2603
2604 static u32 sk_filter_convert_ctx_access(enum bpf_access_type type, int dst_reg,
2605                                         int src_reg, int ctx_off,
2606                                         struct bpf_insn *insn_buf,
2607                                         struct bpf_prog *prog)
2608 {
2609         struct bpf_insn *insn = insn_buf;
2610
2611         switch (ctx_off) {
2612         case offsetof(struct __sk_buff, len):
2613                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, len) != 4);
2614
2615                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
2616                                       offsetof(struct sk_buff, len));
2617                 break;
2618
2619         case offsetof(struct __sk_buff, protocol):
2620                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);
2621
2622                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
2623                                       offsetof(struct sk_buff, protocol));
2624                 break;
2625
2626         case offsetof(struct __sk_buff, vlan_proto):
2627                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);
2628
2629                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
2630                                       offsetof(struct sk_buff, vlan_proto));
2631                 break;
2632
2633         case offsetof(struct __sk_buff, priority):
2634                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, priority) != 4);
2635
2636                 if (type == BPF_WRITE)
2637                         *insn++ = BPF_STX_MEM(BPF_W, dst_reg, src_reg,
2638                                               offsetof(struct sk_buff, priority));
2639                 else
2640                         *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
2641                                               offsetof(struct sk_buff, priority));
2642                 break;
2643
2644         case offsetof(struct __sk_buff, ingress_ifindex):
2645                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, skb_iif) != 4);
2646
2647                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
2648                                       offsetof(struct sk_buff, skb_iif));
2649                 break;
2650
2651         case offsetof(struct __sk_buff, ifindex):
2652                 BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
2653
2654                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
2655                                       dst_reg, src_reg,
2656                                       offsetof(struct sk_buff, dev));
2657                 *insn++ = BPF_JMP_IMM(BPF_JEQ, dst_reg, 0, 1);
2658                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, dst_reg,
2659                                       offsetof(struct net_device, ifindex));
2660                 break;
2661
2662         case offsetof(struct __sk_buff, hash):
2663                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);
2664
2665                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
2666                                       offsetof(struct sk_buff, hash));
2667                 break;
2668
2669         case offsetof(struct __sk_buff, mark):
2670                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);
2671
2672                 if (type == BPF_WRITE)
2673                         *insn++ = BPF_STX_MEM(BPF_W, dst_reg, src_reg,
2674                                               offsetof(struct sk_buff, mark));
2675                 else
2676                         *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
2677                                               offsetof(struct sk_buff, mark));
2678                 break;
2679
2680         case offsetof(struct __sk_buff, pkt_type):
2681                 return convert_skb_access(SKF_AD_PKTTYPE, dst_reg, src_reg, insn);
2682
2683         case offsetof(struct __sk_buff, queue_mapping):
2684                 return convert_skb_access(SKF_AD_QUEUE, dst_reg, src_reg, insn);
2685
2686         case offsetof(struct __sk_buff, vlan_present):
2687                 return convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
2688                                           dst_reg, src_reg, insn);
2689
2690         case offsetof(struct __sk_buff, vlan_tci):
2691                 return convert_skb_access(SKF_AD_VLAN_TAG,
2692                                           dst_reg, src_reg, insn);
2693
2694         case offsetof(struct __sk_buff, cb[0]) ...
2695              offsetof(struct __sk_buff, cb[4]):
2696                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);
2697
2698                 prog->cb_access = 1;
2699                 ctx_off -= offsetof(struct __sk_buff, cb[0]);
2700                 ctx_off += offsetof(struct sk_buff, cb);
2701                 ctx_off += offsetof(struct qdisc_skb_cb, data);
2702                 if (type == BPF_WRITE)
2703                         *insn++ = BPF_STX_MEM(BPF_W, dst_reg, src_reg, ctx_off);
2704                 else
2705                         *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg, ctx_off);
2706                 break;
2707
2708         case offsetof(struct __sk_buff, tc_classid):
2709                 ctx_off -= offsetof(struct __sk_buff, tc_classid);
2710                 ctx_off += offsetof(struct sk_buff, cb);
2711                 ctx_off += offsetof(struct qdisc_skb_cb, tc_classid);
2712                 if (type == BPF_WRITE)
2713                         *insn++ = BPF_STX_MEM(BPF_H, dst_reg, src_reg, ctx_off);
2714                 else
2715                         *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg, ctx_off);
2716                 break;
2717
2718         case offsetof(struct __sk_buff, data):
2719                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
2720                                       dst_reg, src_reg,
2721                                       offsetof(struct sk_buff, data));
2722                 break;
2723
2724         case offsetof(struct __sk_buff, data_end):
2725                 ctx_off -= offsetof(struct __sk_buff, data_end);
2726                 ctx_off += offsetof(struct sk_buff, cb);
2727                 ctx_off += offsetof(struct bpf_skb_data_end, data_end);
2728                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), dst_reg, src_reg,
2729                                       ctx_off);
2730                 break;
2731
2732         case offsetof(struct __sk_buff, tc_index):
2733 #ifdef CONFIG_NET_SCHED
2734                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, tc_index) != 2);
2735
2736                 if (type == BPF_WRITE)
2737                         *insn++ = BPF_STX_MEM(BPF_H, dst_reg, src_reg,
2738                                               offsetof(struct sk_buff, tc_index));
2739                 else
2740                         *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
2741                                               offsetof(struct sk_buff, tc_index));
2742                 break;
2743 #else
2744                 if (type == BPF_WRITE)
2745                         *insn++ = BPF_MOV64_REG(dst_reg, dst_reg);
2746                 else
2747                         *insn++ = BPF_MOV64_IMM(dst_reg, 0);
2748                 break;
2749 #endif
2750         }
2751
2752         return insn - insn_buf;
2753 }
2754
2755 static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type, int dst_reg,
2756                                          int src_reg, int ctx_off,
2757                                          struct bpf_insn *insn_buf,
2758                                          struct bpf_prog *prog)
2759 {
2760         struct bpf_insn *insn = insn_buf;
2761
2762         switch (ctx_off) {
2763         case offsetof(struct __sk_buff, ifindex):
2764                 BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
2765
2766                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
2767                                       dst_reg, src_reg,
2768                                       offsetof(struct sk_buff, dev));
2769                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, dst_reg,
2770                                       offsetof(struct net_device, ifindex));
2771                 break;
2772         default:
2773                 return sk_filter_convert_ctx_access(type, dst_reg, src_reg,
2774                                                     ctx_off, insn_buf, prog);
2775         }
2776
2777         return insn - insn_buf;
2778 }
2779
2780 static u32 xdp_convert_ctx_access(enum bpf_access_type type, int dst_reg,
2781                                   int src_reg, int ctx_off,
2782                                   struct bpf_insn *insn_buf,
2783                                   struct bpf_prog *prog)
2784 {
2785         struct bpf_insn *insn = insn_buf;
2786
2787         switch (ctx_off) {
2788         case offsetof(struct xdp_md, data):
2789                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
2790                                       dst_reg, src_reg,
2791                                       offsetof(struct xdp_buff, data));
2792                 break;
2793         case offsetof(struct xdp_md, data_end):
2794                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
2795                                       dst_reg, src_reg,
2796                                       offsetof(struct xdp_buff, data_end));
2797                 break;
2798         }
2799
2800         return insn - insn_buf;
2801 }
2802
2803 static const struct bpf_verifier_ops sk_filter_ops = {
2804         .get_func_proto         = sk_filter_func_proto,
2805         .is_valid_access        = sk_filter_is_valid_access,
2806         .convert_ctx_access     = sk_filter_convert_ctx_access,
2807 };
2808
2809 static const struct bpf_verifier_ops tc_cls_act_ops = {
2810         .get_func_proto         = tc_cls_act_func_proto,
2811         .is_valid_access        = tc_cls_act_is_valid_access,
2812         .convert_ctx_access     = tc_cls_act_convert_ctx_access,
2813 };
2814
2815 static const struct bpf_verifier_ops xdp_ops = {
2816         .get_func_proto         = xdp_func_proto,
2817         .is_valid_access        = xdp_is_valid_access,
2818         .convert_ctx_access     = xdp_convert_ctx_access,
2819 };
2820
2821 static struct bpf_prog_type_list sk_filter_type __read_mostly = {
2822         .ops    = &sk_filter_ops,
2823         .type   = BPF_PROG_TYPE_SOCKET_FILTER,
2824 };
2825
2826 static struct bpf_prog_type_list sched_cls_type __read_mostly = {
2827         .ops    = &tc_cls_act_ops,
2828         .type   = BPF_PROG_TYPE_SCHED_CLS,
2829 };
2830
2831 static struct bpf_prog_type_list sched_act_type __read_mostly = {
2832         .ops    = &tc_cls_act_ops,
2833         .type   = BPF_PROG_TYPE_SCHED_ACT,
2834 };
2835
2836 static struct bpf_prog_type_list xdp_type __read_mostly = {
2837         .ops    = &xdp_ops,
2838         .type   = BPF_PROG_TYPE_XDP,
2839 };
2840
2841 static int __init register_sk_filter_ops(void)
2842 {
2843         bpf_register_prog_type(&sk_filter_type);
2844         bpf_register_prog_type(&sched_cls_type);
2845         bpf_register_prog_type(&sched_act_type);
2846         bpf_register_prog_type(&xdp_type);
2847
2848         return 0;
2849 }
2850 late_initcall(register_sk_filter_ops);
2851
2852 int sk_detach_filter(struct sock *sk)
2853 {
2854         int ret = -ENOENT;
2855         struct sk_filter *filter;
2856
2857         if (sock_flag(sk, SOCK_FILTER_LOCKED))
2858                 return -EPERM;
2859
2860         filter = rcu_dereference_protected(sk->sk_filter,
2861                                            lockdep_sock_is_held(sk));
2862         if (filter) {
2863                 RCU_INIT_POINTER(sk->sk_filter, NULL);
2864                 sk_filter_uncharge(sk, filter);
2865                 ret = 0;
2866         }
2867
2868         return ret;
2869 }
2870 EXPORT_SYMBOL_GPL(sk_detach_filter);
2871
2872 int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
2873                   unsigned int len)
2874 {
2875         struct sock_fprog_kern *fprog;
2876         struct sk_filter *filter;
2877         int ret = 0;
2878
2879         lock_sock(sk);
2880         filter = rcu_dereference_protected(sk->sk_filter,
2881                                            lockdep_sock_is_held(sk));
2882         if (!filter)
2883                 goto out;
2884
2885         /* We're copying the filter that has been originally attached,
2886          * so no conversion/decode needed anymore. eBPF programs that
2887          * have no original program cannot be dumped through this.
2888          */
2889         ret = -EACCES;
2890         fprog = filter->prog->orig_prog;
2891         if (!fprog)
2892                 goto out;
2893
2894         ret = fprog->len;
2895         if (!len)
2896                 /* User space only enquires number of filter blocks. */
2897                 goto out;
2898
2899         ret = -EINVAL;
2900         if (len < fprog->len)
2901                 goto out;
2902
2903         ret = -EFAULT;
2904         if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
2905                 goto out;
2906
2907         /* Instead of bytes, the API requests to return the number
2908          * of filter blocks.
2909          */
2910         ret = fprog->len;
2911 out:
2912         release_sock(sk);
2913         return ret;
2914 }