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