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