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