~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/net/core/filter.c

Version: ~ [ linux-5.11 ] ~ [ linux-5.10.17 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.99 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.176 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.221 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.257 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.257 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp