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