linux/net/core/filter.c
<<
>>
Prefs
   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/inet_common.h>
  37#include <net/ip.h>
  38#include <net/protocol.h>
  39#include <net/netlink.h>
  40#include <linux/skbuff.h>
  41#include <net/sock.h>
  42#include <net/flow_dissector.h>
  43#include <linux/errno.h>
  44#include <linux/timer.h>
  45#include <linux/uaccess.h>
  46#include <asm/unaligned.h>
  47#include <asm/cmpxchg.h>
  48#include <linux/filter.h>
  49#include <linux/ratelimit.h>
  50#include <linux/seccomp.h>
  51#include <linux/if_vlan.h>
  52#include <linux/bpf.h>
  53#include <net/sch_generic.h>
  54#include <net/cls_cgroup.h>
  55#include <net/dst_metadata.h>
  56#include <net/dst.h>
  57#include <net/sock_reuseport.h>
  58#include <net/busy_poll.h>
  59#include <net/tcp.h>
  60#include <net/xfrm.h>
  61#include <linux/bpf_trace.h>
  62#include <net/xdp_sock.h>
  63#include <linux/inetdevice.h>
  64#include <net/ip_fib.h>
  65#include <net/flow.h>
  66#include <net/arp.h>
  67#include <net/ipv6.h>
  68#include <linux/seg6_local.h>
  69#include <net/seg6.h>
  70#include <net/seg6_local.h>
  71
  72/**
  73 *      sk_filter_trim_cap - run a packet through a socket filter
  74 *      @sk: sock associated with &sk_buff
  75 *      @skb: buffer to filter
  76 *      @cap: limit on how short the eBPF program may trim the packet
  77 *
  78 * Run the eBPF program and then cut skb->data to correct size returned by
  79 * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
  80 * than pkt_len we keep whole skb->data. This is the socket level
  81 * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
  82 * be accepted or -EPERM if the packet should be tossed.
  83 *
  84 */
  85int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
  86{
  87        int err;
  88        struct sk_filter *filter;
  89
  90        /*
  91         * If the skb was allocated from pfmemalloc reserves, only
  92         * allow SOCK_MEMALLOC sockets to use it as this socket is
  93         * helping free memory
  94         */
  95        if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
  96                NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
  97                return -ENOMEM;
  98        }
  99        err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
 100        if (err)
 101                return err;
 102
 103        err = security_sock_rcv_skb(sk, skb);
 104        if (err)
 105                return err;
 106
 107        rcu_read_lock();
 108        filter = rcu_dereference(sk->sk_filter);
 109        if (filter) {
 110                struct sock *save_sk = skb->sk;
 111                unsigned int pkt_len;
 112
 113                skb->sk = sk;
 114                pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
 115                skb->sk = save_sk;
 116                err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
 117        }
 118        rcu_read_unlock();
 119
 120        return err;
 121}
 122EXPORT_SYMBOL(sk_filter_trim_cap);
 123
 124BPF_CALL_1(bpf_skb_get_pay_offset, struct sk_buff *, skb)
 125{
 126        return skb_get_poff(skb);
 127}
 128
 129BPF_CALL_3(bpf_skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
 130{
 131        struct nlattr *nla;
 132
 133        if (skb_is_nonlinear(skb))
 134                return 0;
 135
 136        if (skb->len < sizeof(struct nlattr))
 137                return 0;
 138
 139        if (a > skb->len - sizeof(struct nlattr))
 140                return 0;
 141
 142        nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
 143        if (nla)
 144                return (void *) nla - (void *) skb->data;
 145
 146        return 0;
 147}
 148
 149BPF_CALL_3(bpf_skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
 150{
 151        struct nlattr *nla;
 152
 153        if (skb_is_nonlinear(skb))
 154                return 0;
 155
 156        if (skb->len < sizeof(struct nlattr))
 157                return 0;
 158
 159        if (a > skb->len - sizeof(struct nlattr))
 160                return 0;
 161
 162        nla = (struct nlattr *) &skb->data[a];
 163        if (nla->nla_len > skb->len - a)
 164                return 0;
 165
 166        nla = nla_find_nested(nla, x);
 167        if (nla)
 168                return (void *) nla - (void *) skb->data;
 169
 170        return 0;
 171}
 172
 173BPF_CALL_4(bpf_skb_load_helper_8, const struct sk_buff *, skb, const void *,
 174           data, int, headlen, int, offset)
 175{
 176        u8 tmp, *ptr;
 177        const int len = sizeof(tmp);
 178
 179        if (offset >= 0) {
 180                if (headlen - offset >= len)
 181                        return *(u8 *)(data + offset);
 182                if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
 183                        return tmp;
 184        } else {
 185                ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
 186                if (likely(ptr))
 187                        return *(u8 *)ptr;
 188        }
 189
 190        return -EFAULT;
 191}
 192
 193BPF_CALL_2(bpf_skb_load_helper_8_no_cache, const struct sk_buff *, skb,
 194           int, offset)
 195{
 196        return ____bpf_skb_load_helper_8(skb, skb->data, skb->len - skb->data_len,
 197                                         offset);
 198}
 199
 200BPF_CALL_4(bpf_skb_load_helper_16, const struct sk_buff *, skb, const void *,
 201           data, int, headlen, int, offset)
 202{
 203        u16 tmp, *ptr;
 204        const int len = sizeof(tmp);
 205
 206        if (offset >= 0) {
 207                if (headlen - offset >= len)
 208                        return get_unaligned_be16(data + offset);
 209                if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
 210                        return be16_to_cpu(tmp);
 211        } else {
 212                ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
 213                if (likely(ptr))
 214                        return get_unaligned_be16(ptr);
 215        }
 216
 217        return -EFAULT;
 218}
 219
 220BPF_CALL_2(bpf_skb_load_helper_16_no_cache, const struct sk_buff *, skb,
 221           int, offset)
 222{
 223        return ____bpf_skb_load_helper_16(skb, skb->data, skb->len - skb->data_len,
 224                                          offset);
 225}
 226
 227BPF_CALL_4(bpf_skb_load_helper_32, const struct sk_buff *, skb, const void *,
 228           data, int, headlen, int, offset)
 229{
 230        u32 tmp, *ptr;
 231        const int len = sizeof(tmp);
 232
 233        if (likely(offset >= 0)) {
 234                if (headlen - offset >= len)
 235                        return get_unaligned_be32(data + offset);
 236                if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
 237                        return be32_to_cpu(tmp);
 238        } else {
 239                ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
 240                if (likely(ptr))
 241                        return get_unaligned_be32(ptr);
 242        }
 243
 244        return -EFAULT;
 245}
 246
 247BPF_CALL_2(bpf_skb_load_helper_32_no_cache, const struct sk_buff *, skb,
 248           int, offset)
 249{
 250        return ____bpf_skb_load_helper_32(skb, skb->data, skb->len - skb->data_len,
 251                                          offset);
 252}
 253
 254BPF_CALL_0(bpf_get_raw_cpu_id)
 255{
 256        return raw_smp_processor_id();
 257}
 258
 259static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
 260        .func           = bpf_get_raw_cpu_id,
 261        .gpl_only       = false,
 262        .ret_type       = RET_INTEGER,
 263};
 264
 265static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
 266                              struct bpf_insn *insn_buf)
 267{
 268        struct bpf_insn *insn = insn_buf;
 269
 270        switch (skb_field) {
 271        case SKF_AD_MARK:
 272                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);
 273
 274                *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
 275                                      offsetof(struct sk_buff, mark));
 276                break;
 277
 278        case SKF_AD_PKTTYPE:
 279                *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET());
 280                *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
 281#ifdef __BIG_ENDIAN_BITFIELD
 282                *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
 283#endif
 284                break;
 285
 286        case SKF_AD_QUEUE:
 287                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2);
 288
 289                *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
 290                                      offsetof(struct sk_buff, queue_mapping));
 291                break;
 292
 293        case SKF_AD_VLAN_TAG:
 294        case SKF_AD_VLAN_TAG_PRESENT:
 295                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_tci) != 2);
 296                BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);
 297
 298                /* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
 299                *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
 300                                      offsetof(struct sk_buff, vlan_tci));
 301                if (skb_field == SKF_AD_VLAN_TAG) {
 302                        *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg,
 303                                                ~VLAN_TAG_PRESENT);
 304                } else {
 305                        /* dst_reg >>= 12 */
 306                        *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 12);
 307                        /* dst_reg &= 1 */
 308                        *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1);
 309                }
 310                break;
 311        }
 312
 313        return insn - insn_buf;
 314}
 315
 316static bool convert_bpf_extensions(struct sock_filter *fp,
 317                                   struct bpf_insn **insnp)
 318{
 319        struct bpf_insn *insn = *insnp;
 320        u32 cnt;
 321
 322        switch (fp->k) {
 323        case SKF_AD_OFF + SKF_AD_PROTOCOL:
 324                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);
 325
 326                /* A = *(u16 *) (CTX + offsetof(protocol)) */
 327                *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
 328                                      offsetof(struct sk_buff, protocol));
 329                /* A = ntohs(A) [emitting a nop or swap16] */
 330                *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
 331                break;
 332
 333        case SKF_AD_OFF + SKF_AD_PKTTYPE:
 334                cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
 335                insn += cnt - 1;
 336                break;
 337
 338        case SKF_AD_OFF + SKF_AD_IFINDEX:
 339        case SKF_AD_OFF + SKF_AD_HATYPE:
 340                BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
 341                BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, type) != 2);
 342
 343                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
 344                                      BPF_REG_TMP, BPF_REG_CTX,
 345                                      offsetof(struct sk_buff, dev));
 346                /* if (tmp != 0) goto pc + 1 */
 347                *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
 348                *insn++ = BPF_EXIT_INSN();
 349                if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
 350                        *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
 351                                            offsetof(struct net_device, ifindex));
 352                else
 353                        *insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
 354                                            offsetof(struct net_device, type));
 355                break;
 356
 357        case SKF_AD_OFF + SKF_AD_MARK:
 358                cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
 359                insn += cnt - 1;
 360                break;
 361
 362        case SKF_AD_OFF + SKF_AD_RXHASH:
 363                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);
 364
 365                *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
 366                                    offsetof(struct sk_buff, hash));
 367                break;
 368
 369        case SKF_AD_OFF + SKF_AD_QUEUE:
 370                cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
 371                insn += cnt - 1;
 372                break;
 373
 374        case SKF_AD_OFF + SKF_AD_VLAN_TAG:
 375                cnt = convert_skb_access(SKF_AD_VLAN_TAG,
 376                                         BPF_REG_A, BPF_REG_CTX, insn);
 377                insn += cnt - 1;
 378                break;
 379
 380        case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
 381                cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
 382                                         BPF_REG_A, BPF_REG_CTX, insn);
 383                insn += cnt - 1;
 384                break;
 385
 386        case SKF_AD_OFF + SKF_AD_VLAN_TPID:
 387                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);
 388
 389                /* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
 390                *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
 391                                      offsetof(struct sk_buff, vlan_proto));
 392                /* A = ntohs(A) [emitting a nop or swap16] */
 393                *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
 394                break;
 395
 396        case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
 397        case SKF_AD_OFF + SKF_AD_NLATTR:
 398        case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
 399        case SKF_AD_OFF + SKF_AD_CPU:
 400        case SKF_AD_OFF + SKF_AD_RANDOM:
 401                /* arg1 = CTX */
 402                *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
 403                /* arg2 = A */
 404                *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
 405                /* arg3 = X */
 406                *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
 407                /* Emit call(arg1=CTX, arg2=A, arg3=X) */
 408                switch (fp->k) {
 409                case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
 410                        *insn = BPF_EMIT_CALL(bpf_skb_get_pay_offset);
 411                        break;
 412                case SKF_AD_OFF + SKF_AD_NLATTR:
 413                        *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr);
 414                        break;
 415                case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
 416                        *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr_nest);
 417                        break;
 418                case SKF_AD_OFF + SKF_AD_CPU:
 419                        *insn = BPF_EMIT_CALL(bpf_get_raw_cpu_id);
 420                        break;
 421                case SKF_AD_OFF + SKF_AD_RANDOM:
 422                        *insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
 423                        bpf_user_rnd_init_once();
 424                        break;
 425                }
 426                break;
 427
 428        case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
 429                /* A ^= X */
 430                *insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
 431                break;
 432
 433        default:
 434                /* This is just a dummy call to avoid letting the compiler
 435                 * evict __bpf_call_base() as an optimization. Placed here
 436                 * where no-one bothers.
 437                 */
 438                BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
 439                return false;
 440        }
 441
 442        *insnp = insn;
 443        return true;
 444}
 445
 446static bool convert_bpf_ld_abs(struct sock_filter *fp, struct bpf_insn **insnp)
 447{
 448        const bool unaligned_ok = IS_BUILTIN(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS);
 449        int size = bpf_size_to_bytes(BPF_SIZE(fp->code));
 450        bool endian = BPF_SIZE(fp->code) == BPF_H ||
 451                      BPF_SIZE(fp->code) == BPF_W;
 452        bool indirect = BPF_MODE(fp->code) == BPF_IND;
 453        const int ip_align = NET_IP_ALIGN;
 454        struct bpf_insn *insn = *insnp;
 455        int offset = fp->k;
 456
 457        if (!indirect &&
 458            ((unaligned_ok && offset >= 0) ||
 459             (!unaligned_ok && offset >= 0 &&
 460              offset + ip_align >= 0 &&
 461              offset + ip_align % size == 0))) {
 462                bool ldx_off_ok = offset <= S16_MAX;
 463
 464                *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_H);
 465                *insn++ = BPF_ALU64_IMM(BPF_SUB, BPF_REG_TMP, offset);
 466                *insn++ = BPF_JMP_IMM(BPF_JSLT, BPF_REG_TMP,
 467                                      size, 2 + endian + (!ldx_off_ok * 2));
 468                if (ldx_off_ok) {
 469                        *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
 470                                              BPF_REG_D, offset);
 471                } else {
 472                        *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_D);
 473                        *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_TMP, offset);
 474                        *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
 475                                              BPF_REG_TMP, 0);
 476                }
 477                if (endian)
 478                        *insn++ = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, size * 8);
 479                *insn++ = BPF_JMP_A(8);
 480        }
 481
 482        *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
 483        *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_D);
 484        *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_H);
 485        if (!indirect) {
 486                *insn++ = BPF_MOV64_IMM(BPF_REG_ARG4, offset);
 487        } else {
 488                *insn++ = BPF_MOV64_REG(BPF_REG_ARG4, BPF_REG_X);
 489                if (fp->k)
 490                        *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_ARG4, offset);
 491        }
 492
 493        switch (BPF_SIZE(fp->code)) {
 494        case BPF_B:
 495                *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8);
 496                break;
 497        case BPF_H:
 498                *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16);
 499                break;
 500        case BPF_W:
 501                *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32);
 502                break;
 503        default:
 504                return false;
 505        }
 506
 507        *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_A, 0, 2);
 508        *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
 509        *insn   = BPF_EXIT_INSN();
 510
 511        *insnp = insn;
 512        return true;
 513}
 514
 515/**
 516 *      bpf_convert_filter - convert filter program
 517 *      @prog: the user passed filter program
 518 *      @len: the length of the user passed filter program
 519 *      @new_prog: allocated 'struct bpf_prog' or NULL
 520 *      @new_len: pointer to store length of converted program
 521 *      @seen_ld_abs: bool whether we've seen ld_abs/ind
 522 *
 523 * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
 524 * style extended BPF (eBPF).
 525 * Conversion workflow:
 526 *
 527 * 1) First pass for calculating the new program length:
 528 *   bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs)
 529 *
 530 * 2) 2nd pass to remap in two passes: 1st pass finds new
 531 *    jump offsets, 2nd pass remapping:
 532 *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len, &seen_ld_abs)
 533 */
 534static int bpf_convert_filter(struct sock_filter *prog, int len,
 535                              struct bpf_prog *new_prog, int *new_len,
 536                              bool *seen_ld_abs)
 537{
 538        int new_flen = 0, pass = 0, target, i, stack_off;
 539        struct bpf_insn *new_insn, *first_insn = NULL;
 540        struct sock_filter *fp;
 541        int *addrs = NULL;
 542        u8 bpf_src;
 543
 544        BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
 545        BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
 546
 547        if (len <= 0 || len > BPF_MAXINSNS)
 548                return -EINVAL;
 549
 550        if (new_prog) {
 551                first_insn = new_prog->insnsi;
 552                addrs = kcalloc(len, sizeof(*addrs),
 553                                GFP_KERNEL | __GFP_NOWARN);
 554                if (!addrs)
 555                        return -ENOMEM;
 556        }
 557
 558do_pass:
 559        new_insn = first_insn;
 560        fp = prog;
 561
 562        /* Classic BPF related prologue emission. */
 563        if (new_prog) {
 564                /* Classic BPF expects A and X to be reset first. These need
 565                 * to be guaranteed to be the first two instructions.
 566                 */
 567                *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
 568                *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
 569
 570                /* All programs must keep CTX in callee saved BPF_REG_CTX.
 571                 * In eBPF case it's done by the compiler, here we need to
 572                 * do this ourself. Initial CTX is present in BPF_REG_ARG1.
 573                 */
 574                *new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
 575                if (*seen_ld_abs) {
 576                        /* For packet access in classic BPF, cache skb->data
 577                         * in callee-saved BPF R8 and skb->len - skb->data_len
 578                         * (headlen) in BPF R9. Since classic BPF is read-only
 579                         * on CTX, we only need to cache it once.
 580                         */
 581                        *new_insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
 582                                                  BPF_REG_D, BPF_REG_CTX,
 583                                                  offsetof(struct sk_buff, data));
 584                        *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_H, BPF_REG_CTX,
 585                                                  offsetof(struct sk_buff, len));
 586                        *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_TMP, BPF_REG_CTX,
 587                                                  offsetof(struct sk_buff, data_len));
 588                        *new_insn++ = BPF_ALU32_REG(BPF_SUB, BPF_REG_H, BPF_REG_TMP);
 589                }
 590        } else {
 591                new_insn += 3;
 592        }
 593
 594        for (i = 0; i < len; fp++, i++) {
 595                struct bpf_insn tmp_insns[32] = { };
 596                struct bpf_insn *insn = tmp_insns;
 597
 598                if (addrs)
 599                        addrs[i] = new_insn - first_insn;
 600
 601                switch (fp->code) {
 602                /* All arithmetic insns and skb loads map as-is. */
 603                case BPF_ALU | BPF_ADD | BPF_X:
 604                case BPF_ALU | BPF_ADD | BPF_K:
 605                case BPF_ALU | BPF_SUB | BPF_X:
 606                case BPF_ALU | BPF_SUB | BPF_K:
 607                case BPF_ALU | BPF_AND | BPF_X:
 608                case BPF_ALU | BPF_AND | BPF_K:
 609                case BPF_ALU | BPF_OR | BPF_X:
 610                case BPF_ALU | BPF_OR | BPF_K:
 611                case BPF_ALU | BPF_LSH | BPF_X:
 612                case BPF_ALU | BPF_LSH | BPF_K:
 613                case BPF_ALU | BPF_RSH | BPF_X:
 614                case BPF_ALU | BPF_RSH | BPF_K:
 615                case BPF_ALU | BPF_XOR | BPF_X:
 616                case BPF_ALU | BPF_XOR | BPF_K:
 617                case BPF_ALU | BPF_MUL | BPF_X:
 618                case BPF_ALU | BPF_MUL | BPF_K:
 619                case BPF_ALU | BPF_DIV | BPF_X:
 620                case BPF_ALU | BPF_DIV | BPF_K:
 621                case BPF_ALU | BPF_MOD | BPF_X:
 622                case BPF_ALU | BPF_MOD | BPF_K:
 623                case BPF_ALU | BPF_NEG:
 624                case BPF_LD | BPF_ABS | BPF_W:
 625                case BPF_LD | BPF_ABS | BPF_H:
 626                case BPF_LD | BPF_ABS | BPF_B:
 627                case BPF_LD | BPF_IND | BPF_W:
 628                case BPF_LD | BPF_IND | BPF_H:
 629                case BPF_LD | BPF_IND | BPF_B:
 630                        /* Check for overloaded BPF extension and
 631                         * directly convert it if found, otherwise
 632                         * just move on with mapping.
 633                         */
 634                        if (BPF_CLASS(fp->code) == BPF_LD &&
 635                            BPF_MODE(fp->code) == BPF_ABS &&
 636                            convert_bpf_extensions(fp, &insn))
 637                                break;
 638                        if (BPF_CLASS(fp->code) == BPF_LD &&
 639                            convert_bpf_ld_abs(fp, &insn)) {
 640                                *seen_ld_abs = true;
 641                                break;
 642                        }
 643
 644                        if (fp->code == (BPF_ALU | BPF_DIV | BPF_X) ||
 645                            fp->code == (BPF_ALU | BPF_MOD | BPF_X)) {
 646                                *insn++ = BPF_MOV32_REG(BPF_REG_X, BPF_REG_X);
 647                                /* Error with exception code on div/mod by 0.
 648                                 * For cBPF programs, this was always return 0.
 649                                 */
 650                                *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_X, 0, 2);
 651                                *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
 652                                *insn++ = BPF_EXIT_INSN();
 653                        }
 654
 655                        *insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
 656                        break;
 657
 658                /* Jump transformation cannot use BPF block macros
 659                 * everywhere as offset calculation and target updates
 660                 * require a bit more work than the rest, i.e. jump
 661                 * opcodes map as-is, but offsets need adjustment.
 662                 */
 663
 664#define BPF_EMIT_JMP                                                    \
 665        do {                                                            \
 666                const s32 off_min = S16_MIN, off_max = S16_MAX;         \
 667                s32 off;                                                \
 668                                                                        \
 669                if (target >= len || target < 0)                        \
 670                        goto err;                                       \
 671                off = addrs ? addrs[target] - addrs[i] - 1 : 0;         \
 672                /* Adjust pc relative offset for 2nd or 3rd insn. */    \
 673                off -= insn - tmp_insns;                                \
 674                /* Reject anything not fitting into insn->off. */       \
 675                if (off < off_min || off > off_max)                     \
 676                        goto err;                                       \
 677                insn->off = off;                                        \
 678        } while (0)
 679
 680                case BPF_JMP | BPF_JA:
 681                        target = i + fp->k + 1;
 682                        insn->code = fp->code;
 683                        BPF_EMIT_JMP;
 684                        break;
 685
 686                case BPF_JMP | BPF_JEQ | BPF_K:
 687                case BPF_JMP | BPF_JEQ | BPF_X:
 688                case BPF_JMP | BPF_JSET | BPF_K:
 689                case BPF_JMP | BPF_JSET | BPF_X:
 690                case BPF_JMP | BPF_JGT | BPF_K:
 691                case BPF_JMP | BPF_JGT | BPF_X:
 692                case BPF_JMP | BPF_JGE | BPF_K:
 693                case BPF_JMP | BPF_JGE | BPF_X:
 694                        if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
 695                                /* BPF immediates are signed, zero extend
 696                                 * immediate into tmp register and use it
 697                                 * in compare insn.
 698                                 */
 699                                *insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
 700
 701                                insn->dst_reg = BPF_REG_A;
 702                                insn->src_reg = BPF_REG_TMP;
 703                                bpf_src = BPF_X;
 704                        } else {
 705                                insn->dst_reg = BPF_REG_A;
 706                                insn->imm = fp->k;
 707                                bpf_src = BPF_SRC(fp->code);
 708                                insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
 709                        }
 710
 711                        /* Common case where 'jump_false' is next insn. */
 712                        if (fp->jf == 0) {
 713                                insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
 714                                target = i + fp->jt + 1;
 715                                BPF_EMIT_JMP;
 716                                break;
 717                        }
 718
 719                        /* Convert some jumps when 'jump_true' is next insn. */
 720                        if (fp->jt == 0) {
 721                                switch (BPF_OP(fp->code)) {
 722                                case BPF_JEQ:
 723                                        insn->code = BPF_JMP | BPF_JNE | bpf_src;
 724                                        break;
 725                                case BPF_JGT:
 726                                        insn->code = BPF_JMP | BPF_JLE | bpf_src;
 727                                        break;
 728                                case BPF_JGE:
 729                                        insn->code = BPF_JMP | BPF_JLT | bpf_src;
 730                                        break;
 731                                default:
 732                                        goto jmp_rest;
 733                                }
 734
 735                                target = i + fp->jf + 1;
 736                                BPF_EMIT_JMP;
 737                                break;
 738                        }
 739jmp_rest:
 740                        /* Other jumps are mapped into two insns: Jxx and JA. */
 741                        target = i + fp->jt + 1;
 742                        insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
 743                        BPF_EMIT_JMP;
 744                        insn++;
 745
 746                        insn->code = BPF_JMP | BPF_JA;
 747                        target = i + fp->jf + 1;
 748                        BPF_EMIT_JMP;
 749                        break;
 750
 751                /* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
 752                case BPF_LDX | BPF_MSH | BPF_B: {
 753                        struct sock_filter tmp = {
 754                                .code   = BPF_LD | BPF_ABS | BPF_B,
 755                                .k      = fp->k,
 756                        };
 757
 758                        *seen_ld_abs = true;
 759
 760                        /* X = A */
 761                        *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
 762                        /* A = BPF_R0 = *(u8 *) (skb->data + K) */
 763                        convert_bpf_ld_abs(&tmp, &insn);
 764                        insn++;
 765                        /* A &= 0xf */
 766                        *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
 767                        /* A <<= 2 */
 768                        *insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
 769                        /* tmp = X */
 770                        *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_X);
 771                        /* X = A */
 772                        *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
 773                        /* A = tmp */
 774                        *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
 775                        break;
 776                }
 777                /* RET_K is remaped into 2 insns. RET_A case doesn't need an
 778                 * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
 779                 */
 780                case BPF_RET | BPF_A:
 781                case BPF_RET | BPF_K:
 782                        if (BPF_RVAL(fp->code) == BPF_K)
 783                                *insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
 784                                                        0, fp->k);
 785                        *insn = BPF_EXIT_INSN();
 786                        break;
 787
 788                /* Store to stack. */
 789                case BPF_ST:
 790                case BPF_STX:
 791                        stack_off = fp->k * 4  + 4;
 792                        *insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
 793                                            BPF_ST ? BPF_REG_A : BPF_REG_X,
 794                                            -stack_off);
 795                        /* check_load_and_stores() verifies that classic BPF can
 796                         * load from stack only after write, so tracking
 797                         * stack_depth for ST|STX insns is enough
 798                         */
 799                        if (new_prog && new_prog->aux->stack_depth < stack_off)
 800                                new_prog->aux->stack_depth = stack_off;
 801                        break;
 802
 803                /* Load from stack. */
 804                case BPF_LD | BPF_MEM:
 805                case BPF_LDX | BPF_MEM:
 806                        stack_off = fp->k * 4  + 4;
 807                        *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
 808                                            BPF_REG_A : BPF_REG_X, BPF_REG_FP,
 809                                            -stack_off);
 810                        break;
 811
 812                /* A = K or X = K */
 813                case BPF_LD | BPF_IMM:
 814                case BPF_LDX | BPF_IMM:
 815                        *insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
 816                                              BPF_REG_A : BPF_REG_X, fp->k);
 817                        break;
 818
 819                /* X = A */
 820                case BPF_MISC | BPF_TAX:
 821                        *insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
 822                        break;
 823
 824                /* A = X */
 825                case BPF_MISC | BPF_TXA:
 826                        *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
 827                        break;
 828
 829                /* A = skb->len or X = skb->len */
 830                case BPF_LD | BPF_W | BPF_LEN:
 831                case BPF_LDX | BPF_W | BPF_LEN:
 832                        *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
 833                                            BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
 834                                            offsetof(struct sk_buff, len));
 835                        break;
 836
 837                /* Access seccomp_data fields. */
 838                case BPF_LDX | BPF_ABS | BPF_W:
 839                        /* A = *(u32 *) (ctx + K) */
 840                        *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
 841                        break;
 842
 843                /* Unknown instruction. */
 844                default:
 845                        goto err;
 846                }
 847
 848                insn++;
 849                if (new_prog)
 850                        memcpy(new_insn, tmp_insns,
 851                               sizeof(*insn) * (insn - tmp_insns));
 852                new_insn += insn - tmp_insns;
 853        }
 854
 855        if (!new_prog) {
 856                /* Only calculating new length. */
 857                *new_len = new_insn - first_insn;
 858                if (*seen_ld_abs)
 859                        *new_len += 4; /* Prologue bits. */
 860                return 0;
 861        }
 862
 863        pass++;
 864        if (new_flen != new_insn - first_insn) {
 865                new_flen = new_insn - first_insn;
 866                if (pass > 2)
 867                        goto err;
 868                goto do_pass;
 869        }
 870
 871        kfree(addrs);
 872        BUG_ON(*new_len != new_flen);
 873        return 0;
 874err:
 875        kfree(addrs);
 876        return -EINVAL;
 877}
 878
 879/* Security:
 880 *
 881 * As we dont want to clear mem[] array for each packet going through
 882 * __bpf_prog_run(), we check that filter loaded by user never try to read
 883 * a cell if not previously written, and we check all branches to be sure
 884 * a malicious user doesn't try to abuse us.
 885 */
 886static int check_load_and_stores(const struct sock_filter *filter, int flen)
 887{
 888        u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
 889        int pc, ret = 0;
 890
 891        BUILD_BUG_ON(BPF_MEMWORDS > 16);
 892
 893        masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
 894        if (!masks)
 895                return -ENOMEM;
 896
 897        memset(masks, 0xff, flen * sizeof(*masks));
 898
 899        for (pc = 0; pc < flen; pc++) {
 900                memvalid &= masks[pc];
 901
 902                switch (filter[pc].code) {
 903                case BPF_ST:
 904                case BPF_STX:
 905                        memvalid |= (1 << filter[pc].k);
 906                        break;
 907                case BPF_LD | BPF_MEM:
 908                case BPF_LDX | BPF_MEM:
 909                        if (!(memvalid & (1 << filter[pc].k))) {
 910                                ret = -EINVAL;
 911                                goto error;
 912                        }
 913                        break;
 914                case BPF_JMP | BPF_JA:
 915                        /* A jump must set masks on target */
 916                        masks[pc + 1 + filter[pc].k] &= memvalid;
 917                        memvalid = ~0;
 918                        break;
 919                case BPF_JMP | BPF_JEQ | BPF_K:
 920                case BPF_JMP | BPF_JEQ | BPF_X:
 921                case BPF_JMP | BPF_JGE | BPF_K:
 922                case BPF_JMP | BPF_JGE | BPF_X:
 923                case BPF_JMP | BPF_JGT | BPF_K:
 924                case BPF_JMP | BPF_JGT | BPF_X:
 925                case BPF_JMP | BPF_JSET | BPF_K:
 926                case BPF_JMP | BPF_JSET | BPF_X:
 927                        /* A jump must set masks on targets */
 928                        masks[pc + 1 + filter[pc].jt] &= memvalid;
 929                        masks[pc + 1 + filter[pc].jf] &= memvalid;
 930                        memvalid = ~0;
 931                        break;
 932                }
 933        }
 934error:
 935        kfree(masks);
 936        return ret;
 937}
 938
 939static bool chk_code_allowed(u16 code_to_probe)
 940{
 941        static const bool codes[] = {
 942                /* 32 bit ALU operations */
 943                [BPF_ALU | BPF_ADD | BPF_K] = true,
 944                [BPF_ALU | BPF_ADD | BPF_X] = true,
 945                [BPF_ALU | BPF_SUB | BPF_K] = true,
 946                [BPF_ALU | BPF_SUB | BPF_X] = true,
 947                [BPF_ALU | BPF_MUL | BPF_K] = true,
 948                [BPF_ALU | BPF_MUL | BPF_X] = true,
 949                [BPF_ALU | BPF_DIV | BPF_K] = true,
 950                [BPF_ALU | BPF_DIV | BPF_X] = true,
 951                [BPF_ALU | BPF_MOD | BPF_K] = true,
 952                [BPF_ALU | BPF_MOD | BPF_X] = true,
 953                [BPF_ALU | BPF_AND | BPF_K] = true,
 954                [BPF_ALU | BPF_AND | BPF_X] = true,
 955                [BPF_ALU | BPF_OR | BPF_K] = true,
 956                [BPF_ALU | BPF_OR | BPF_X] = true,
 957                [BPF_ALU | BPF_XOR | BPF_K] = true,
 958                [BPF_ALU | BPF_XOR | BPF_X] = true,
 959                [BPF_ALU | BPF_LSH | BPF_K] = true,
 960                [BPF_ALU | BPF_LSH | BPF_X] = true,
 961                [BPF_ALU | BPF_RSH | BPF_K] = true,
 962                [BPF_ALU | BPF_RSH | BPF_X] = true,
 963                [BPF_ALU | BPF_NEG] = true,
 964                /* Load instructions */
 965                [BPF_LD | BPF_W | BPF_ABS] = true,
 966                [BPF_LD | BPF_H | BPF_ABS] = true,
 967                [BPF_LD | BPF_B | BPF_ABS] = true,
 968                [BPF_LD | BPF_W | BPF_LEN] = true,
 969                [BPF_LD | BPF_W | BPF_IND] = true,
 970                [BPF_LD | BPF_H | BPF_IND] = true,
 971                [BPF_LD | BPF_B | BPF_IND] = true,
 972                [BPF_LD | BPF_IMM] = true,
 973                [BPF_LD | BPF_MEM] = true,
 974                [BPF_LDX | BPF_W | BPF_LEN] = true,
 975                [BPF_LDX | BPF_B | BPF_MSH] = true,
 976                [BPF_LDX | BPF_IMM] = true,
 977                [BPF_LDX | BPF_MEM] = true,
 978                /* Store instructions */
 979                [BPF_ST] = true,
 980                [BPF_STX] = true,
 981                /* Misc instructions */
 982                [BPF_MISC | BPF_TAX] = true,
 983                [BPF_MISC | BPF_TXA] = true,
 984                /* Return instructions */
 985                [BPF_RET | BPF_K] = true,
 986                [BPF_RET | BPF_A] = true,
 987                /* Jump instructions */
 988                [BPF_JMP | BPF_JA] = true,
 989                [BPF_JMP | BPF_JEQ | BPF_K] = true,
 990                [BPF_JMP | BPF_JEQ | BPF_X] = true,
 991                [BPF_JMP | BPF_JGE | BPF_K] = true,
 992                [BPF_JMP | BPF_JGE | BPF_X] = true,
 993                [BPF_JMP | BPF_JGT | BPF_K] = true,
 994                [BPF_JMP | BPF_JGT | BPF_X] = true,
 995                [BPF_JMP | BPF_JSET | BPF_K] = true,
 996                [BPF_JMP | BPF_JSET | BPF_X] = true,
 997        };
 998
 999        if (code_to_probe >= ARRAY_SIZE(codes))
1000                return false;
1001
1002        return codes[code_to_probe];
1003}
1004
1005static bool bpf_check_basics_ok(const struct sock_filter *filter,
1006                                unsigned int flen)
1007{
1008        if (filter == NULL)
1009                return false;
1010        if (flen == 0 || flen > BPF_MAXINSNS)
1011                return false;
1012
1013        return true;
1014}
1015
1016/**
1017 *      bpf_check_classic - verify socket filter code
1018 *      @filter: filter to verify
1019 *      @flen: length of filter
1020 *
1021 * Check the user's filter code. If we let some ugly
1022 * filter code slip through kaboom! The filter must contain
1023 * no references or jumps that are out of range, no illegal
1024 * instructions, and must end with a RET instruction.
1025 *
1026 * All jumps are forward as they are not signed.
1027 *
1028 * Returns 0 if the rule set is legal or -EINVAL if not.
1029 */
1030static int bpf_check_classic(const struct sock_filter *filter,
1031                             unsigned int flen)
1032{
1033        bool anc_found;
1034        int pc;
1035
1036        /* Check the filter code now */
1037        for (pc = 0; pc < flen; pc++) {
1038                const struct sock_filter *ftest = &filter[pc];
1039
1040                /* May we actually operate on this code? */
1041                if (!chk_code_allowed(ftest->code))
1042                        return -EINVAL;
1043
1044                /* Some instructions need special checks */
1045                switch (ftest->code) {
1046                case BPF_ALU | BPF_DIV | BPF_K:
1047                case BPF_ALU | BPF_MOD | BPF_K:
1048                        /* Check for division by zero */
1049                        if (ftest->k == 0)
1050                                return -EINVAL;
1051                        break;
1052                case BPF_ALU | BPF_LSH | BPF_K:
1053                case BPF_ALU | BPF_RSH | BPF_K:
1054                        if (ftest->k >= 32)
1055                                return -EINVAL;
1056                        break;
1057                case BPF_LD | BPF_MEM:
1058                case BPF_LDX | BPF_MEM:
1059                case BPF_ST:
1060                case BPF_STX:
1061                        /* Check for invalid memory addresses */
1062                        if (ftest->k >= BPF_MEMWORDS)
1063                                return -EINVAL;
1064                        break;
1065                case BPF_JMP | BPF_JA:
1066                        /* Note, the large ftest->k might cause loops.
1067                         * Compare this with conditional jumps below,
1068                         * where offsets are limited. --ANK (981016)
1069                         */
1070                        if (ftest->k >= (unsigned int)(flen - pc - 1))
1071                                return -EINVAL;
1072                        break;
1073                case BPF_JMP | BPF_JEQ | BPF_K:
1074                case BPF_JMP | BPF_JEQ | BPF_X:
1075                case BPF_JMP | BPF_JGE | BPF_K:
1076                case BPF_JMP | BPF_JGE | BPF_X:
1077                case BPF_JMP | BPF_JGT | BPF_K:
1078                case BPF_JMP | BPF_JGT | BPF_X:
1079                case BPF_JMP | BPF_JSET | BPF_K:
1080                case BPF_JMP | BPF_JSET | BPF_X:
1081                        /* Both conditionals must be safe */
1082                        if (pc + ftest->jt + 1 >= flen ||
1083                            pc + ftest->jf + 1 >= flen)
1084                                return -EINVAL;
1085                        break;
1086                case BPF_LD | BPF_W | BPF_ABS:
1087                case BPF_LD | BPF_H | BPF_ABS:
1088                case BPF_LD | BPF_B | BPF_ABS:
1089                        anc_found = false;
1090                        if (bpf_anc_helper(ftest) & BPF_ANC)
1091                                anc_found = true;
1092                        /* Ancillary operation unknown or unsupported */
1093                        if (anc_found == false && ftest->k >= SKF_AD_OFF)
1094                                return -EINVAL;
1095                }
1096        }
1097
1098        /* Last instruction must be a RET code */
1099        switch (filter[flen - 1].code) {
1100        case BPF_RET | BPF_K:
1101        case BPF_RET | BPF_A:
1102                return check_load_and_stores(filter, flen);
1103        }
1104
1105        return -EINVAL;
1106}
1107
1108static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
1109                                      const struct sock_fprog *fprog)
1110{
1111        unsigned int fsize = bpf_classic_proglen(fprog);
1112        struct sock_fprog_kern *fkprog;
1113
1114        fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
1115        if (!fp->orig_prog)
1116                return -ENOMEM;
1117
1118        fkprog = fp->orig_prog;
1119        fkprog->len = fprog->len;
1120
1121        fkprog->filter = kmemdup(fp->insns, fsize,
1122                                 GFP_KERNEL | __GFP_NOWARN);
1123        if (!fkprog->filter) {
1124                kfree(fp->orig_prog);
1125                return -ENOMEM;
1126        }
1127
1128        return 0;
1129}
1130
1131static void bpf_release_orig_filter(struct bpf_prog *fp)
1132{
1133        struct sock_fprog_kern *fprog = fp->orig_prog;
1134
1135        if (fprog) {
1136                kfree(fprog->filter);
1137                kfree(fprog);
1138        }
1139}
1140
1141static void __bpf_prog_release(struct bpf_prog *prog)
1142{
1143        if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
1144                bpf_prog_put(prog);
1145        } else {
1146                bpf_release_orig_filter(prog);
1147                bpf_prog_free(prog);
1148        }
1149}
1150
1151static void __sk_filter_release(struct sk_filter *fp)
1152{
1153        __bpf_prog_release(fp->prog);
1154        kfree(fp);
1155}
1156
1157/**
1158 *      sk_filter_release_rcu - Release a socket filter by rcu_head
1159 *      @rcu: rcu_head that contains the sk_filter to free
1160 */
1161static void sk_filter_release_rcu(struct rcu_head *rcu)
1162{
1163        struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
1164
1165        __sk_filter_release(fp);
1166}
1167
1168/**
1169 *      sk_filter_release - release a socket filter
1170 *      @fp: filter to remove
1171 *
1172 *      Remove a filter from a socket and release its resources.
1173 */
1174static void sk_filter_release(struct sk_filter *fp)
1175{
1176        if (refcount_dec_and_test(&fp->refcnt))
1177                call_rcu(&fp->rcu, sk_filter_release_rcu);
1178}
1179
1180void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
1181{
1182        u32 filter_size = bpf_prog_size(fp->prog->len);
1183
1184        atomic_sub(filter_size, &sk->sk_omem_alloc);
1185        sk_filter_release(fp);
1186}
1187
1188/* try to charge the socket memory if there is space available
1189 * return true on success
1190 */
1191static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1192{
1193        u32 filter_size = bpf_prog_size(fp->prog->len);
1194
1195        /* same check as in sock_kmalloc() */
1196        if (filter_size <= sysctl_optmem_max &&
1197            atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
1198                atomic_add(filter_size, &sk->sk_omem_alloc);
1199                return true;
1200        }
1201        return false;
1202}
1203
1204bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1205{
1206        if (!refcount_inc_not_zero(&fp->refcnt))
1207                return false;
1208
1209        if (!__sk_filter_charge(sk, fp)) {
1210                sk_filter_release(fp);
1211                return false;
1212        }
1213        return true;
1214}
1215
1216static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
1217{
1218        struct sock_filter *old_prog;
1219        struct bpf_prog *old_fp;
1220        int err, new_len, old_len = fp->len;
1221        bool seen_ld_abs = false;
1222
1223        /* We are free to overwrite insns et al right here as it
1224         * won't be used at this point in time anymore internally
1225         * after the migration to the internal BPF instruction
1226         * representation.
1227         */
1228        BUILD_BUG_ON(sizeof(struct sock_filter) !=
1229                     sizeof(struct bpf_insn));
1230
1231        /* Conversion cannot happen on overlapping memory areas,
1232         * so we need to keep the user BPF around until the 2nd
1233         * pass. At this time, the user BPF is stored in fp->insns.
1234         */
1235        old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
1236                           GFP_KERNEL | __GFP_NOWARN);
1237        if (!old_prog) {
1238                err = -ENOMEM;
1239                goto out_err;
1240        }
1241
1242        /* 1st pass: calculate the new program length. */
1243        err = bpf_convert_filter(old_prog, old_len, NULL, &new_len,
1244                                 &seen_ld_abs);
1245        if (err)
1246                goto out_err_free;
1247
1248        /* Expand fp for appending the new filter representation. */
1249        old_fp = fp;
1250        fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1251        if (!fp) {
1252                /* The old_fp is still around in case we couldn't
1253                 * allocate new memory, so uncharge on that one.
1254                 */
1255                fp = old_fp;
1256                err = -ENOMEM;
1257                goto out_err_free;
1258        }
1259
1260        fp->len = new_len;
1261
1262        /* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1263        err = bpf_convert_filter(old_prog, old_len, fp, &new_len,
1264                                 &seen_ld_abs);
1265        if (err)
1266                /* 2nd bpf_convert_filter() can fail only if it fails
1267                 * to allocate memory, remapping must succeed. Note,
1268                 * that at this time old_fp has already been released
1269                 * by krealloc().
1270                 */
1271                goto out_err_free;
1272
1273        fp = bpf_prog_select_runtime(fp, &err);
1274        if (err)
1275                goto out_err_free;
1276
1277        kfree(old_prog);
1278        return fp;
1279
1280out_err_free:
1281        kfree(old_prog);
1282out_err:
1283        __bpf_prog_release(fp);
1284        return ERR_PTR(err);
1285}
1286
1287static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
1288                                           bpf_aux_classic_check_t trans)
1289{
1290        int err;
1291
1292        fp->bpf_func = NULL;
1293        fp->jited = 0;
1294
1295        err = bpf_check_classic(fp->insns, fp->len);
1296        if (err) {
1297                __bpf_prog_release(fp);
1298                return ERR_PTR(err);
1299        }
1300
1301        /* There might be additional checks and transformations
1302         * needed on classic filters, f.e. in case of seccomp.
1303         */
1304        if (trans) {
1305                err = trans(fp->insns, fp->len);
1306                if (err) {
1307                        __bpf_prog_release(fp);
1308                        return ERR_PTR(err);
1309                }
1310        }
1311
1312        /* Probe if we can JIT compile the filter and if so, do
1313         * the compilation of the filter.
1314         */
1315        bpf_jit_compile(fp);
1316
1317        /* JIT compiler couldn't process this filter, so do the
1318         * internal BPF translation for the optimized interpreter.
1319         */
1320        if (!fp->jited)
1321                fp = bpf_migrate_filter(fp);
1322
1323        return fp;
1324}
1325
1326/**
1327 *      bpf_prog_create - create an unattached filter
1328 *      @pfp: the unattached filter that is created
1329 *      @fprog: the filter program
1330 *
1331 * Create a filter independent of any socket. We first run some
1332 * sanity checks on it to make sure it does not explode on us later.
1333 * If an error occurs or there is insufficient memory for the filter
1334 * a negative errno code is returned. On success the return is zero.
1335 */
1336int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1337{
1338        unsigned int fsize = bpf_classic_proglen(fprog);
1339        struct bpf_prog *fp;
1340
1341        /* Make sure new filter is there and in the right amounts. */
1342        if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1343                return -EINVAL;
1344
1345        fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1346        if (!fp)
1347                return -ENOMEM;
1348
1349        memcpy(fp->insns, fprog->filter, fsize);
1350
1351        fp->len = fprog->len;
1352        /* Since unattached filters are not copied back to user
1353         * space through sk_get_filter(), we do not need to hold
1354         * a copy here, and can spare us the work.
1355         */
1356        fp->orig_prog = NULL;
1357
1358        /* bpf_prepare_filter() already takes care of freeing
1359         * memory in case something goes wrong.
1360         */
1361        fp = bpf_prepare_filter(fp, NULL);
1362        if (IS_ERR(fp))
1363                return PTR_ERR(fp);
1364
1365        *pfp = fp;
1366        return 0;
1367}
1368EXPORT_SYMBOL_GPL(bpf_prog_create);
1369
1370/**
1371 *      bpf_prog_create_from_user - create an unattached filter from user buffer
1372 *      @pfp: the unattached filter that is created
1373 *      @fprog: the filter program
1374 *      @trans: post-classic verifier transformation handler
1375 *      @save_orig: save classic BPF program
1376 *
1377 * This function effectively does the same as bpf_prog_create(), only
1378 * that it builds up its insns buffer from user space provided buffer.
1379 * It also allows for passing a bpf_aux_classic_check_t handler.
1380 */
1381int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1382                              bpf_aux_classic_check_t trans, bool save_orig)
1383{
1384        unsigned int fsize = bpf_classic_proglen(fprog);
1385        struct bpf_prog *fp;
1386        int err;
1387
1388        /* Make sure new filter is there and in the right amounts. */
1389        if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1390                return -EINVAL;
1391
1392        fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1393        if (!fp)
1394                return -ENOMEM;
1395
1396        if (copy_from_user(fp->insns, fprog->filter, fsize)) {
1397                __bpf_prog_free(fp);
1398                return -EFAULT;
1399        }
1400
1401        fp->len = fprog->len;
1402        fp->orig_prog = NULL;
1403
1404        if (save_orig) {
1405                err = bpf_prog_store_orig_filter(fp, fprog);
1406                if (err) {
1407                        __bpf_prog_free(fp);
1408                        return -ENOMEM;
1409                }
1410        }
1411
1412        /* bpf_prepare_filter() already takes care of freeing
1413         * memory in case something goes wrong.
1414         */
1415        fp = bpf_prepare_filter(fp, trans);
1416        if (IS_ERR(fp))
1417                return PTR_ERR(fp);
1418
1419        *pfp = fp;
1420        return 0;
1421}
1422EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1423
1424void bpf_prog_destroy(struct bpf_prog *fp)
1425{
1426        __bpf_prog_release(fp);
1427}
1428EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1429
1430static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1431{
1432        struct sk_filter *fp, *old_fp;
1433
1434        fp = kmalloc(sizeof(*fp), GFP_KERNEL);
1435        if (!fp)
1436                return -ENOMEM;
1437
1438        fp->prog = prog;
1439
1440        if (!__sk_filter_charge(sk, fp)) {
1441                kfree(fp);
1442                return -ENOMEM;
1443        }
1444        refcount_set(&fp->refcnt, 1);
1445
1446        old_fp = rcu_dereference_protected(sk->sk_filter,
1447                                           lockdep_sock_is_held(sk));
1448        rcu_assign_pointer(sk->sk_filter, fp);
1449
1450        if (old_fp)
1451                sk_filter_uncharge(sk, old_fp);
1452
1453        return 0;
1454}
1455
1456static
1457struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
1458{
1459        unsigned int fsize = bpf_classic_proglen(fprog);
1460        struct bpf_prog *prog;
1461        int err;
1462
1463        if (sock_flag(sk, SOCK_FILTER_LOCKED))
1464                return ERR_PTR(-EPERM);
1465
1466        /* Make sure new filter is there and in the right amounts. */
1467        if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1468                return ERR_PTR(-EINVAL);
1469
1470        prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1471        if (!prog)
1472                return ERR_PTR(-ENOMEM);
1473
1474        if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1475                __bpf_prog_free(prog);
1476                return ERR_PTR(-EFAULT);
1477        }
1478
1479        prog->len = fprog->len;
1480
1481        err = bpf_prog_store_orig_filter(prog, fprog);
1482        if (err) {
1483                __bpf_prog_free(prog);
1484                return ERR_PTR(-ENOMEM);
1485        }
1486
1487        /* bpf_prepare_filter() already takes care of freeing
1488         * memory in case something goes wrong.
1489         */
1490        return bpf_prepare_filter(prog, NULL);
1491}
1492
1493/**
1494 *      sk_attach_filter - attach a socket filter
1495 *      @fprog: the filter program
1496 *      @sk: the socket to use
1497 *
1498 * Attach the user's filter code. We first run some sanity checks on
1499 * it to make sure it does not explode on us later. If an error
1500 * occurs or there is insufficient memory for the filter a negative
1501 * errno code is returned. On success the return is zero.
1502 */
1503int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1504{
1505        struct bpf_prog *prog = __get_filter(fprog, sk);
1506        int err;
1507
1508        if (IS_ERR(prog))
1509                return PTR_ERR(prog);
1510
1511        err = __sk_attach_prog(prog, sk);
1512        if (err < 0) {
1513                __bpf_prog_release(prog);
1514                return err;
1515        }
1516
1517        return 0;
1518}
1519EXPORT_SYMBOL_GPL(sk_attach_filter);
1520
1521int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1522{
1523        struct bpf_prog *prog = __get_filter(fprog, sk);
1524        int err;
1525
1526        if (IS_ERR(prog))
1527                return PTR_ERR(prog);
1528
1529        if (bpf_prog_size(prog->len) > sysctl_optmem_max)
1530                err = -ENOMEM;
1531        else
1532                err = reuseport_attach_prog(sk, prog);
1533
1534        if (err)
1535                __bpf_prog_release(prog);
1536
1537        return err;
1538}
1539
1540static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
1541{
1542        if (sock_flag(sk, SOCK_FILTER_LOCKED))
1543                return ERR_PTR(-EPERM);
1544
1545        return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1546}
1547
1548int sk_attach_bpf(u32 ufd, struct sock *sk)
1549{
1550        struct bpf_prog *prog = __get_bpf(ufd, sk);
1551        int err;
1552
1553        if (IS_ERR(prog))
1554                return PTR_ERR(prog);
1555
1556        err = __sk_attach_prog(prog, sk);
1557        if (err < 0) {
1558                bpf_prog_put(prog);
1559                return err;
1560        }
1561
1562        return 0;
1563}
1564
1565int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
1566{
1567        struct bpf_prog *prog;
1568        int err;
1569
1570        if (sock_flag(sk, SOCK_FILTER_LOCKED))
1571                return -EPERM;
1572
1573        prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1574        if (IS_ERR(prog) && PTR_ERR(prog) == -EINVAL)
1575                prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SK_REUSEPORT);
1576        if (IS_ERR(prog))
1577                return PTR_ERR(prog);
1578
1579        if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) {
1580                /* Like other non BPF_PROG_TYPE_SOCKET_FILTER
1581                 * bpf prog (e.g. sockmap).  It depends on the
1582                 * limitation imposed by bpf_prog_load().
1583                 * Hence, sysctl_optmem_max is not checked.
1584                 */
1585                if ((sk->sk_type != SOCK_STREAM &&
1586                     sk->sk_type != SOCK_DGRAM) ||
1587                    (sk->sk_protocol != IPPROTO_UDP &&
1588                     sk->sk_protocol != IPPROTO_TCP) ||
1589                    (sk->sk_family != AF_INET &&
1590                     sk->sk_family != AF_INET6)) {
1591                        err = -ENOTSUPP;
1592                        goto err_prog_put;
1593                }
1594        } else {
1595                /* BPF_PROG_TYPE_SOCKET_FILTER */
1596                if (bpf_prog_size(prog->len) > sysctl_optmem_max) {
1597                        err = -ENOMEM;
1598                        goto err_prog_put;
1599                }
1600        }
1601
1602        err = reuseport_attach_prog(sk, prog);
1603err_prog_put:
1604        if (err)
1605                bpf_prog_put(prog);
1606
1607        return err;
1608}
1609
1610void sk_reuseport_prog_free(struct bpf_prog *prog)
1611{
1612        if (!prog)
1613                return;
1614
1615        if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT)
1616                bpf_prog_put(prog);
1617        else
1618                bpf_prog_destroy(prog);
1619}
1620
1621struct bpf_scratchpad {
1622        union {
1623                __be32 diff[MAX_BPF_STACK / sizeof(__be32)];
1624                u8     buff[MAX_BPF_STACK];
1625        };
1626};
1627
1628static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp);
1629
1630static inline int __bpf_try_make_writable(struct sk_buff *skb,
1631                                          unsigned int write_len)
1632{
1633        return skb_ensure_writable(skb, write_len);
1634}
1635
1636static inline int bpf_try_make_writable(struct sk_buff *skb,
1637                                        unsigned int write_len)
1638{
1639        int err = __bpf_try_make_writable(skb, write_len);
1640
1641        bpf_compute_data_pointers(skb);
1642        return err;
1643}
1644
1645static int bpf_try_make_head_writable(struct sk_buff *skb)
1646{
1647        return bpf_try_make_writable(skb, skb_headlen(skb));
1648}
1649
1650static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
1651{
1652        if (skb_at_tc_ingress(skb))
1653                skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1654}
1655
1656static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
1657{
1658        if (skb_at_tc_ingress(skb))
1659                skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1660}
1661
1662BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
1663           const void *, from, u32, len, u64, flags)
1664{
1665        void *ptr;
1666
1667        if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1668                return -EINVAL;
1669        if (unlikely(offset > 0xffff))
1670                return -EFAULT;
1671        if (unlikely(bpf_try_make_writable(skb, offset + len)))
1672                return -EFAULT;
1673
1674        ptr = skb->data + offset;
1675        if (flags & BPF_F_RECOMPUTE_CSUM)
1676                __skb_postpull_rcsum(skb, ptr, len, offset);
1677
1678        memcpy(ptr, from, len);
1679
1680        if (flags & BPF_F_RECOMPUTE_CSUM)
1681                __skb_postpush_rcsum(skb, ptr, len, offset);
1682        if (flags & BPF_F_INVALIDATE_HASH)
1683                skb_clear_hash(skb);
1684
1685        return 0;
1686}
1687
1688static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1689        .func           = bpf_skb_store_bytes,
1690        .gpl_only       = false,
1691        .ret_type       = RET_INTEGER,
1692        .arg1_type      = ARG_PTR_TO_CTX,
1693        .arg2_type      = ARG_ANYTHING,
1694        .arg3_type      = ARG_PTR_TO_MEM,
1695        .arg4_type      = ARG_CONST_SIZE,
1696        .arg5_type      = ARG_ANYTHING,
1697};
1698
1699BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
1700           void *, to, u32, len)
1701{
1702        void *ptr;
1703
1704        if (unlikely(offset > 0xffff))
1705                goto err_clear;
1706
1707        ptr = skb_header_pointer(skb, offset, len, to);
1708        if (unlikely(!ptr))
1709                goto err_clear;
1710        if (ptr != to)
1711                memcpy(to, ptr, len);
1712
1713        return 0;
1714err_clear:
1715        memset(to, 0, len);
1716        return -EFAULT;
1717}
1718
1719static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1720        .func           = bpf_skb_load_bytes,
1721        .gpl_only       = false,
1722        .ret_type       = RET_INTEGER,
1723        .arg1_type      = ARG_PTR_TO_CTX,
1724        .arg2_type      = ARG_ANYTHING,
1725        .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1726        .arg4_type      = ARG_CONST_SIZE,
1727};
1728
1729BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb,
1730           u32, offset, void *, to, u32, len, u32, start_header)
1731{
1732        u8 *end = skb_tail_pointer(skb);
1733        u8 *net = skb_network_header(skb);
1734        u8 *mac = skb_mac_header(skb);
1735        u8 *ptr;
1736
1737        if (unlikely(offset > 0xffff || len > (end - mac)))
1738                goto err_clear;
1739
1740        switch (start_header) {
1741        case BPF_HDR_START_MAC:
1742                ptr = mac + offset;
1743                break;
1744        case BPF_HDR_START_NET:
1745                ptr = net + offset;
1746                break;
1747        default:
1748                goto err_clear;
1749        }
1750
1751        if (likely(ptr >= mac && ptr + len <= end)) {
1752                memcpy(to, ptr, len);
1753                return 0;
1754        }
1755
1756err_clear:
1757        memset(to, 0, len);
1758        return -EFAULT;
1759}
1760
1761static const struct bpf_func_proto bpf_skb_load_bytes_relative_proto = {
1762        .func           = bpf_skb_load_bytes_relative,
1763        .gpl_only       = false,
1764        .ret_type       = RET_INTEGER,
1765        .arg1_type      = ARG_PTR_TO_CTX,
1766        .arg2_type      = ARG_ANYTHING,
1767        .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1768        .arg4_type      = ARG_CONST_SIZE,
1769        .arg5_type      = ARG_ANYTHING,
1770};
1771
1772BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
1773{
1774        /* Idea is the following: should the needed direct read/write
1775         * test fail during runtime, we can pull in more data and redo
1776         * again, since implicitly, we invalidate previous checks here.
1777         *
1778         * Or, since we know how much we need to make read/writeable,
1779         * this can be done once at the program beginning for direct
1780         * access case. By this we overcome limitations of only current
1781         * headroom being accessible.
1782         */
1783        return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
1784}
1785
1786static const struct bpf_func_proto bpf_skb_pull_data_proto = {
1787        .func           = bpf_skb_pull_data,
1788        .gpl_only       = false,
1789        .ret_type       = RET_INTEGER,
1790        .arg1_type      = ARG_PTR_TO_CTX,
1791        .arg2_type      = ARG_ANYTHING,
1792};
1793
1794static inline int sk_skb_try_make_writable(struct sk_buff *skb,
1795                                           unsigned int write_len)
1796{
1797        int err = __bpf_try_make_writable(skb, write_len);
1798
1799        bpf_compute_data_end_sk_skb(skb);
1800        return err;
1801}
1802
1803BPF_CALL_2(sk_skb_pull_data, struct sk_buff *, skb, u32, len)
1804{
1805        /* Idea is the following: should the needed direct read/write
1806         * test fail during runtime, we can pull in more data and redo
1807         * again, since implicitly, we invalidate previous checks here.
1808         *
1809         * Or, since we know how much we need to make read/writeable,
1810         * this can be done once at the program beginning for direct
1811         * access case. By this we overcome limitations of only current
1812         * headroom being accessible.
1813         */
1814        return sk_skb_try_make_writable(skb, len ? : skb_headlen(skb));
1815}
1816
1817static const struct bpf_func_proto sk_skb_pull_data_proto = {
1818        .func           = sk_skb_pull_data,
1819        .gpl_only       = false,
1820        .ret_type       = RET_INTEGER,
1821        .arg1_type      = ARG_PTR_TO_CTX,
1822        .arg2_type      = ARG_ANYTHING,
1823};
1824
1825BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
1826           u64, from, u64, to, u64, flags)
1827{
1828        __sum16 *ptr;
1829
1830        if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
1831                return -EINVAL;
1832        if (unlikely(offset > 0xffff || offset & 1))
1833                return -EFAULT;
1834        if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1835                return -EFAULT;
1836
1837        ptr = (__sum16 *)(skb->data + offset);
1838        switch (flags & BPF_F_HDR_FIELD_MASK) {
1839        case 0:
1840                if (unlikely(from != 0))
1841                        return -EINVAL;
1842
1843                csum_replace_by_diff(ptr, to);
1844                break;
1845        case 2:
1846                csum_replace2(ptr, from, to);
1847                break;
1848        case 4:
1849                csum_replace4(ptr, from, to);
1850                break;
1851        default:
1852                return -EINVAL;
1853        }
1854
1855        return 0;
1856}
1857
1858static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1859        .func           = bpf_l3_csum_replace,
1860        .gpl_only       = false,
1861        .ret_type       = RET_INTEGER,
1862        .arg1_type      = ARG_PTR_TO_CTX,
1863        .arg2_type      = ARG_ANYTHING,
1864        .arg3_type      = ARG_ANYTHING,
1865        .arg4_type      = ARG_ANYTHING,
1866        .arg5_type      = ARG_ANYTHING,
1867};
1868
1869BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
1870           u64, from, u64, to, u64, flags)
1871{
1872        bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1873        bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1874        bool do_mforce = flags & BPF_F_MARK_ENFORCE;
1875        __sum16 *ptr;
1876
1877        if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
1878                               BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK)))
1879                return -EINVAL;
1880        if (unlikely(offset > 0xffff || offset & 1))
1881                return -EFAULT;
1882        if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1883                return -EFAULT;
1884
1885        ptr = (__sum16 *)(skb->data + offset);
1886        if (is_mmzero && !do_mforce && !*ptr)
1887                return 0;
1888
1889        switch (flags & BPF_F_HDR_FIELD_MASK) {
1890        case 0:
1891                if (unlikely(from != 0))
1892                        return -EINVAL;
1893
1894                inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
1895                break;
1896        case 2:
1897                inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
1898                break;
1899        case 4:
1900                inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
1901                break;
1902        default:
1903                return -EINVAL;
1904        }
1905
1906        if (is_mmzero && !*ptr)
1907                *ptr = CSUM_MANGLED_0;
1908        return 0;
1909}
1910
1911static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1912        .func           = bpf_l4_csum_replace,
1913        .gpl_only       = false,
1914        .ret_type       = RET_INTEGER,
1915        .arg1_type      = ARG_PTR_TO_CTX,
1916        .arg2_type      = ARG_ANYTHING,
1917        .arg3_type      = ARG_ANYTHING,
1918        .arg4_type      = ARG_ANYTHING,
1919        .arg5_type      = ARG_ANYTHING,
1920};
1921
1922BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
1923           __be32 *, to, u32, to_size, __wsum, seed)
1924{
1925        struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1926        u32 diff_size = from_size + to_size;
1927        int i, j = 0;
1928
1929        /* This is quite flexible, some examples:
1930         *
1931         * from_size == 0, to_size > 0,  seed := csum --> pushing data
1932         * from_size > 0,  to_size == 0, seed := csum --> pulling data
1933         * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
1934         *
1935         * Even for diffing, from_size and to_size don't need to be equal.
1936         */
1937        if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) ||
1938                     diff_size > sizeof(sp->diff)))
1939                return -EINVAL;
1940
1941        for (i = 0; i < from_size / sizeof(__be32); i++, j++)
1942                sp->diff[j] = ~from[i];
1943        for (i = 0; i <   to_size / sizeof(__be32); i++, j++)
1944                sp->diff[j] = to[i];
1945
1946        return csum_partial(sp->diff, diff_size, seed);
1947}
1948
1949static const struct bpf_func_proto bpf_csum_diff_proto = {
1950        .func           = bpf_csum_diff,
1951        .gpl_only       = false,
1952        .pkt_access     = true,
1953        .ret_type       = RET_INTEGER,
1954        .arg1_type      = ARG_PTR_TO_MEM_OR_NULL,
1955        .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
1956        .arg3_type      = ARG_PTR_TO_MEM_OR_NULL,
1957        .arg4_type      = ARG_CONST_SIZE_OR_ZERO,
1958        .arg5_type      = ARG_ANYTHING,
1959};
1960
1961BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
1962{
1963        /* The interface is to be used in combination with bpf_csum_diff()
1964         * for direct packet writes. csum rotation for alignment as well
1965         * as emulating csum_sub() can be done from the eBPF program.
1966         */
1967        if (skb->ip_summed == CHECKSUM_COMPLETE)
1968                return (skb->csum = csum_add(skb->csum, csum));
1969
1970        return -ENOTSUPP;
1971}
1972
1973static const struct bpf_func_proto bpf_csum_update_proto = {
1974        .func           = bpf_csum_update,
1975        .gpl_only       = false,
1976        .ret_type       = RET_INTEGER,
1977        .arg1_type      = ARG_PTR_TO_CTX,
1978        .arg2_type      = ARG_ANYTHING,
1979};
1980
1981static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
1982{
1983        return dev_forward_skb(dev, skb);
1984}
1985
1986static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
1987                                      struct sk_buff *skb)
1988{
1989        int ret = ____dev_forward_skb(dev, skb);
1990
1991        if (likely(!ret)) {
1992                skb->dev = dev;
1993                ret = netif_rx(skb);
1994        }
1995
1996        return ret;
1997}
1998
1999static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
2000{
2001        int ret;
2002
2003        if (unlikely(__this_cpu_read(xmit_recursion) > XMIT_RECURSION_LIMIT)) {
2004                net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2005                kfree_skb(skb);
2006                return -ENETDOWN;
2007        }
2008
2009        skb->dev = dev;
2010
2011        __this_cpu_inc(xmit_recursion);
2012        ret = dev_queue_xmit(skb);
2013        __this_cpu_dec(xmit_recursion);
2014
2015        return ret;
2016}
2017
2018static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
2019                                 u32 flags)
2020{
2021        /* skb->mac_len is not set on normal egress */
2022        unsigned int mlen = skb->network_header - skb->mac_header;
2023
2024        __skb_pull(skb, mlen);
2025
2026        /* At ingress, the mac header has already been pulled once.
2027         * At egress, skb_pospull_rcsum has to be done in case that
2028         * the skb is originated from ingress (i.e. a forwarded skb)
2029         * to ensure that rcsum starts at net header.
2030         */
2031        if (!skb_at_tc_ingress(skb))
2032                skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
2033        skb_pop_mac_header(skb);
2034        skb_reset_mac_len(skb);
2035        return flags & BPF_F_INGRESS ?
2036               __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
2037}
2038
2039static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
2040                                 u32 flags)
2041{
2042        /* Verify that a link layer header is carried */
2043        if (unlikely(skb->mac_header >= skb->network_header)) {
2044                kfree_skb(skb);
2045                return -ERANGE;
2046        }
2047
2048        bpf_push_mac_rcsum(skb);
2049        return flags & BPF_F_INGRESS ?
2050               __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
2051}
2052
2053static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
2054                          u32 flags)
2055{
2056        if (dev_is_mac_header_xmit(dev))
2057                return __bpf_redirect_common(skb, dev, flags);
2058        else
2059                return __bpf_redirect_no_mac(skb, dev, flags);
2060}
2061
2062BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
2063{
2064        struct net_device *dev;
2065        struct sk_buff *clone;
2066        int ret;
2067
2068        if (unlikely(flags & ~(BPF_F_INGRESS)))
2069                return -EINVAL;
2070
2071        dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
2072        if (unlikely(!dev))
2073                return -EINVAL;
2074
2075        clone = skb_clone(skb, GFP_ATOMIC);
2076        if (unlikely(!clone))
2077                return -ENOMEM;
2078
2079        /* For direct write, we need to keep the invariant that the skbs
2080         * we're dealing with need to be uncloned. Should uncloning fail
2081         * here, we need to free the just generated clone to unclone once
2082         * again.
2083         */
2084        ret = bpf_try_make_head_writable(skb);
2085        if (unlikely(ret)) {
2086                kfree_skb(clone);
2087                return -ENOMEM;
2088        }
2089
2090        return __bpf_redirect(clone, dev, flags);
2091}
2092
2093static const struct bpf_func_proto bpf_clone_redirect_proto = {
2094        .func           = bpf_clone_redirect,
2095        .gpl_only       = false,
2096        .ret_type       = RET_INTEGER,
2097        .arg1_type      = ARG_PTR_TO_CTX,
2098        .arg2_type      = ARG_ANYTHING,
2099        .arg3_type      = ARG_ANYTHING,
2100};
2101
2102DEFINE_PER_CPU(struct bpf_redirect_info, bpf_redirect_info);
2103EXPORT_PER_CPU_SYMBOL_GPL(bpf_redirect_info);
2104
2105BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
2106{
2107        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2108
2109        if (unlikely(flags & ~(BPF_F_INGRESS)))
2110                return TC_ACT_SHOT;
2111
2112        ri->ifindex = ifindex;
2113        ri->flags = flags;
2114
2115        return TC_ACT_REDIRECT;
2116}
2117
2118int skb_do_redirect(struct sk_buff *skb)
2119{
2120        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2121        struct net_device *dev;
2122
2123        dev = dev_get_by_index_rcu(dev_net(skb->dev), ri->ifindex);
2124        ri->ifindex = 0;
2125        if (unlikely(!dev)) {
2126                kfree_skb(skb);
2127                return -EINVAL;
2128        }
2129
2130        return __bpf_redirect(skb, dev, ri->flags);
2131}
2132
2133static const struct bpf_func_proto bpf_redirect_proto = {
2134        .func           = bpf_redirect,
2135        .gpl_only       = false,
2136        .ret_type       = RET_INTEGER,
2137        .arg1_type      = ARG_ANYTHING,
2138        .arg2_type      = ARG_ANYTHING,
2139};
2140
2141BPF_CALL_4(bpf_sk_redirect_hash, struct sk_buff *, skb,
2142           struct bpf_map *, map, void *, key, u64, flags)
2143{
2144        struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
2145
2146        /* If user passes invalid input drop the packet. */
2147        if (unlikely(flags & ~(BPF_F_INGRESS)))
2148                return SK_DROP;
2149
2150        tcb->bpf.flags = flags;
2151        tcb->bpf.sk_redir = __sock_hash_lookup_elem(map, key);
2152        if (!tcb->bpf.sk_redir)
2153                return SK_DROP;
2154
2155        return SK_PASS;
2156}
2157
2158static const struct bpf_func_proto bpf_sk_redirect_hash_proto = {
2159        .func           = bpf_sk_redirect_hash,
2160        .gpl_only       = false,
2161        .ret_type       = RET_INTEGER,
2162        .arg1_type      = ARG_PTR_TO_CTX,
2163        .arg2_type      = ARG_CONST_MAP_PTR,
2164        .arg3_type      = ARG_PTR_TO_MAP_KEY,
2165        .arg4_type      = ARG_ANYTHING,
2166};
2167
2168BPF_CALL_4(bpf_sk_redirect_map, struct sk_buff *, skb,
2169           struct bpf_map *, map, u32, key, u64, flags)
2170{
2171        struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
2172
2173        /* If user passes invalid input drop the packet. */
2174        if (unlikely(flags & ~(BPF_F_INGRESS)))
2175                return SK_DROP;
2176
2177        tcb->bpf.flags = flags;
2178        tcb->bpf.sk_redir = __sock_map_lookup_elem(map, key);
2179        if (!tcb->bpf.sk_redir)
2180                return SK_DROP;
2181
2182        return SK_PASS;
2183}
2184
2185struct sock *do_sk_redirect_map(struct sk_buff *skb)
2186{
2187        struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
2188
2189        return tcb->bpf.sk_redir;
2190}
2191
2192static const struct bpf_func_proto bpf_sk_redirect_map_proto = {
2193        .func           = bpf_sk_redirect_map,
2194        .gpl_only       = false,
2195        .ret_type       = RET_INTEGER,
2196        .arg1_type      = ARG_PTR_TO_CTX,
2197        .arg2_type      = ARG_CONST_MAP_PTR,
2198        .arg3_type      = ARG_ANYTHING,
2199        .arg4_type      = ARG_ANYTHING,
2200};
2201
2202BPF_CALL_4(bpf_msg_redirect_hash, struct sk_msg_buff *, msg,
2203           struct bpf_map *, map, void *, key, u64, flags)
2204{
2205        /* If user passes invalid input drop the packet. */
2206        if (unlikely(flags & ~(BPF_F_INGRESS)))
2207                return SK_DROP;
2208
2209        msg->flags = flags;
2210        msg->sk_redir = __sock_hash_lookup_elem(map, key);
2211        if (!msg->sk_redir)
2212                return SK_DROP;
2213
2214        return SK_PASS;
2215}
2216
2217static const struct bpf_func_proto bpf_msg_redirect_hash_proto = {
2218        .func           = bpf_msg_redirect_hash,
2219        .gpl_only       = false,
2220        .ret_type       = RET_INTEGER,
2221        .arg1_type      = ARG_PTR_TO_CTX,
2222        .arg2_type      = ARG_CONST_MAP_PTR,
2223        .arg3_type      = ARG_PTR_TO_MAP_KEY,
2224        .arg4_type      = ARG_ANYTHING,
2225};
2226
2227BPF_CALL_4(bpf_msg_redirect_map, struct sk_msg_buff *, msg,
2228           struct bpf_map *, map, u32, key, u64, flags)
2229{
2230        /* If user passes invalid input drop the packet. */
2231        if (unlikely(flags & ~(BPF_F_INGRESS)))
2232                return SK_DROP;
2233
2234        msg->flags = flags;
2235        msg->sk_redir = __sock_map_lookup_elem(map, key);
2236        if (!msg->sk_redir)
2237                return SK_DROP;
2238
2239        return SK_PASS;
2240}
2241
2242struct sock *do_msg_redirect_map(struct sk_msg_buff *msg)
2243{
2244        return msg->sk_redir;
2245}
2246
2247static const struct bpf_func_proto bpf_msg_redirect_map_proto = {
2248        .func           = bpf_msg_redirect_map,
2249        .gpl_only       = false,
2250        .ret_type       = RET_INTEGER,
2251        .arg1_type      = ARG_PTR_TO_CTX,
2252        .arg2_type      = ARG_CONST_MAP_PTR,
2253        .arg3_type      = ARG_ANYTHING,
2254        .arg4_type      = ARG_ANYTHING,
2255};
2256
2257BPF_CALL_2(bpf_msg_apply_bytes, struct sk_msg_buff *, msg, u32, bytes)
2258{
2259        msg->apply_bytes = bytes;
2260        return 0;
2261}
2262
2263static const struct bpf_func_proto bpf_msg_apply_bytes_proto = {
2264        .func           = bpf_msg_apply_bytes,
2265        .gpl_only       = false,
2266        .ret_type       = RET_INTEGER,
2267        .arg1_type      = ARG_PTR_TO_CTX,
2268        .arg2_type      = ARG_ANYTHING,
2269};
2270
2271BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg_buff *, msg, u32, bytes)
2272{
2273        msg->cork_bytes = bytes;
2274        return 0;
2275}
2276
2277static const struct bpf_func_proto bpf_msg_cork_bytes_proto = {
2278        .func           = bpf_msg_cork_bytes,
2279        .gpl_only       = false,
2280        .ret_type       = RET_INTEGER,
2281        .arg1_type      = ARG_PTR_TO_CTX,
2282        .arg2_type      = ARG_ANYTHING,
2283};
2284
2285#define sk_msg_iter_var(var)                    \
2286        do {                                    \
2287                var++;                          \
2288                if (var == MAX_SKB_FRAGS)       \
2289                        var = 0;                \
2290        } while (0)
2291
2292BPF_CALL_4(bpf_msg_pull_data,
2293           struct sk_msg_buff *, msg, u32, start, u32, end, u64, flags)
2294{
2295        unsigned int len = 0, offset = 0, copy = 0, poffset = 0;
2296        int bytes = end - start, bytes_sg_total;
2297        struct scatterlist *sg = msg->sg_data;
2298        int first_sg, last_sg, i, shift;
2299        unsigned char *p, *to, *from;
2300        struct page *page;
2301
2302        if (unlikely(flags || end <= start))
2303                return -EINVAL;
2304
2305        /* First find the starting scatterlist element */
2306        i = msg->sg_start;
2307        do {
2308                len = sg[i].length;
2309                if (start < offset + len)
2310                        break;
2311                offset += len;
2312                sk_msg_iter_var(i);
2313        } while (i != msg->sg_end);
2314
2315        if (unlikely(start >= offset + len))
2316                return -EINVAL;
2317
2318        first_sg = i;
2319        /* The start may point into the sg element so we need to also
2320         * account for the headroom.
2321         */
2322        bytes_sg_total = start - offset + bytes;
2323        if (!msg->sg_copy[i] && bytes_sg_total <= len)
2324                goto out;
2325
2326        /* At this point we need to linearize multiple scatterlist
2327         * elements or a single shared page. Either way we need to
2328         * copy into a linear buffer exclusively owned by BPF. Then
2329         * place the buffer in the scatterlist and fixup the original
2330         * entries by removing the entries now in the linear buffer
2331         * and shifting the remaining entries. For now we do not try
2332         * to copy partial entries to avoid complexity of running out
2333         * of sg_entry slots. The downside is reading a single byte
2334         * will copy the entire sg entry.
2335         */
2336        do {
2337                copy += sg[i].length;
2338                sk_msg_iter_var(i);
2339                if (bytes_sg_total <= copy)
2340                        break;
2341        } while (i != msg->sg_end);
2342        last_sg = i;
2343
2344        if (unlikely(bytes_sg_total > copy))
2345                return -EINVAL;
2346
2347        page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2348                           get_order(copy));
2349        if (unlikely(!page))
2350                return -ENOMEM;
2351        p = page_address(page);
2352
2353        i = first_sg;
2354        do {
2355                from = sg_virt(&sg[i]);
2356                len = sg[i].length;
2357                to = p + poffset;
2358
2359                memcpy(to, from, len);
2360                poffset += len;
2361                sg[i].length = 0;
2362                put_page(sg_page(&sg[i]));
2363
2364                sk_msg_iter_var(i);
2365        } while (i != last_sg);
2366
2367        sg[first_sg].length = copy;
2368        sg_set_page(&sg[first_sg], page, copy, 0);
2369
2370        /* To repair sg ring we need to shift entries. If we only
2371         * had a single entry though we can just replace it and
2372         * be done. Otherwise walk the ring and shift the entries.
2373         */
2374        WARN_ON_ONCE(last_sg == first_sg);
2375        shift = last_sg > first_sg ?
2376                last_sg - first_sg - 1 :
2377                MAX_SKB_FRAGS - first_sg + last_sg - 1;
2378        if (!shift)
2379                goto out;
2380
2381        i = first_sg;
2382        sk_msg_iter_var(i);
2383        do {
2384                int move_from;
2385
2386                if (i + shift >= MAX_SKB_FRAGS)
2387                        move_from = i + shift - MAX_SKB_FRAGS;
2388                else
2389                        move_from = i + shift;
2390
2391                if (move_from == msg->sg_end)
2392                        break;
2393
2394                sg[i] = sg[move_from];
2395                sg[move_from].length = 0;
2396                sg[move_from].page_link = 0;
2397                sg[move_from].offset = 0;
2398
2399                sk_msg_iter_var(i);
2400        } while (1);
2401        msg->sg_end -= shift;
2402        if (msg->sg_end < 0)
2403                msg->sg_end += MAX_SKB_FRAGS;
2404out:
2405        msg->data = sg_virt(&sg[first_sg]) + start - offset;
2406        msg->data_end = msg->data + bytes;
2407
2408        return 0;
2409}
2410
2411static const struct bpf_func_proto bpf_msg_pull_data_proto = {
2412        .func           = bpf_msg_pull_data,
2413        .gpl_only       = false,
2414        .ret_type       = RET_INTEGER,
2415        .arg1_type      = ARG_PTR_TO_CTX,
2416        .arg2_type      = ARG_ANYTHING,
2417        .arg3_type      = ARG_ANYTHING,
2418        .arg4_type      = ARG_ANYTHING,
2419};
2420
2421BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
2422{
2423        return task_get_classid(skb);
2424}
2425
2426static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
2427        .func           = bpf_get_cgroup_classid,
2428        .gpl_only       = false,
2429        .ret_type       = RET_INTEGER,
2430        .arg1_type      = ARG_PTR_TO_CTX,
2431};
2432
2433BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
2434{
2435        return dst_tclassid(skb);
2436}
2437
2438static const struct bpf_func_proto bpf_get_route_realm_proto = {
2439        .func           = bpf_get_route_realm,
2440        .gpl_only       = false,
2441        .ret_type       = RET_INTEGER,
2442        .arg1_type      = ARG_PTR_TO_CTX,
2443};
2444
2445BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
2446{
2447        /* If skb_clear_hash() was called due to mangling, we can
2448         * trigger SW recalculation here. Later access to hash
2449         * can then use the inline skb->hash via context directly
2450         * instead of calling this helper again.
2451         */
2452        return skb_get_hash(skb);
2453}
2454
2455static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
2456        .func           = bpf_get_hash_recalc,
2457        .gpl_only       = false,
2458        .ret_type       = RET_INTEGER,
2459        .arg1_type      = ARG_PTR_TO_CTX,
2460};
2461
2462BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
2463{
2464        /* After all direct packet write, this can be used once for
2465         * triggering a lazy recalc on next skb_get_hash() invocation.
2466         */
2467        skb_clear_hash(skb);
2468        return 0;
2469}
2470
2471static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
2472        .func           = bpf_set_hash_invalid,
2473        .gpl_only       = false,
2474        .ret_type       = RET_INTEGER,
2475        .arg1_type      = ARG_PTR_TO_CTX,
2476};
2477
2478BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
2479{
2480        /* Set user specified hash as L4(+), so that it gets returned
2481         * on skb_get_hash() call unless BPF prog later on triggers a
2482         * skb_clear_hash().
2483         */
2484        __skb_set_sw_hash(skb, hash, true);
2485        return 0;
2486}
2487
2488static const struct bpf_func_proto bpf_set_hash_proto = {
2489        .func           = bpf_set_hash,
2490        .gpl_only       = false,
2491        .ret_type       = RET_INTEGER,
2492        .arg1_type      = ARG_PTR_TO_CTX,
2493        .arg2_type      = ARG_ANYTHING,
2494};
2495
2496BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
2497           u16, vlan_tci)
2498{
2499        int ret;
2500
2501        if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
2502                     vlan_proto != htons(ETH_P_8021AD)))
2503                vlan_proto = htons(ETH_P_8021Q);
2504
2505        bpf_push_mac_rcsum(skb);
2506        ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
2507        bpf_pull_mac_rcsum(skb);
2508
2509        bpf_compute_data_pointers(skb);
2510        return ret;
2511}
2512
2513static const struct bpf_func_proto bpf_skb_vlan_push_proto = {
2514        .func           = bpf_skb_vlan_push,
2515        .gpl_only       = false,
2516        .ret_type       = RET_INTEGER,
2517        .arg1_type      = ARG_PTR_TO_CTX,
2518        .arg2_type      = ARG_ANYTHING,
2519        .arg3_type      = ARG_ANYTHING,
2520};
2521
2522BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
2523{
2524        int ret;
2525
2526        bpf_push_mac_rcsum(skb);
2527        ret = skb_vlan_pop(skb);
2528        bpf_pull_mac_rcsum(skb);
2529
2530        bpf_compute_data_pointers(skb);
2531        return ret;
2532}
2533
2534static const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
2535        .func           = bpf_skb_vlan_pop,
2536        .gpl_only       = false,
2537        .ret_type       = RET_INTEGER,
2538        .arg1_type      = ARG_PTR_TO_CTX,
2539};
2540
2541static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
2542{
2543        /* Caller already did skb_cow() with len as headroom,
2544         * so no need to do it here.
2545         */
2546        skb_push(skb, len);
2547        memmove(skb->data, skb->data + len, off);
2548        memset(skb->data + off, 0, len);
2549
2550        /* No skb_postpush_rcsum(skb, skb->data + off, len)
2551         * needed here as it does not change the skb->csum
2552         * result for checksum complete when summing over
2553         * zeroed blocks.
2554         */
2555        return 0;
2556}
2557
2558static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
2559{
2560        /* skb_ensure_writable() is not needed here, as we're
2561         * already working on an uncloned skb.
2562         */
2563        if (unlikely(!pskb_may_pull(skb, off + len)))
2564                return -ENOMEM;
2565
2566        skb_postpull_rcsum(skb, skb->data + off, len);
2567        memmove(skb->data + len, skb->data, off);
2568        __skb_pull(skb, len);
2569
2570        return 0;
2571}
2572
2573static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
2574{
2575        bool trans_same = skb->transport_header == skb->network_header;
2576        int ret;
2577
2578        /* There's no need for __skb_push()/__skb_pull() pair to
2579         * get to the start of the mac header as we're guaranteed
2580         * to always start from here under eBPF.
2581         */
2582        ret = bpf_skb_generic_push(skb, off, len);
2583        if (likely(!ret)) {
2584                skb->mac_header -= len;
2585                skb->network_header -= len;
2586                if (trans_same)
2587                        skb->transport_header = skb->network_header;
2588        }
2589
2590        return ret;
2591}
2592
2593static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
2594{
2595        bool trans_same = skb->transport_header == skb->network_header;
2596        int ret;
2597
2598        /* Same here, __skb_push()/__skb_pull() pair not needed. */
2599        ret = bpf_skb_generic_pop(skb, off, len);
2600        if (likely(!ret)) {
2601                skb->mac_header += len;
2602                skb->network_header += len;
2603                if (trans_same)
2604                        skb->transport_header = skb->network_header;
2605        }
2606
2607        return ret;
2608}
2609
2610static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
2611{
2612        const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2613        u32 off = skb_mac_header_len(skb);
2614        int ret;
2615
2616        /* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
2617        if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
2618                return -ENOTSUPP;
2619
2620        ret = skb_cow(skb, len_diff);
2621        if (unlikely(ret < 0))
2622                return ret;
2623
2624        ret = bpf_skb_net_hdr_push(skb, off, len_diff);
2625        if (unlikely(ret < 0))
2626                return ret;
2627
2628        if (skb_is_gso(skb)) {
2629                struct skb_shared_info *shinfo = skb_shinfo(skb);
2630
2631                /* SKB_GSO_TCPV4 needs to be changed into
2632                 * SKB_GSO_TCPV6.
2633                 */
2634                if (shinfo->gso_type & SKB_GSO_TCPV4) {
2635                        shinfo->gso_type &= ~SKB_GSO_TCPV4;
2636                        shinfo->gso_type |=  SKB_GSO_TCPV6;
2637                }
2638
2639                /* Due to IPv6 header, MSS needs to be downgraded. */
2640                skb_decrease_gso_size(shinfo, len_diff);
2641                /* Header must be checked, and gso_segs recomputed. */
2642                shinfo->gso_type |= SKB_GSO_DODGY;
2643                shinfo->gso_segs = 0;
2644        }
2645
2646        skb->protocol = htons(ETH_P_IPV6);
2647        skb_clear_hash(skb);
2648
2649        return 0;
2650}
2651
2652static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
2653{
2654        const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2655        u32 off = skb_mac_header_len(skb);
2656        int ret;
2657
2658        /* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
2659        if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
2660                return -ENOTSUPP;
2661
2662        ret = skb_unclone(skb, GFP_ATOMIC);
2663        if (unlikely(ret < 0))
2664                return ret;
2665
2666        ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
2667        if (unlikely(ret < 0))
2668                return ret;
2669
2670        if (skb_is_gso(skb)) {
2671                struct skb_shared_info *shinfo = skb_shinfo(skb);
2672
2673                /* SKB_GSO_TCPV6 needs to be changed into
2674                 * SKB_GSO_TCPV4.
2675                 */
2676                if (shinfo->gso_type & SKB_GSO_TCPV6) {
2677                        shinfo->gso_type &= ~SKB_GSO_TCPV6;
2678                        shinfo->gso_type |=  SKB_GSO_TCPV4;
2679                }
2680
2681                /* Due to IPv4 header, MSS can be upgraded. */
2682                skb_increase_gso_size(shinfo, len_diff);
2683                /* Header must be checked, and gso_segs recomputed. */
2684                shinfo->gso_type |= SKB_GSO_DODGY;
2685                shinfo->gso_segs = 0;
2686        }
2687
2688        skb->protocol = htons(ETH_P_IP);
2689        skb_clear_hash(skb);
2690
2691        return 0;
2692}
2693
2694static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
2695{
2696        __be16 from_proto = skb->protocol;
2697
2698        if (from_proto == htons(ETH_P_IP) &&
2699              to_proto == htons(ETH_P_IPV6))
2700                return bpf_skb_proto_4_to_6(skb);
2701
2702        if (from_proto == htons(ETH_P_IPV6) &&
2703              to_proto == htons(ETH_P_IP))
2704                return bpf_skb_proto_6_to_4(skb);
2705
2706        return -ENOTSUPP;
2707}
2708
2709BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
2710           u64, flags)
2711{
2712        int ret;
2713
2714        if (unlikely(flags))
2715                return -EINVAL;
2716
2717        /* General idea is that this helper does the basic groundwork
2718         * needed for changing the protocol, and eBPF program fills the
2719         * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
2720         * and other helpers, rather than passing a raw buffer here.
2721         *
2722         * The rationale is to keep this minimal and without a need to
2723         * deal with raw packet data. F.e. even if we would pass buffers
2724         * here, the program still needs to call the bpf_lX_csum_replace()
2725         * helpers anyway. Plus, this way we keep also separation of
2726         * concerns, since f.e. bpf_skb_store_bytes() should only take
2727         * care of stores.
2728         *
2729         * Currently, additional options and extension header space are
2730         * not supported, but flags register is reserved so we can adapt
2731         * that. For offloads, we mark packet as dodgy, so that headers
2732         * need to be verified first.
2733         */
2734        ret = bpf_skb_proto_xlat(skb, proto);
2735        bpf_compute_data_pointers(skb);
2736        return ret;
2737}
2738
2739static const struct bpf_func_proto bpf_skb_change_proto_proto = {
2740        .func           = bpf_skb_change_proto,
2741        .gpl_only       = false,
2742        .ret_type       = RET_INTEGER,
2743        .arg1_type      = ARG_PTR_TO_CTX,
2744        .arg2_type      = ARG_ANYTHING,
2745        .arg3_type      = ARG_ANYTHING,
2746};
2747
2748BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
2749{
2750        /* We only allow a restricted subset to be changed for now. */
2751        if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
2752                     !skb_pkt_type_ok(pkt_type)))
2753                return -EINVAL;
2754
2755        skb->pkt_type = pkt_type;
2756        return 0;
2757}
2758
2759static const struct bpf_func_proto bpf_skb_change_type_proto = {
2760        .func           = bpf_skb_change_type,
2761        .gpl_only       = false,
2762        .ret_type       = RET_INTEGER,
2763        .arg1_type      = ARG_PTR_TO_CTX,
2764        .arg2_type      = ARG_ANYTHING,
2765};
2766
2767static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
2768{
2769        switch (skb->protocol) {
2770        case htons(ETH_P_IP):
2771                return sizeof(struct iphdr);
2772        case htons(ETH_P_IPV6):
2773                return sizeof(struct ipv6hdr);
2774        default:
2775                return ~0U;
2776        }
2777}
2778
2779static int bpf_skb_net_grow(struct sk_buff *skb, u32 len_diff)
2780{
2781        u32 off = skb_mac_header_len(skb) + bpf_skb_net_base_len(skb);
2782        int ret;
2783
2784        /* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
2785        if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
2786                return -ENOTSUPP;
2787
2788        ret = skb_cow(skb, len_diff);
2789        if (unlikely(ret < 0))
2790                return ret;
2791
2792        ret = bpf_skb_net_hdr_push(skb, off, len_diff);
2793        if (unlikely(ret < 0))
2794                return ret;
2795
2796        if (skb_is_gso(skb)) {
2797                struct skb_shared_info *shinfo = skb_shinfo(skb);
2798
2799                /* Due to header grow, MSS needs to be downgraded. */
2800                skb_decrease_gso_size(shinfo, len_diff);
2801                /* Header must be checked, and gso_segs recomputed. */
2802                shinfo->gso_type |= SKB_GSO_DODGY;
2803                shinfo->gso_segs = 0;
2804        }
2805
2806        return 0;
2807}
2808
2809static int bpf_skb_net_shrink(struct sk_buff *skb, u32 len_diff)
2810{
2811        u32 off = skb_mac_header_len(skb) + bpf_skb_net_base_len(skb);
2812        int ret;
2813
2814        /* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
2815        if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
2816                return -ENOTSUPP;
2817
2818        ret = skb_unclone(skb, GFP_ATOMIC);
2819        if (unlikely(ret < 0))
2820                return ret;
2821
2822        ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
2823        if (unlikely(ret < 0))
2824                return ret;
2825
2826        if (skb_is_gso(skb)) {
2827                struct skb_shared_info *shinfo = skb_shinfo(skb);
2828
2829                /* Due to header shrink, MSS can be upgraded. */
2830                skb_increase_gso_size(shinfo, len_diff);
2831                /* Header must be checked, and gso_segs recomputed. */
2832                shinfo->gso_type |= SKB_GSO_DODGY;
2833                shinfo->gso_segs = 0;
2834        }
2835
2836        return 0;
2837}
2838
2839static u32 __bpf_skb_max_len(const struct sk_buff *skb)
2840{
2841        return skb->dev ? skb->dev->mtu + skb->dev->hard_header_len :
2842                          SKB_MAX_ALLOC;
2843}
2844
2845static int bpf_skb_adjust_net(struct sk_buff *skb, s32 len_diff)
2846{
2847        bool trans_same = skb->transport_header == skb->network_header;
2848        u32 len_cur, len_diff_abs = abs(len_diff);
2849        u32 len_min = bpf_skb_net_base_len(skb);
2850        u32 len_max = __bpf_skb_max_len(skb);
2851        __be16 proto = skb->protocol;
2852        bool shrink = len_diff < 0;
2853        int ret;
2854
2855        if (unlikely(len_diff_abs > 0xfffU))
2856                return -EFAULT;
2857        if (unlikely(proto != htons(ETH_P_IP) &&
2858                     proto != htons(ETH_P_IPV6)))
2859                return -ENOTSUPP;
2860
2861        len_cur = skb->len - skb_network_offset(skb);
2862        if (skb_transport_header_was_set(skb) && !trans_same)
2863                len_cur = skb_network_header_len(skb);
2864        if ((shrink && (len_diff_abs >= len_cur ||
2865                        len_cur - len_diff_abs < len_min)) ||
2866            (!shrink && (skb->len + len_diff_abs > len_max &&
2867                         !skb_is_gso(skb))))
2868                return -ENOTSUPP;
2869
2870        ret = shrink ? bpf_skb_net_shrink(skb, len_diff_abs) :
2871                       bpf_skb_net_grow(skb, len_diff_abs);
2872
2873        bpf_compute_data_pointers(skb);
2874        return ret;
2875}
2876
2877BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
2878           u32, mode, u64, flags)
2879{
2880        if (unlikely(flags))
2881                return -EINVAL;
2882        if (likely(mode == BPF_ADJ_ROOM_NET))
2883                return bpf_skb_adjust_net(skb, len_diff);
2884
2885        return -ENOTSUPP;
2886}
2887
2888static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
2889        .func           = bpf_skb_adjust_room,
2890        .gpl_only       = false,
2891        .ret_type       = RET_INTEGER,
2892        .arg1_type      = ARG_PTR_TO_CTX,
2893        .arg2_type      = ARG_ANYTHING,
2894        .arg3_type      = ARG_ANYTHING,
2895        .arg4_type      = ARG_ANYTHING,
2896};
2897
2898static u32 __bpf_skb_min_len(const struct sk_buff *skb)
2899{
2900        u32 min_len = skb_network_offset(skb);
2901
2902        if (skb_transport_header_was_set(skb))
2903                min_len = skb_transport_offset(skb);
2904        if (skb->ip_summed == CHECKSUM_PARTIAL)
2905                min_len = skb_checksum_start_offset(skb) +
2906                          skb->csum_offset + sizeof(__sum16);
2907        return min_len;
2908}
2909
2910static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
2911{
2912        unsigned int old_len = skb->len;
2913        int ret;
2914
2915        ret = __skb_grow_rcsum(skb, new_len);
2916        if (!ret)
2917                memset(skb->data + old_len, 0, new_len - old_len);
2918        return ret;
2919}
2920
2921static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
2922{
2923        return __skb_trim_rcsum(skb, new_len);
2924}
2925
2926static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len,
2927                                        u64 flags)
2928{
2929        u32 max_len = __bpf_skb_max_len(skb);
2930        u32 min_len = __bpf_skb_min_len(skb);
2931        int ret;
2932
2933        if (unlikely(flags || new_len > max_len || new_len < min_len))
2934                return -EINVAL;
2935        if (skb->encapsulation)
2936                return -ENOTSUPP;
2937
2938        /* The basic idea of this helper is that it's performing the
2939         * needed work to either grow or trim an skb, and eBPF program
2940         * rewrites the rest via helpers like bpf_skb_store_bytes(),
2941         * bpf_lX_csum_replace() and others rather than passing a raw
2942         * buffer here. This one is a slow path helper and intended
2943         * for replies with control messages.
2944         *
2945         * Like in bpf_skb_change_proto(), we want to keep this rather
2946         * minimal and without protocol specifics so that we are able
2947         * to separate concerns as in bpf_skb_store_bytes() should only
2948         * be the one responsible for writing buffers.
2949         *
2950         * It's really expected to be a slow path operation here for
2951         * control message replies, so we're implicitly linearizing,
2952         * uncloning and drop offloads from the skb by this.
2953         */
2954        ret = __bpf_try_make_writable(skb, skb->len);
2955        if (!ret) {
2956                if (new_len > skb->len)
2957                        ret = bpf_skb_grow_rcsum(skb, new_len);
2958                else if (new_len < skb->len)
2959                        ret = bpf_skb_trim_rcsum(skb, new_len);
2960                if (!ret && skb_is_gso(skb))
2961                        skb_gso_reset(skb);
2962        }
2963        return ret;
2964}
2965
2966BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
2967           u64, flags)
2968{
2969        int ret = __bpf_skb_change_tail(skb, new_len, flags);
2970
2971        bpf_compute_data_pointers(skb);
2972        return ret;
2973}
2974
2975static const struct bpf_func_proto bpf_skb_change_tail_proto = {
2976        .func           = bpf_skb_change_tail,
2977        .gpl_only       = false,
2978        .ret_type       = RET_INTEGER,
2979        .arg1_type      = ARG_PTR_TO_CTX,
2980        .arg2_type      = ARG_ANYTHING,
2981        .arg3_type      = ARG_ANYTHING,
2982};
2983
2984BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len,
2985           u64, flags)
2986{
2987        int ret = __bpf_skb_change_tail(skb, new_len, flags);
2988
2989        bpf_compute_data_end_sk_skb(skb);
2990        return ret;
2991}
2992
2993static const struct bpf_func_proto sk_skb_change_tail_proto = {
2994        .func           = sk_skb_change_tail,
2995        .gpl_only       = false,
2996        .ret_type       = RET_INTEGER,
2997        .arg1_type      = ARG_PTR_TO_CTX,
2998        .arg2_type      = ARG_ANYTHING,
2999        .arg3_type      = ARG_ANYTHING,
3000};
3001
3002static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room,
3003                                        u64 flags)
3004{
3005        u32 max_len = __bpf_skb_max_len(skb);
3006        u32 new_len = skb->len + head_room;
3007        int ret;
3008
3009        if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
3010                     new_len < skb->len))
3011                return -EINVAL;
3012
3013        ret = skb_cow(skb, head_room);
3014        if (likely(!ret)) {
3015                /* Idea for this helper is that we currently only
3016                 * allow to expand on mac header. This means that
3017                 * skb->protocol network header, etc, stay as is.
3018                 * Compared to bpf_skb_change_tail(), we're more
3019                 * flexible due to not needing to linearize or
3020                 * reset GSO. Intention for this helper is to be
3021                 * used by an L3 skb that needs to push mac header
3022                 * for redirection into L2 device.
3023                 */
3024                __skb_push(skb, head_room);
3025                memset(skb->data, 0, head_room);
3026                skb_reset_mac_header(skb);
3027        }
3028
3029        return ret;
3030}
3031
3032BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
3033           u64, flags)
3034{
3035        int ret = __bpf_skb_change_head(skb, head_room, flags);
3036
3037        bpf_compute_data_pointers(skb);
3038        return ret;
3039}
3040
3041static const struct bpf_func_proto bpf_skb_change_head_proto = {
3042        .func           = bpf_skb_change_head,
3043        .gpl_only       = false,
3044        .ret_type       = RET_INTEGER,
3045        .arg1_type      = ARG_PTR_TO_CTX,
3046        .arg2_type      = ARG_ANYTHING,
3047        .arg3_type      = ARG_ANYTHING,
3048};
3049
3050BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room,
3051           u64, flags)
3052{
3053        int ret = __bpf_skb_change_head(skb, head_room, flags);
3054
3055        bpf_compute_data_end_sk_skb(skb);
3056        return ret;
3057}
3058
3059static const struct bpf_func_proto sk_skb_change_head_proto = {
3060        .func           = sk_skb_change_head,
3061        .gpl_only       = false,
3062        .ret_type       = RET_INTEGER,
3063        .arg1_type      = ARG_PTR_TO_CTX,
3064        .arg2_type      = ARG_ANYTHING,
3065        .arg3_type      = ARG_ANYTHING,
3066};
3067static unsigned long xdp_get_metalen(const struct xdp_buff *xdp)
3068{
3069        return xdp_data_meta_unsupported(xdp) ? 0 :
3070               xdp->data - xdp->data_meta;
3071}
3072
3073BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
3074{
3075        void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3076        unsigned long metalen = xdp_get_metalen(xdp);
3077        void *data_start = xdp_frame_end + metalen;
3078        void *data = xdp->data + offset;
3079
3080        if (unlikely(data < data_start ||
3081                     data > xdp->data_end - ETH_HLEN))
3082                return -EINVAL;
3083
3084        if (metalen)
3085                memmove(xdp->data_meta + offset,
3086                        xdp->data_meta, metalen);
3087        xdp->data_meta += offset;
3088        xdp->data = data;
3089
3090        return 0;
3091}
3092
3093static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
3094        .func           = bpf_xdp_adjust_head,
3095        .gpl_only       = false,
3096        .ret_type       = RET_INTEGER,
3097        .arg1_type      = ARG_PTR_TO_CTX,
3098        .arg2_type      = ARG_ANYTHING,
3099};
3100
3101BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
3102{
3103        void *data_end = xdp->data_end + offset;
3104
3105        /* only shrinking is allowed for now. */
3106        if (unlikely(offset >= 0))
3107                return -EINVAL;
3108
3109        if (unlikely(data_end < xdp->data + ETH_HLEN))
3110                return -EINVAL;
3111
3112        xdp->data_end = data_end;
3113
3114        return 0;
3115}
3116
3117static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
3118        .func           = bpf_xdp_adjust_tail,
3119        .gpl_only       = false,
3120        .ret_type       = RET_INTEGER,
3121        .arg1_type      = ARG_PTR_TO_CTX,
3122        .arg2_type      = ARG_ANYTHING,
3123};
3124
3125BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
3126{
3127        void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3128        void *meta = xdp->data_meta + offset;
3129        unsigned long metalen = xdp->data - meta;
3130
3131        if (xdp_data_meta_unsupported(xdp))
3132                return -ENOTSUPP;
3133        if (unlikely(meta < xdp_frame_end ||
3134                     meta > xdp->data))
3135                return -EINVAL;
3136        if (unlikely((metalen & (sizeof(__u32) - 1)) ||
3137                     (metalen > 32)))
3138                return -EACCES;
3139
3140        xdp->data_meta = meta;
3141
3142        return 0;
3143}
3144
3145static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
3146        .func           = bpf_xdp_adjust_meta,
3147        .gpl_only       = false,
3148        .ret_type       = RET_INTEGER,
3149        .arg1_type      = ARG_PTR_TO_CTX,
3150        .arg2_type      = ARG_ANYTHING,
3151};
3152
3153static int __bpf_tx_xdp(struct net_device *dev,
3154                        struct bpf_map *map,
3155                        struct xdp_buff *xdp,
3156                        u32 index)
3157{
3158        struct xdp_frame *xdpf;
3159        int err, sent;
3160
3161        if (!dev->netdev_ops->ndo_xdp_xmit) {
3162                return -EOPNOTSUPP;
3163        }
3164
3165        err = xdp_ok_fwd_dev(dev, xdp->data_end - xdp->data);
3166        if (unlikely(err))
3167                return err;
3168
3169        xdpf = convert_to_xdp_frame(xdp);
3170        if (unlikely(!xdpf))
3171                return -EOVERFLOW;
3172
3173        sent = dev->netdev_ops->ndo_xdp_xmit(dev, 1, &xdpf, XDP_XMIT_FLUSH);
3174        if (sent <= 0)
3175                return sent;
3176        return 0;
3177}
3178
3179static int __bpf_tx_xdp_map(struct net_device *dev_rx, void *fwd,
3180                            struct bpf_map *map,
3181                            struct xdp_buff *xdp,
3182                            u32 index)
3183{
3184        int err;
3185
3186        switch (map->map_type) {
3187        case BPF_MAP_TYPE_DEVMAP: {
3188                struct bpf_dtab_netdev *dst = fwd;
3189
3190                err = dev_map_enqueue(dst, xdp, dev_rx);
3191                if (err)
3192                        return err;
3193                __dev_map_insert_ctx(map, index);
3194                break;
3195        }
3196        case BPF_MAP_TYPE_CPUMAP: {
3197                struct bpf_cpu_map_entry *rcpu = fwd;
3198
3199                err = cpu_map_enqueue(rcpu, xdp, dev_rx);
3200                if (err)
3201                        return err;
3202                __cpu_map_insert_ctx(map, index);
3203                break;
3204        }
3205        case BPF_MAP_TYPE_XSKMAP: {
3206                struct xdp_sock *xs = fwd;
3207
3208                err = __xsk_map_redirect(map, xdp, xs);
3209                return err;
3210        }
3211        default:
3212                break;
3213        }
3214        return 0;
3215}
3216
3217void xdp_do_flush_map(void)
3218{
3219        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3220        struct bpf_map *map = ri->map_to_flush;
3221
3222        ri->map_to_flush = NULL;
3223        if (map) {
3224                switch (map->map_type) {
3225                case BPF_MAP_TYPE_DEVMAP:
3226                        __dev_map_flush(map);
3227                        break;
3228                case BPF_MAP_TYPE_CPUMAP:
3229                        __cpu_map_flush(map);
3230                        break;
3231                case BPF_MAP_TYPE_XSKMAP:
3232                        __xsk_map_flush(map);
3233                        break;
3234                default:
3235                        break;
3236                }
3237        }
3238}
3239EXPORT_SYMBOL_GPL(xdp_do_flush_map);
3240
3241static void *__xdp_map_lookup_elem(struct bpf_map *map, u32 index)
3242{
3243        switch (map->map_type) {
3244        case BPF_MAP_TYPE_DEVMAP:
3245                return __dev_map_lookup_elem(map, index);
3246        case BPF_MAP_TYPE_CPUMAP:
3247                return __cpu_map_lookup_elem(map, index);
3248        case BPF_MAP_TYPE_XSKMAP:
3249                return __xsk_map_lookup_elem(map, index);
3250        default:
3251                return NULL;
3252        }
3253}
3254
3255void bpf_clear_redirect_map(struct bpf_map *map)
3256{
3257        struct bpf_redirect_info *ri;
3258        int cpu;
3259
3260        for_each_possible_cpu(cpu) {
3261                ri = per_cpu_ptr(&bpf_redirect_info, cpu);
3262                /* Avoid polluting remote cacheline due to writes if
3263                 * not needed. Once we pass this test, we need the
3264                 * cmpxchg() to make sure it hasn't been changed in
3265                 * the meantime by remote CPU.
3266                 */
3267                if (unlikely(READ_ONCE(ri->map) == map))
3268                        cmpxchg(&ri->map, map, NULL);
3269        }
3270}
3271
3272static int xdp_do_redirect_map(struct net_device *dev, struct xdp_buff *xdp,
3273                               struct bpf_prog *xdp_prog, struct bpf_map *map)
3274{
3275        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3276        u32 index = ri->ifindex;
3277        void *fwd = NULL;
3278        int err;
3279
3280        ri->ifindex = 0;
3281        WRITE_ONCE(ri->map, NULL);
3282
3283        fwd = __xdp_map_lookup_elem(map, index);
3284        if (!fwd) {
3285                err = -EINVAL;
3286                goto err;
3287        }
3288        if (ri->map_to_flush && ri->map_to_flush != map)
3289                xdp_do_flush_map();
3290
3291        err = __bpf_tx_xdp_map(dev, fwd, map, xdp, index);
3292        if (unlikely(err))
3293                goto err;
3294
3295        ri->map_to_flush = map;
3296        _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3297        return 0;
3298err:
3299        _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3300        return err;
3301}
3302
3303int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
3304                    struct bpf_prog *xdp_prog)
3305{
3306        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3307        struct bpf_map *map = READ_ONCE(ri->map);
3308        struct net_device *fwd;
3309        u32 index = ri->ifindex;
3310        int err;
3311
3312        if (map)
3313                return xdp_do_redirect_map(dev, xdp, xdp_prog, map);
3314
3315        fwd = dev_get_by_index_rcu(dev_net(dev), index);
3316        ri->ifindex = 0;
3317        if (unlikely(!fwd)) {
3318                err = -EINVAL;
3319                goto err;
3320        }
3321
3322        err = __bpf_tx_xdp(fwd, NULL, xdp, 0);
3323        if (unlikely(err))
3324                goto err;
3325
3326        _trace_xdp_redirect(dev, xdp_prog, index);
3327        return 0;
3328err:
3329        _trace_xdp_redirect_err(dev, xdp_prog, index, err);
3330        return err;
3331}
3332EXPORT_SYMBOL_GPL(xdp_do_redirect);
3333
3334static int xdp_do_generic_redirect_map(struct net_device *dev,
3335                                       struct sk_buff *skb,
3336                                       struct xdp_buff *xdp,
3337                                       struct bpf_prog *xdp_prog,
3338                                       struct bpf_map *map)
3339{
3340        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3341        u32 index = ri->ifindex;
3342        void *fwd = NULL;
3343        int err = 0;
3344
3345        ri->ifindex = 0;
3346        WRITE_ONCE(ri->map, NULL);
3347
3348        fwd = __xdp_map_lookup_elem(map, index);
3349        if (unlikely(!fwd)) {
3350                err = -EINVAL;
3351                goto err;
3352        }
3353
3354        if (map->map_type == BPF_MAP_TYPE_DEVMAP) {
3355                struct bpf_dtab_netdev *dst = fwd;
3356
3357                err = dev_map_generic_redirect(dst, skb, xdp_prog);
3358                if (unlikely(err))
3359                        goto err;
3360        } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
3361                struct xdp_sock *xs = fwd;
3362
3363                err = xsk_generic_rcv(xs, xdp);
3364                if (err)
3365                        goto err;
3366                consume_skb(skb);
3367        } else {
3368                /* TODO: Handle BPF_MAP_TYPE_CPUMAP */
3369                err = -EBADRQC;
3370                goto err;
3371        }
3372
3373        _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3374        return 0;
3375err:
3376        _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3377        return err;
3378}
3379
3380int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
3381                            struct xdp_buff *xdp, struct bpf_prog *xdp_prog)
3382{
3383        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3384        struct bpf_map *map = READ_ONCE(ri->map);
3385        u32 index = ri->ifindex;
3386        struct net_device *fwd;
3387        int err = 0;
3388
3389        if (map)
3390                return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog,
3391                                                   map);
3392        ri->ifindex = 0;
3393        fwd = dev_get_by_index_rcu(dev_net(dev), index);
3394        if (unlikely(!fwd)) {
3395                err = -EINVAL;
3396                goto err;
3397        }
3398
3399        err = xdp_ok_fwd_dev(fwd, skb->len);
3400        if (unlikely(err))
3401                goto err;
3402
3403        skb->dev = fwd;
3404        _trace_xdp_redirect(dev, xdp_prog, index);
3405        generic_xdp_tx(skb, xdp_prog);
3406        return 0;
3407err:
3408        _trace_xdp_redirect_err(dev, xdp_prog, index, err);
3409        return err;
3410}
3411EXPORT_SYMBOL_GPL(xdp_do_generic_redirect);
3412
3413BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
3414{
3415        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3416
3417        if (unlikely(flags))
3418                return XDP_ABORTED;
3419
3420        ri->ifindex = ifindex;
3421        ri->flags = flags;
3422        WRITE_ONCE(ri->map, NULL);
3423
3424        return XDP_REDIRECT;
3425}
3426
3427static const struct bpf_func_proto bpf_xdp_redirect_proto = {
3428        .func           = bpf_xdp_redirect,
3429        .gpl_only       = false,
3430        .ret_type       = RET_INTEGER,
3431        .arg1_type      = ARG_ANYTHING,
3432        .arg2_type      = ARG_ANYTHING,
3433};
3434
3435BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u32, ifindex,
3436           u64, flags)
3437{
3438        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3439
3440        if (unlikely(flags))
3441                return XDP_ABORTED;
3442
3443        ri->ifindex = ifindex;
3444        ri->flags = flags;
3445        WRITE_ONCE(ri->map, map);
3446
3447        return XDP_REDIRECT;
3448}
3449
3450static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
3451        .func           = bpf_xdp_redirect_map,
3452        .gpl_only       = false,
3453        .ret_type       = RET_INTEGER,
3454        .arg1_type      = ARG_CONST_MAP_PTR,
3455        .arg2_type      = ARG_ANYTHING,
3456        .arg3_type      = ARG_ANYTHING,
3457};
3458
3459static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
3460                                  unsigned long off, unsigned long len)
3461{
3462        void *ptr = skb_header_pointer(skb, off, len, dst_buff);
3463
3464        if (unlikely(!ptr))
3465                return len;
3466        if (ptr != dst_buff)
3467                memcpy(dst_buff, ptr, len);
3468
3469        return 0;
3470}
3471
3472BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
3473           u64, flags, void *, meta, u64, meta_size)
3474{
3475        u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
3476
3477        if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
3478                return -EINVAL;
3479        if (unlikely(skb_size > skb->len))
3480                return -EFAULT;
3481
3482        return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
3483                                bpf_skb_copy);
3484}
3485
3486static const struct bpf_func_proto bpf_skb_event_output_proto = {
3487        .func           = bpf_skb_event_output,
3488        .gpl_only       = true,
3489        .ret_type       = RET_INTEGER,
3490        .arg1_type      = ARG_PTR_TO_CTX,
3491        .arg2_type      = ARG_CONST_MAP_PTR,
3492        .arg3_type      = ARG_ANYTHING,
3493        .arg4_type      = ARG_PTR_TO_MEM,
3494        .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
3495};
3496
3497static unsigned short bpf_tunnel_key_af(u64 flags)
3498{
3499        return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
3500}
3501
3502BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
3503           u32, size, u64, flags)
3504{
3505        const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3506        u8 compat[sizeof(struct bpf_tunnel_key)];
3507        void *to_orig = to;
3508        int err;
3509
3510        if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) {
3511                err = -EINVAL;
3512                goto err_clear;
3513        }
3514        if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
3515                err = -EPROTO;
3516                goto err_clear;
3517        }
3518        if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3519                err = -EINVAL;
3520                switch (size) {
3521                case offsetof(struct bpf_tunnel_key, tunnel_label):
3522                case offsetof(struct bpf_tunnel_key, tunnel_ext):
3523                        goto set_compat;
3524                case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3525                        /* Fixup deprecated structure layouts here, so we have
3526                         * a common path later on.
3527                         */
3528                        if (ip_tunnel_info_af(info) != AF_INET)
3529                                goto err_clear;
3530set_compat:
3531                        to = (struct bpf_tunnel_key *)compat;
3532                        break;
3533                default:
3534                        goto err_clear;
3535                }
3536        }
3537
3538        to->tunnel_id = be64_to_cpu(info->key.tun_id);
3539        to->tunnel_tos = info->key.tos;
3540        to->tunnel_ttl = info->key.ttl;
3541        to->tunnel_ext = 0;
3542
3543        if (flags & BPF_F_TUNINFO_IPV6) {
3544                memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
3545                       sizeof(to->remote_ipv6));
3546                to->tunnel_label = be32_to_cpu(info->key.label);
3547        } else {
3548                to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
3549                memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
3550                to->tunnel_label = 0;
3551        }
3552
3553        if (unlikely(size != sizeof(struct bpf_tunnel_key)))
3554                memcpy(to_orig, to, size);
3555
3556        return 0;
3557err_clear:
3558        memset(to_orig, 0, size);
3559        return err;
3560}
3561
3562static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
3563        .func           = bpf_skb_get_tunnel_key,
3564        .gpl_only       = false,
3565        .ret_type       = RET_INTEGER,
3566        .arg1_type      = ARG_PTR_TO_CTX,
3567        .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
3568        .arg3_type      = ARG_CONST_SIZE,
3569        .arg4_type      = ARG_ANYTHING,
3570};
3571
3572BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
3573{
3574        const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3575        int err;
3576
3577        if (unlikely(!info ||
3578                     !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
3579                err = -ENOENT;
3580                goto err_clear;
3581        }
3582        if (unlikely(size < info->options_len)) {
3583                err = -ENOMEM;
3584                goto err_clear;
3585        }
3586
3587        ip_tunnel_info_opts_get(to, info);
3588        if (size > info->options_len)
3589                memset(to + info->options_len, 0, size - info->options_len);
3590
3591        return info->options_len;
3592err_clear:
3593        memset(to, 0, size);
3594        return err;
3595}
3596
3597static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
3598        .func           = bpf_skb_get_tunnel_opt,
3599        .gpl_only       = false,
3600        .ret_type       = RET_INTEGER,
3601        .arg1_type      = ARG_PTR_TO_CTX,
3602        .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
3603        .arg3_type      = ARG_CONST_SIZE,
3604};
3605
3606static struct metadata_dst __percpu *md_dst;
3607
3608BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
3609           const struct bpf_tunnel_key *, from, u32, size, u64, flags)
3610{
3611        struct metadata_dst *md = this_cpu_ptr(md_dst);
3612        u8 compat[sizeof(struct bpf_tunnel_key)];
3613        struct ip_tunnel_info *info;
3614
3615        if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
3616                               BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER)))
3617                return -EINVAL;
3618        if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3619                switch (size) {
3620                case offsetof(struct bpf_tunnel_key, tunnel_label):
3621                case offsetof(struct bpf_tunnel_key, tunnel_ext):
3622                case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3623                        /* Fixup deprecated structure layouts here, so we have
3624                         * a common path later on.
3625                         */
3626                        memcpy(compat, from, size);
3627                        memset(compat + size, 0, sizeof(compat) - size);
3628                        from = (const struct bpf_tunnel_key *) compat;
3629                        break;
3630                default:
3631                        return -EINVAL;
3632                }
3633        }
3634        if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
3635                     from->tunnel_ext))
3636                return -EINVAL;
3637
3638        skb_dst_drop(skb);
3639        dst_hold((struct dst_entry *) md);
3640        skb_dst_set(skb, (struct dst_entry *) md);
3641
3642        info = &md->u.tun_info;
3643        memset(info, 0, sizeof(*info));
3644        info->mode = IP_TUNNEL_INFO_TX;
3645
3646        info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
3647        if (flags & BPF_F_DONT_FRAGMENT)
3648                info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;
3649        if (flags & BPF_F_ZERO_CSUM_TX)
3650                info->key.tun_flags &= ~TUNNEL_CSUM;
3651        if (flags & BPF_F_SEQ_NUMBER)
3652                info->key.tun_flags |= TUNNEL_SEQ;
3653
3654        info->key.tun_id = cpu_to_be64(from->tunnel_id);
3655        info->key.tos = from->tunnel_tos;
3656        info->key.ttl = from->tunnel_ttl;
3657
3658        if (flags & BPF_F_TUNINFO_IPV6) {
3659                info->mode |= IP_TUNNEL_INFO_IPV6;
3660                memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
3661                       sizeof(from->remote_ipv6));
3662                info->key.label = cpu_to_be32(from->tunnel_label) &
3663                                  IPV6_FLOWLABEL_MASK;
3664        } else {
3665                info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
3666        }
3667
3668        return 0;
3669}
3670
3671static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
3672        .func           = bpf_skb_set_tunnel_key,
3673        .gpl_only       = false,
3674        .ret_type       = RET_INTEGER,
3675        .arg1_type      = ARG_PTR_TO_CTX,
3676        .arg2_type      = ARG_PTR_TO_MEM,
3677        .arg3_type      = ARG_CONST_SIZE,
3678        .arg4_type      = ARG_ANYTHING,
3679};
3680
3681BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
3682           const u8 *, from, u32, size)
3683{
3684        struct ip_tunnel_info *info = skb_tunnel_info(skb);
3685        const struct metadata_dst *md = this_cpu_ptr(md_dst);
3686
3687        if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
3688                return -EINVAL;
3689        if (unlikely(size > IP_TUNNEL_OPTS_MAX))
3690                return -ENOMEM;
3691
3692        ip_tunnel_info_opts_set(info, from, size, TUNNEL_OPTIONS_PRESENT);
3693
3694        return 0;
3695}
3696
3697static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
3698        .func           = bpf_skb_set_tunnel_opt,
3699        .gpl_only       = false,
3700        .ret_type       = RET_INTEGER,
3701        .arg1_type      = ARG_PTR_TO_CTX,
3702        .arg2_type      = ARG_PTR_TO_MEM,
3703        .arg3_type      = ARG_CONST_SIZE,
3704};
3705
3706static const struct bpf_func_proto *
3707bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
3708{
3709        if (!md_dst) {
3710                struct metadata_dst __percpu *tmp;
3711
3712                tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
3713                                                METADATA_IP_TUNNEL,
3714                                                GFP_KERNEL);
3715                if (!tmp)
3716                        return NULL;
3717                if (cmpxchg(&md_dst, NULL, tmp))
3718                        metadata_dst_free_percpu(tmp);
3719        }
3720
3721        switch (which) {
3722        case BPF_FUNC_skb_set_tunnel_key:
3723                return &bpf_skb_set_tunnel_key_proto;
3724        case BPF_FUNC_skb_set_tunnel_opt:
3725                return &bpf_skb_set_tunnel_opt_proto;
3726        default:
3727                return NULL;
3728        }
3729}
3730
3731BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
3732           u32, idx)
3733{
3734        struct bpf_array *array = container_of(map, struct bpf_array, map);
3735        struct cgroup *cgrp;
3736        struct sock *sk;
3737
3738        sk = skb_to_full_sk(skb);
3739        if (!sk || !sk_fullsock(sk))
3740                return -ENOENT;
3741        if (unlikely(idx >= array->map.max_entries))
3742                return -E2BIG;
3743
3744        cgrp = READ_ONCE(array->ptrs[idx]);
3745        if (unlikely(!cgrp))
3746                return -EAGAIN;
3747
3748        return sk_under_cgroup_hierarchy(sk, cgrp);
3749}
3750
3751static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
3752        .func           = bpf_skb_under_cgroup,
3753        .gpl_only       = false,
3754        .ret_type       = RET_INTEGER,
3755        .arg1_type      = ARG_PTR_TO_CTX,
3756        .arg2_type      = ARG_CONST_MAP_PTR,
3757        .arg3_type      = ARG_ANYTHING,
3758};
3759
3760#ifdef CONFIG_SOCK_CGROUP_DATA
3761BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
3762{
3763        struct sock *sk = skb_to_full_sk(skb);
3764        struct cgroup *cgrp;
3765
3766        if (!sk || !sk_fullsock(sk))
3767                return 0;
3768
3769        cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
3770        return cgrp->kn->id.id;
3771}
3772
3773static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
3774        .func           = bpf_skb_cgroup_id,
3775        .gpl_only       = false,
3776        .ret_type       = RET_INTEGER,
3777        .arg1_type      = ARG_PTR_TO_CTX,
3778};
3779
3780BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
3781           ancestor_level)
3782{
3783        struct sock *sk = skb_to_full_sk(skb);
3784        struct cgroup *ancestor;
3785        struct cgroup *cgrp;
3786
3787        if (!sk || !sk_fullsock(sk))
3788                return 0;
3789
3790        cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
3791        ancestor = cgroup_ancestor(cgrp, ancestor_level);
3792        if (!ancestor)
3793                return 0;
3794
3795        return ancestor->kn->id.id;
3796}
3797
3798static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
3799        .func           = bpf_skb_ancestor_cgroup_id,
3800        .gpl_only       = false,
3801        .ret_type       = RET_INTEGER,
3802        .arg1_type      = ARG_PTR_TO_CTX,
3803        .arg2_type      = ARG_ANYTHING,
3804};
3805#endif
3806
3807static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff,
3808                                  unsigned long off, unsigned long len)
3809{
3810        memcpy(dst_buff, src_buff + off, len);
3811        return 0;
3812}
3813
3814BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
3815           u64, flags, void *, meta, u64, meta_size)
3816{
3817        u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
3818
3819        if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
3820                return -EINVAL;
3821        if (unlikely(xdp_size > (unsigned long)(xdp->data_end - xdp->data)))
3822                return -EFAULT;
3823
3824        return bpf_event_output(map, flags, meta, meta_size, xdp->data,
3825                                xdp_size, bpf_xdp_copy);
3826}
3827
3828static const struct bpf_func_proto bpf_xdp_event_output_proto = {
3829        .func           = bpf_xdp_event_output,
3830        .gpl_only       = true,
3831        .ret_type       = RET_INTEGER,
3832        .arg1_type      = ARG_PTR_TO_CTX,
3833        .arg2_type      = ARG_CONST_MAP_PTR,
3834        .arg3_type      = ARG_ANYTHING,
3835        .arg4_type      = ARG_PTR_TO_MEM,
3836        .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
3837};
3838
3839BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
3840{
3841        return skb->sk ? sock_gen_cookie(skb->sk) : 0;
3842}
3843
3844static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
3845        .func           = bpf_get_socket_cookie,
3846        .gpl_only       = false,
3847        .ret_type       = RET_INTEGER,
3848        .arg1_type      = ARG_PTR_TO_CTX,
3849};
3850
3851BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
3852{
3853        return sock_gen_cookie(ctx->sk);
3854}
3855
3856static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
3857        .func           = bpf_get_socket_cookie_sock_addr,
3858        .gpl_only       = false,
3859        .ret_type       = RET_INTEGER,
3860        .arg1_type      = ARG_PTR_TO_CTX,
3861};
3862
3863BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
3864{
3865        return sock_gen_cookie(ctx->sk);
3866}
3867
3868static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
3869        .func           = bpf_get_socket_cookie_sock_ops,
3870        .gpl_only       = false,
3871        .ret_type       = RET_INTEGER,
3872        .arg1_type      = ARG_PTR_TO_CTX,
3873};
3874
3875BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
3876{
3877        struct sock *sk = sk_to_full_sk(skb->sk);
3878        kuid_t kuid;
3879
3880        if (!sk || !sk_fullsock(sk))
3881                return overflowuid;
3882        kuid = sock_net_uid(sock_net(sk), sk);
3883        return from_kuid_munged(sock_net(sk)->user_ns, kuid);
3884}
3885
3886static const struct bpf_func_proto bpf_get_socket_uid_proto = {
3887        .func           = bpf_get_socket_uid,
3888        .gpl_only       = false,
3889        .ret_type       = RET_INTEGER,
3890        .arg1_type      = ARG_PTR_TO_CTX,
3891};
3892
3893BPF_CALL_5(bpf_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
3894           int, level, int, optname, char *, optval, int, optlen)
3895{
3896        struct sock *sk = bpf_sock->sk;
3897        int ret = 0;
3898        int val;
3899
3900        if (!sk_fullsock(sk))
3901                return -EINVAL;
3902
3903        if (level == SOL_SOCKET) {
3904                if (optlen != sizeof(int))
3905                        return -EINVAL;
3906                val = *((int *)optval);
3907
3908                /* Only some socketops are supported */
3909                switch (optname) {
3910                case SO_RCVBUF:
3911                        sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
3912                        sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);
3913                        break;
3914                case SO_SNDBUF:
3915                        sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
3916                        sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
3917                        break;
3918                case SO_MAX_PACING_RATE:
3919                        sk->sk_max_pacing_rate = val;
3920                        sk->sk_pacing_rate = min(sk->sk_pacing_rate,
3921                                                 sk->sk_max_pacing_rate);
3922                        break;
3923                case SO_PRIORITY:
3924                        sk->sk_priority = val;
3925                        break;
3926                case SO_RCVLOWAT:
3927                        if (val < 0)
3928                                val = INT_MAX;
3929                        sk->sk_rcvlowat = val ? : 1;
3930                        break;
3931                case SO_MARK:
3932                        sk->sk_mark = val;
3933                        break;
3934                default:
3935                        ret = -EINVAL;
3936                }
3937#ifdef CONFIG_INET
3938        } else if (level == SOL_IP) {
3939                if (optlen != sizeof(int) || sk->sk_family != AF_INET)
3940                        return -EINVAL;
3941
3942                val = *((int *)optval);
3943                /* Only some options are supported */
3944                switch (optname) {
3945                case IP_TOS:
3946                        if (val < -1 || val > 0xff) {
3947                                ret = -EINVAL;
3948                        } else {
3949                                struct inet_sock *inet = inet_sk(sk);
3950
3951                                if (val == -1)
3952                                        val = 0;
3953                                inet->tos = val;
3954                        }
3955                        break;
3956                default:
3957                        ret = -EINVAL;
3958                }
3959#if IS_ENABLED(CONFIG_IPV6)
3960        } else if (level == SOL_IPV6) {
3961                if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
3962                        return -EINVAL;
3963
3964                val = *((int *)optval);
3965                /* Only some options are supported */
3966                switch (optname) {
3967                case IPV6_TCLASS:
3968                        if (val < -1 || val > 0xff) {
3969                                ret = -EINVAL;
3970                        } else {
3971                                struct ipv6_pinfo *np = inet6_sk(sk);
3972
3973                                if (val == -1)
3974                                        val = 0;
3975                                np->tclass = val;
3976                        }
3977                        break;
3978                default:
3979                        ret = -EINVAL;
3980                }
3981#endif
3982        } else if (level == SOL_TCP &&
3983                   sk->sk_prot->setsockopt == tcp_setsockopt) {
3984                if (optname == TCP_CONGESTION) {
3985                        char name[TCP_CA_NAME_MAX];
3986                        bool reinit = bpf_sock->op > BPF_SOCK_OPS_NEEDS_ECN;
3987
3988                        strncpy(name, optval, min_t(long, optlen,
3989                                                    TCP_CA_NAME_MAX-1));
3990                        name[TCP_CA_NAME_MAX-1] = 0;
3991                        ret = tcp_set_congestion_control(sk, name, false,
3992                                                         reinit);
3993                } else {
3994                        struct tcp_sock *tp = tcp_sk(sk);
3995
3996                        if (optlen != sizeof(int))
3997                                return -EINVAL;
3998
3999                        val = *((int *)optval);
4000                        /* Only some options are supported */
4001                        switch (optname) {
4002                        case TCP_BPF_IW:
4003                                if (val <= 0 || tp->data_segs_out > 0)
4004                                        ret = -EINVAL;
4005                                else
4006                                        tp->snd_cwnd = val;
4007                                break;
4008                        case TCP_BPF_SNDCWND_CLAMP:
4009                                if (val <= 0) {
4010                                        ret = -EINVAL;
4011                                } else {
4012                                        tp->snd_cwnd_clamp = val;
4013                                        tp->snd_ssthresh = val;
4014                                }
4015                                break;
4016                        default:
4017                                ret = -EINVAL;
4018                        }
4019                }
4020#endif
4021        } else {
4022                ret = -EINVAL;
4023        }
4024        return ret;
4025}
4026
4027static const struct bpf_func_proto bpf_setsockopt_proto = {
4028        .func           = bpf_setsockopt,
4029        .gpl_only       = false,
4030        .ret_type       = RET_INTEGER,
4031        .arg1_type      = ARG_PTR_TO_CTX,
4032        .arg2_type      = ARG_ANYTHING,
4033        .arg3_type      = ARG_ANYTHING,
4034        .arg4_type      = ARG_PTR_TO_MEM,
4035        .arg5_type      = ARG_CONST_SIZE,
4036};
4037
4038BPF_CALL_5(bpf_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4039           int, level, int, optname, char *, optval, int, optlen)
4040{
4041        struct sock *sk = bpf_sock->sk;
4042
4043        if (!sk_fullsock(sk))
4044                goto err_clear;
4045
4046#ifdef CONFIG_INET
4047        if (level == SOL_TCP && sk->sk_prot->getsockopt == tcp_getsockopt) {
4048                if (optname == TCP_CONGESTION) {
4049                        struct inet_connection_sock *icsk = inet_csk(sk);
4050
4051                        if (!icsk->icsk_ca_ops || optlen <= 1)
4052                                goto err_clear;
4053                        strncpy(optval, icsk->icsk_ca_ops->name, optlen);
4054                        optval[optlen - 1] = 0;
4055                } else {
4056                        goto err_clear;
4057                }
4058        } else if (level == SOL_IP) {
4059                struct inet_sock *inet = inet_sk(sk);
4060
4061                if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4062                        goto err_clear;
4063
4064                /* Only some options are supported */
4065                switch (optname) {
4066                case IP_TOS:
4067                        *((int *)optval) = (int)inet->tos;
4068                        break;
4069                default:
4070                        goto err_clear;
4071                }
4072#if IS_ENABLED(CONFIG_IPV6)
4073        } else if (level == SOL_IPV6) {
4074                struct ipv6_pinfo *np = inet6_sk(sk);
4075
4076                if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4077                        goto err_clear;
4078
4079                /* Only some options are supported */
4080                switch (optname) {
4081                case IPV6_TCLASS:
4082                        *((int *)optval) = (int)np->tclass;
4083                        break;
4084                default:
4085                        goto err_clear;
4086                }
4087#endif
4088        } else {
4089                goto err_clear;
4090        }
4091        return 0;
4092#endif
4093err_clear:
4094        memset(optval, 0, optlen);
4095        return -EINVAL;
4096}
4097
4098static const struct bpf_func_proto bpf_getsockopt_proto = {
4099        .func           = bpf_getsockopt,
4100        .gpl_only       = false,
4101        .ret_type       = RET_INTEGER,
4102        .arg1_type      = ARG_PTR_TO_CTX,
4103        .arg2_type      = ARG_ANYTHING,
4104        .arg3_type      = ARG_ANYTHING,
4105        .arg4_type      = ARG_PTR_TO_UNINIT_MEM,
4106        .arg5_type      = ARG_CONST_SIZE,
4107};
4108
4109BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
4110           int, argval)
4111{
4112        struct sock *sk = bpf_sock->sk;
4113        int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
4114
4115        if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
4116                return -EINVAL;
4117
4118        if (val)
4119                tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
4120
4121        return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
4122}
4123
4124static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
4125        .func           = bpf_sock_ops_cb_flags_set,
4126        .gpl_only       = false,
4127        .ret_type       = RET_INTEGER,
4128        .arg1_type      = ARG_PTR_TO_CTX,
4129        .arg2_type      = ARG_ANYTHING,
4130};
4131
4132const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly;
4133EXPORT_SYMBOL_GPL(ipv6_bpf_stub);
4134
4135BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
4136           int, addr_len)
4137{
4138#ifdef CONFIG_INET
4139        struct sock *sk = ctx->sk;
4140        int err;
4141
4142        /* Binding to port can be expensive so it's prohibited in the helper.
4143         * Only binding to IP is supported.
4144         */
4145        err = -EINVAL;
4146        if (addr->sa_family == AF_INET) {
4147                if (addr_len < sizeof(struct sockaddr_in))
4148                        return err;
4149                if (((struct sockaddr_in *)addr)->sin_port != htons(0))
4150                        return err;
4151                return __inet_bind(sk, addr, addr_len, true, false);
4152#if IS_ENABLED(CONFIG_IPV6)
4153        } else if (addr->sa_family == AF_INET6) {
4154                if (addr_len < SIN6_LEN_RFC2133)
4155                        return err;
4156                if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
4157                        return err;
4158                /* ipv6_bpf_stub cannot be NULL, since it's called from
4159                 * bpf_cgroup_inet6_connect hook and ipv6 is already loaded
4160                 */
4161                return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, true, false);
4162#endif /* CONFIG_IPV6 */
4163        }
4164#endif /* CONFIG_INET */
4165
4166        return -EAFNOSUPPORT;
4167}
4168
4169static const struct bpf_func_proto bpf_bind_proto = {
4170        .func           = bpf_bind,
4171        .gpl_only       = false,
4172        .ret_type       = RET_INTEGER,
4173        .arg1_type      = ARG_PTR_TO_CTX,
4174        .arg2_type      = ARG_PTR_TO_MEM,
4175        .arg3_type      = ARG_CONST_SIZE,
4176};
4177
4178#ifdef CONFIG_XFRM
4179BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
4180           struct bpf_xfrm_state *, to, u32, size, u64, flags)
4181{
4182        const struct sec_path *sp = skb_sec_path(skb);
4183        const struct xfrm_state *x;
4184
4185        if (!sp || unlikely(index >= sp->len || flags))
4186                goto err_clear;
4187
4188        x = sp->xvec[index];
4189
4190        if (unlikely(size != sizeof(struct bpf_xfrm_state)))
4191                goto err_clear;
4192
4193        to->reqid = x->props.reqid;
4194        to->spi = x->id.spi;
4195        to->family = x->props.family;
4196        to->ext = 0;
4197
4198        if (to->family == AF_INET6) {
4199                memcpy(to->remote_ipv6, x->props.saddr.a6,
4200                       sizeof(to->remote_ipv6));
4201        } else {
4202                to->remote_ipv4 = x->props.saddr.a4;
4203                memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4204        }
4205
4206        return 0;
4207err_clear:
4208        memset(to, 0, size);
4209        return -EINVAL;
4210}
4211
4212static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
4213        .func           = bpf_skb_get_xfrm_state,
4214        .gpl_only       = false,
4215        .ret_type       = RET_INTEGER,
4216        .arg1_type      = ARG_PTR_TO_CTX,
4217        .arg2_type      = ARG_ANYTHING,
4218        .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
4219        .arg4_type      = ARG_CONST_SIZE,
4220        .arg5_type      = ARG_ANYTHING,
4221};
4222#endif
4223
4224#if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
4225static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params,
4226                                  const struct neighbour *neigh,
4227                                  const struct net_device *dev)
4228{
4229        memcpy(params->dmac, neigh->ha, ETH_ALEN);
4230        memcpy(params->smac, dev->dev_addr, ETH_ALEN);
4231        params->h_vlan_TCI = 0;
4232        params->h_vlan_proto = 0;
4233        params->ifindex = dev->ifindex;
4234
4235        return 0;
4236}
4237#endif
4238
4239#if IS_ENABLED(CONFIG_INET)
4240static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4241                               u32 flags, bool check_mtu)
4242{
4243        struct in_device *in_dev;
4244        struct neighbour *neigh;
4245        struct net_device *dev;
4246        struct fib_result res;
4247        struct fib_nh *nh;
4248        struct flowi4 fl4;
4249        int err;
4250        u32 mtu;
4251
4252        dev = dev_get_by_index_rcu(net, params->ifindex);
4253        if (unlikely(!dev))
4254                return -ENODEV;
4255
4256        /* verify forwarding is enabled on this interface */
4257        in_dev = __in_dev_get_rcu(dev);
4258        if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
4259                return BPF_FIB_LKUP_RET_FWD_DISABLED;
4260
4261        if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4262                fl4.flowi4_iif = 1;
4263                fl4.flowi4_oif = params->ifindex;
4264        } else {
4265                fl4.flowi4_iif = params->ifindex;
4266                fl4.flowi4_oif = 0;
4267        }
4268        fl4.flowi4_tos = params->tos & IPTOS_RT_MASK;
4269        fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
4270        fl4.flowi4_flags = 0;
4271
4272        fl4.flowi4_proto = params->l4_protocol;
4273        fl4.daddr = params->ipv4_dst;
4274        fl4.saddr = params->ipv4_src;
4275        fl4.fl4_sport = params->sport;
4276        fl4.fl4_dport = params->dport;
4277
4278        if (flags & BPF_FIB_LOOKUP_DIRECT) {
4279                u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4280                struct fib_table *tb;
4281
4282                tb = fib_get_table(net, tbid);
4283                if (unlikely(!tb))
4284                        return BPF_FIB_LKUP_RET_NOT_FWDED;
4285
4286                err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
4287        } else {
4288                fl4.flowi4_mark = 0;
4289                fl4.flowi4_secid = 0;
4290                fl4.flowi4_tun_key.tun_id = 0;
4291                fl4.flowi4_uid = sock_net_uid(net, NULL);
4292
4293                err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
4294        }
4295
4296        if (err) {
4297                /* map fib lookup errors to RTN_ type */
4298                if (err == -EINVAL)
4299                        return BPF_FIB_LKUP_RET_BLACKHOLE;
4300                if (err == -EHOSTUNREACH)
4301                        return BPF_FIB_LKUP_RET_UNREACHABLE;
4302                if (err == -EACCES)
4303                        return BPF_FIB_LKUP_RET_PROHIBIT;
4304
4305                return BPF_FIB_LKUP_RET_NOT_FWDED;
4306        }
4307
4308        if (res.type != RTN_UNICAST)
4309                return BPF_FIB_LKUP_RET_NOT_FWDED;
4310
4311        if (res.fi->fib_nhs > 1)
4312                fib_select_path(net, &res, &fl4, NULL);
4313
4314        if (check_mtu) {
4315                mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
4316                if (params->tot_len > mtu)
4317                        return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4318        }
4319
4320        nh = &res.fi->fib_nh[res.nh_sel];
4321
4322        /* do not handle lwt encaps right now */
4323        if (nh->nh_lwtstate)
4324                return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4325
4326        dev = nh->nh_dev;
4327        if (nh->nh_gw)
4328                params->ipv4_dst = nh->nh_gw;
4329
4330        params->rt_metric = res.fi->fib_priority;
4331
4332        /* xdp and cls_bpf programs are run in RCU-bh so
4333         * rcu_read_lock_bh is not needed here
4334         */
4335        neigh = __ipv4_neigh_lookup_noref(dev, (__force u32)params->ipv4_dst);
4336        if (!neigh)
4337                return BPF_FIB_LKUP_RET_NO_NEIGH;
4338
4339        return bpf_fib_set_fwd_params(params, neigh, dev);
4340}
4341#endif
4342
4343#if IS_ENABLED(CONFIG_IPV6)
4344static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4345                               u32 flags, bool check_mtu)
4346{
4347        struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
4348        struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
4349        struct neighbour *neigh;
4350        struct net_device *dev;
4351        struct inet6_dev *idev;
4352        struct fib6_info *f6i;
4353        struct flowi6 fl6;
4354        int strict = 0;
4355        int oif;
4356        u32 mtu;
4357
4358        /* link local addresses are never forwarded */
4359        if (rt6_need_strict(dst) || rt6_need_strict(src))
4360                return BPF_FIB_LKUP_RET_NOT_FWDED;
4361
4362        dev = dev_get_by_index_rcu(net, params->ifindex);
4363        if (unlikely(!dev))
4364                return -ENODEV;
4365
4366        idev = __in6_dev_get_safely(dev);
4367        if (unlikely(!idev || !net->ipv6.devconf_all->forwarding))
4368                return BPF_FIB_LKUP_RET_FWD_DISABLED;
4369
4370        if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4371                fl6.flowi6_iif = 1;
4372                oif = fl6.flowi6_oif = params->ifindex;
4373        } else {
4374                oif = fl6.flowi6_iif = params->ifindex;
4375                fl6.flowi6_oif = 0;
4376                strict = RT6_LOOKUP_F_HAS_SADDR;
4377        }
4378        fl6.flowlabel = params->flowinfo;
4379        fl6.flowi6_scope = 0;
4380        fl6.flowi6_flags = 0;
4381        fl6.mp_hash = 0;
4382
4383        fl6.flowi6_proto = params->l4_protocol;
4384        fl6.daddr = *dst;
4385        fl6.saddr = *src;
4386        fl6.fl6_sport = params->sport;
4387        fl6.fl6_dport = params->dport;
4388
4389        if (flags & BPF_FIB_LOOKUP_DIRECT) {
4390                u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4391                struct fib6_table *tb;
4392
4393                tb = ipv6_stub->fib6_get_table(net, tbid);
4394                if (unlikely(!tb))
4395                        return BPF_FIB_LKUP_RET_NOT_FWDED;
4396
4397                f6i = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, strict);
4398        } else {
4399                fl6.flowi6_mark = 0;
4400                fl6.flowi6_secid = 0;
4401                fl6.flowi6_tun_key.tun_id = 0;
4402                fl6.flowi6_uid = sock_net_uid(net, NULL);
4403
4404                f6i = ipv6_stub->fib6_lookup(net, oif, &fl6, strict);
4405        }
4406
4407        if (unlikely(IS_ERR_OR_NULL(f6i) || f6i == net->ipv6.fib6_null_entry))
4408                return BPF_FIB_LKUP_RET_NOT_FWDED;
4409
4410        if (unlikely(f6i->fib6_flags & RTF_REJECT)) {
4411                switch (f6i->fib6_type) {
4412                case RTN_BLACKHOLE:
4413                        return BPF_FIB_LKUP_RET_BLACKHOLE;
4414                case RTN_UNREACHABLE:
4415                        return BPF_FIB_LKUP_RET_UNREACHABLE;
4416                case RTN_PROHIBIT:
4417                        return BPF_FIB_LKUP_RET_PROHIBIT;
4418                default:
4419                        return BPF_FIB_LKUP_RET_NOT_FWDED;
4420                }
4421        }
4422
4423        if (f6i->fib6_type != RTN_UNICAST)
4424                return BPF_FIB_LKUP_RET_NOT_FWDED;
4425
4426        if (f6i->fib6_nsiblings && fl6.flowi6_oif == 0)
4427                f6i = ipv6_stub->fib6_multipath_select(net, f6i, &fl6,
4428                                                       fl6.flowi6_oif, NULL,
4429                                                       strict);
4430
4431        if (check_mtu) {
4432                mtu = ipv6_stub->ip6_mtu_from_fib6(f6i, dst, src);
4433                if (params->tot_len > mtu)
4434                        return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4435        }
4436
4437        if (f6i->fib6_nh.nh_lwtstate)
4438                return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4439
4440        if (f6i->fib6_flags & RTF_GATEWAY)
4441                *dst = f6i->fib6_nh.nh_gw;
4442
4443        dev = f6i->fib6_nh.nh_dev;
4444        params->rt_metric = f6i->fib6_metric;
4445
4446        /* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
4447         * not needed here. Can not use __ipv6_neigh_lookup_noref here
4448         * because we need to get nd_tbl via the stub
4449         */
4450        neigh = ___neigh_lookup_noref(ipv6_stub->nd_tbl, neigh_key_eq128,
4451                                      ndisc_hashfn, dst, dev);
4452        if (!neigh)
4453                return BPF_FIB_LKUP_RET_NO_NEIGH;
4454
4455        return bpf_fib_set_fwd_params(params, neigh, dev);
4456}
4457#endif
4458
4459BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
4460           struct bpf_fib_lookup *, params, int, plen, u32, flags)
4461{
4462        if (plen < sizeof(*params))
4463                return -EINVAL;
4464
4465        if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4466                return -EINVAL;
4467
4468        switch (params->family) {
4469#if IS_ENABLED(CONFIG_INET)
4470        case AF_INET:
4471                return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
4472                                           flags, true);
4473#endif
4474#if IS_ENABLED(CONFIG_IPV6)
4475        case AF_INET6:
4476                return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
4477                                           flags, true);
4478#endif
4479        }
4480        return -EAFNOSUPPORT;
4481}
4482
4483static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
4484        .func           = bpf_xdp_fib_lookup,
4485        .gpl_only       = true,
4486        .ret_type       = RET_INTEGER,
4487        .arg1_type      = ARG_PTR_TO_CTX,
4488        .arg2_type      = ARG_PTR_TO_MEM,
4489        .arg3_type      = ARG_CONST_SIZE,
4490        .arg4_type      = ARG_ANYTHING,
4491};
4492
4493BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
4494           struct bpf_fib_lookup *, params, int, plen, u32, flags)
4495{
4496        struct net *net = dev_net(skb->dev);
4497        int rc = -EAFNOSUPPORT;
4498
4499        if (plen < sizeof(*params))
4500                return -EINVAL;
4501
4502        if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4503                return -EINVAL;
4504
4505        switch (params->family) {
4506#if IS_ENABLED(CONFIG_INET)
4507        case AF_INET:
4508                rc = bpf_ipv4_fib_lookup(net, params, flags, false);
4509                break;
4510#endif
4511#if IS_ENABLED(CONFIG_IPV6)
4512        case AF_INET6:
4513                rc = bpf_ipv6_fib_lookup(net, params, flags, false);
4514                break;
4515#endif
4516        }
4517
4518        if (!rc) {
4519                struct net_device *dev;
4520
4521                dev = dev_get_by_index_rcu(net, params->ifindex);
4522                if (!is_skb_forwardable(dev, skb))
4523                        rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
4524        }
4525
4526        return rc;
4527}
4528
4529static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
4530        .func           = bpf_skb_fib_lookup,
4531        .gpl_only       = true,
4532        .ret_type       = RET_INTEGER,
4533        .arg1_type      = ARG_PTR_TO_CTX,
4534        .arg2_type      = ARG_PTR_TO_MEM,
4535        .arg3_type      = ARG_CONST_SIZE,
4536        .arg4_type      = ARG_ANYTHING,
4537};
4538
4539#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4540static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
4541{
4542        int err;
4543        struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;
4544
4545        if (!seg6_validate_srh(srh, len))
4546                return -EINVAL;
4547
4548        switch (type) {
4549        case BPF_LWT_ENCAP_SEG6_INLINE:
4550                if (skb->protocol != htons(ETH_P_IPV6))
4551                        return -EBADMSG;
4552
4553                err = seg6_do_srh_inline(skb, srh);
4554                break;
4555        case BPF_LWT_ENCAP_SEG6:
4556                skb_reset_inner_headers(skb);
4557                skb->encapsulation = 1;
4558                err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
4559                break;
4560        default:
4561                return -EINVAL;
4562        }
4563
4564        bpf_compute_data_pointers(skb);
4565        if (err)
4566                return err;
4567
4568        ipv6_hdr(skb)->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
4569        skb_set_transport_header(skb, sizeof(struct ipv6hdr));
4570
4571        return seg6_lookup_nexthop(skb, NULL, 0);
4572}
4573#endif /* CONFIG_IPV6_SEG6_BPF */
4574
4575BPF_CALL_4(bpf_lwt_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
4576           u32, len)
4577{
4578        switch (type) {
4579#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4580        case BPF_LWT_ENCAP_SEG6:
4581        case BPF_LWT_ENCAP_SEG6_INLINE:
4582                return bpf_push_seg6_encap(skb, type, hdr, len);
4583#endif
4584        default:
4585                return -EINVAL;
4586        }
4587}
4588
4589static const struct bpf_func_proto bpf_lwt_push_encap_proto = {
4590        .func           = bpf_lwt_push_encap,
4591        .gpl_only       = false,
4592        .ret_type       = RET_INTEGER,
4593        .arg1_type      = ARG_PTR_TO_CTX,
4594        .arg2_type      = ARG_ANYTHING,
4595        .arg3_type      = ARG_PTR_TO_MEM,
4596        .arg4_type      = ARG_CONST_SIZE
4597};
4598
4599#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4600BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
4601           const void *, from, u32, len)
4602{
4603        struct seg6_bpf_srh_state *srh_state =
4604                this_cpu_ptr(&seg6_bpf_srh_states);
4605        struct ipv6_sr_hdr *srh = srh_state->srh;
4606        void *srh_tlvs, *srh_end, *ptr;
4607        int srhoff = 0;
4608
4609        if (srh == NULL)
4610                return -EINVAL;
4611
4612        srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
4613        srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
4614
4615        ptr = skb->data + offset;
4616        if (ptr >= srh_tlvs && ptr + len <= srh_end)
4617                srh_state->valid = false;
4618        else if (ptr < (void *)&srh->flags ||
4619                 ptr + len > (void *)&srh->segments)
4620                return -EFAULT;
4621
4622        if (unlikely(bpf_try_make_writable(skb, offset + len)))
4623                return -EFAULT;
4624        if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
4625                return -EINVAL;
4626        srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
4627
4628        memcpy(skb->data + offset, from, len);
4629        return 0;
4630}
4631
4632static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
4633        .func           = bpf_lwt_seg6_store_bytes,
4634        .gpl_only       = false,
4635        .ret_type       = RET_INTEGER,
4636        .arg1_type      = ARG_PTR_TO_CTX,
4637        .arg2_type      = ARG_ANYTHING,
4638        .arg3_type      = ARG_PTR_TO_MEM,
4639        .arg4_type      = ARG_CONST_SIZE
4640};
4641
4642static void bpf_update_srh_state(struct sk_buff *skb)
4643{
4644        struct seg6_bpf_srh_state *srh_state =
4645                this_cpu_ptr(&seg6_bpf_srh_states);
4646        int srhoff = 0;
4647
4648        if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) {
4649                srh_state->srh = NULL;
4650        } else {
4651                srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
4652                srh_state->hdrlen = srh_state->srh->hdrlen << 3;
4653                srh_state->valid = true;
4654        }
4655}
4656
4657BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
4658           u32, action, void *, param, u32, param_len)
4659{
4660        struct seg6_bpf_srh_state *srh_state =
4661                this_cpu_ptr(&seg6_bpf_srh_states);
4662        int hdroff = 0;
4663        int err;
4664
4665        switch (action) {
4666        case SEG6_LOCAL_ACTION_END_X:
4667                if (!seg6_bpf_has_valid_srh(skb))
4668                        return -EBADMSG;
4669                if (param_len != sizeof(struct in6_addr))
4670                        return -EINVAL;
4671                return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
4672        case SEG6_LOCAL_ACTION_END_T:
4673                if (!seg6_bpf_has_valid_srh(skb))
4674                        return -EBADMSG;
4675                if (param_len != sizeof(int))
4676                        return -EINVAL;
4677                return seg6_lookup_nexthop(skb, NULL, *(int *)param);
4678        case SEG6_LOCAL_ACTION_END_DT6:
4679                if (!seg6_bpf_has_valid_srh(skb))
4680                        return -EBADMSG;
4681                if (param_len != sizeof(int))
4682                        return -EINVAL;
4683
4684                if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
4685                        return -EBADMSG;
4686                if (!pskb_pull(skb, hdroff))
4687                        return -EBADMSG;
4688
4689                skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
4690                skb_reset_network_header(skb);
4691                skb_reset_transport_header(skb);
4692                skb->encapsulation = 0;
4693
4694                bpf_compute_data_pointers(skb);
4695                bpf_update_srh_state(skb);
4696                return seg6_lookup_nexthop(skb, NULL, *(int *)param);
4697        case SEG6_LOCAL_ACTION_END_B6:
4698                if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
4699                        return -EBADMSG;
4700                err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
4701                                          param, param_len);
4702                if (!err)
4703                        bpf_update_srh_state(skb);
4704
4705                return err;
4706        case SEG6_LOCAL_ACTION_END_B6_ENCAP:
4707                if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
4708                        return -EBADMSG;
4709                err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
4710                                          param, param_len);
4711                if (!err)
4712                        bpf_update_srh_state(skb);
4713
4714                return err;
4715        default:
4716                return -EINVAL;
4717        }
4718}
4719
4720static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
4721        .func           = bpf_lwt_seg6_action,
4722        .gpl_only       = false,
4723        .ret_type       = RET_INTEGER,
4724        .arg1_type      = ARG_PTR_TO_CTX,
4725        .arg2_type      = ARG_ANYTHING,
4726        .arg3_type      = ARG_PTR_TO_MEM,
4727        .arg4_type      = ARG_CONST_SIZE
4728};
4729
4730BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
4731           s32, len)
4732{
4733        struct seg6_bpf_srh_state *srh_state =
4734                this_cpu_ptr(&seg6_bpf_srh_states);
4735        struct ipv6_sr_hdr *srh = srh_state->srh;
4736        void *srh_end, *srh_tlvs, *ptr;
4737        struct ipv6hdr *hdr;
4738        int srhoff = 0;
4739        int ret;
4740
4741        if (unlikely(srh == NULL))
4742                return -EINVAL;
4743
4744        srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
4745                        ((srh->first_segment + 1) << 4));
4746        srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
4747                        srh_state->hdrlen);
4748        ptr = skb->data + offset;
4749
4750        if (unlikely(ptr < srh_tlvs || ptr > srh_end))
4751                return -EFAULT;
4752        if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
4753                return -EFAULT;
4754
4755        if (len > 0) {
4756                ret = skb_cow_head(skb, len);
4757                if (unlikely(ret < 0))
4758                        return ret;
4759
4760                ret = bpf_skb_net_hdr_push(skb, offset, len);
4761        } else {
4762                ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
4763        }
4764
4765        bpf_compute_data_pointers(skb);
4766        if (unlikely(ret < 0))
4767                return ret;
4768
4769        hdr = (struct ipv6hdr *)skb->data;
4770        hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
4771
4772        if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
4773                return -EINVAL;
4774        srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
4775        srh_state->hdrlen += len;
4776        srh_state->valid = false;
4777        return 0;
4778}
4779
4780static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
4781        .func           = bpf_lwt_seg6_adjust_srh,
4782        .gpl_only       = false,
4783        .ret_type       = RET_INTEGER,
4784        .arg1_type      = ARG_PTR_TO_CTX,
4785        .arg2_type      = ARG_ANYTHING,
4786        .arg3_type      = ARG_ANYTHING,
4787};
4788#endif /* CONFIG_IPV6_SEG6_BPF */
4789
4790bool bpf_helper_changes_pkt_data(void *func)
4791{
4792        if (func == bpf_skb_vlan_push ||
4793            func == bpf_skb_vlan_pop ||
4794            func == bpf_skb_store_bytes ||
4795            func == bpf_skb_change_proto ||
4796            func == bpf_skb_change_head ||
4797            func == sk_skb_change_head ||
4798            func == bpf_skb_change_tail ||
4799            func == sk_skb_change_tail ||
4800            func == bpf_skb_adjust_room ||
4801            func == bpf_skb_pull_data ||
4802            func == sk_skb_pull_data ||
4803            func == bpf_clone_redirect ||
4804            func == bpf_l3_csum_replace ||
4805            func == bpf_l4_csum_replace ||
4806            func == bpf_xdp_adjust_head ||
4807            func == bpf_xdp_adjust_meta ||
4808            func == bpf_msg_pull_data ||
4809            func == bpf_xdp_adjust_tail ||
4810#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4811            func == bpf_lwt_seg6_store_bytes ||
4812            func == bpf_lwt_seg6_adjust_srh ||
4813            func == bpf_lwt_seg6_action ||
4814#endif
4815            func == bpf_lwt_push_encap)
4816                return true;
4817
4818        return false;
4819}
4820
4821static const struct bpf_func_proto *
4822bpf_base_func_proto(enum bpf_func_id func_id)
4823{
4824        switch (func_id) {
4825        case BPF_FUNC_map_lookup_elem:
4826                return &bpf_map_lookup_elem_proto;
4827        case BPF_FUNC_map_update_elem:
4828                return &bpf_map_update_elem_proto;
4829        case BPF_FUNC_map_delete_elem:
4830                return &bpf_map_delete_elem_proto;
4831        case BPF_FUNC_get_prandom_u32:
4832                return &bpf_get_prandom_u32_proto;
4833        case BPF_FUNC_get_smp_processor_id:
4834                return &bpf_get_raw_smp_processor_id_proto;
4835        case BPF_FUNC_get_numa_node_id:
4836                return &bpf_get_numa_node_id_proto;
4837        case BPF_FUNC_tail_call:
4838                return &bpf_tail_call_proto;
4839        case BPF_FUNC_ktime_get_ns:
4840                return &bpf_ktime_get_ns_proto;
4841        case BPF_FUNC_trace_printk:
4842                if (capable(CAP_SYS_ADMIN))
4843                        return bpf_get_trace_printk_proto();
4844                /* else: fall through */
4845        default:
4846                return NULL;
4847        }
4848}
4849
4850static const struct bpf_func_proto *
4851sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
4852{
4853        switch (func_id) {
4854        /* inet and inet6 sockets are created in a process
4855         * context so there is always a valid uid/gid
4856         */
4857        case BPF_FUNC_get_current_uid_gid:
4858                return &bpf_get_current_uid_gid_proto;
4859        case BPF_FUNC_get_local_storage:
4860                return &bpf_get_local_storage_proto;
4861        default:
4862                return bpf_base_func_proto(func_id);
4863        }
4864}
4865
4866static const struct bpf_func_proto *
4867sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
4868{
4869        switch (func_id) {
4870        /* inet and inet6 sockets are created in a process
4871         * context so there is always a valid uid/gid
4872         */
4873        case BPF_FUNC_get_current_uid_gid:
4874                return &bpf_get_current_uid_gid_proto;
4875        case BPF_FUNC_bind:
4876                switch (prog->expected_attach_type) {
4877                case BPF_CGROUP_INET4_CONNECT:
4878                case BPF_CGROUP_INET6_CONNECT:
4879                        return &bpf_bind_proto;
4880                default:
4881                        return NULL;
4882                }
4883        case BPF_FUNC_get_socket_cookie:
4884                return &bpf_get_socket_cookie_sock_addr_proto;
4885        case BPF_FUNC_get_local_storage:
4886                return &bpf_get_local_storage_proto;
4887        default:
4888                return bpf_base_func_proto(func_id);
4889        }
4890}
4891
4892static const struct bpf_func_proto *
4893sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
4894{
4895        switch (func_id) {
4896        case BPF_FUNC_skb_load_bytes:
4897                return &bpf_skb_load_bytes_proto;
4898        case BPF_FUNC_skb_load_bytes_relative:
4899                return &bpf_skb_load_bytes_relative_proto;
4900        case BPF_FUNC_get_socket_cookie:
4901                return &bpf_get_socket_cookie_proto;
4902        case BPF_FUNC_get_socket_uid:
4903                return &bpf_get_socket_uid_proto;
4904        default:
4905                return bpf_base_func_proto(func_id);
4906        }
4907}
4908
4909static const struct bpf_func_proto *
4910cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
4911{
4912        switch (func_id) {
4913        case BPF_FUNC_get_local_storage:
4914                return &bpf_get_local_storage_proto;
4915        default:
4916                return sk_filter_func_proto(func_id, prog);
4917        }
4918}
4919
4920static const struct bpf_func_proto *
4921tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
4922{
4923        switch (func_id) {
4924        case BPF_FUNC_skb_store_bytes:
4925                return &bpf_skb_store_bytes_proto;
4926        case BPF_FUNC_skb_load_bytes:
4927                return &bpf_skb_load_bytes_proto;
4928        case BPF_FUNC_skb_load_bytes_relative:
4929                return &bpf_skb_load_bytes_relative_proto;
4930        case BPF_FUNC_skb_pull_data:
4931                return &bpf_skb_pull_data_proto;
4932        case BPF_FUNC_csum_diff:
4933                return &bpf_csum_diff_proto;
4934        case BPF_FUNC_csum_update:
4935                return &bpf_csum_update_proto;
4936        case BPF_FUNC_l3_csum_replace:
4937                return &bpf_l3_csum_replace_proto;
4938        case BPF_FUNC_l4_csum_replace:
4939                return &bpf_l4_csum_replace_proto;
4940        case BPF_FUNC_clone_redirect:
4941                return &bpf_clone_redirect_proto;
4942        case BPF_FUNC_get_cgroup_classid:
4943                return &bpf_get_cgroup_classid_proto;
4944        case BPF_FUNC_skb_vlan_push:
4945                return &bpf_skb_vlan_push_proto;
4946        case BPF_FUNC_skb_vlan_pop:
4947                return &bpf_skb_vlan_pop_proto;
4948        case BPF_FUNC_skb_change_proto:
4949                return &bpf_skb_change_proto_proto;
4950        case BPF_FUNC_skb_change_type:
4951                return &bpf_skb_change_type_proto;
4952        case BPF_FUNC_skb_adjust_room:
4953                return &bpf_skb_adjust_room_proto;
4954        case BPF_FUNC_skb_change_tail:
4955                return &bpf_skb_change_tail_proto;
4956        case BPF_FUNC_skb_get_tunnel_key:
4957                return &bpf_skb_get_tunnel_key_proto;
4958        case BPF_FUNC_skb_set_tunnel_key:
4959                return bpf_get_skb_set_tunnel_proto(func_id);
4960        case BPF_FUNC_skb_get_tunnel_opt:
4961                return &bpf_skb_get_tunnel_opt_proto;
4962        case BPF_FUNC_skb_set_tunnel_opt:
4963                return bpf_get_skb_set_tunnel_proto(func_id);
4964        case BPF_FUNC_redirect:
4965                return &bpf_redirect_proto;
4966        case BPF_FUNC_get_route_realm:
4967                return &bpf_get_route_realm_proto;
4968        case BPF_FUNC_get_hash_recalc:
4969                return &bpf_get_hash_recalc_proto;
4970        case BPF_FUNC_set_hash_invalid:
4971                return &bpf_set_hash_invalid_proto;
4972        case BPF_FUNC_set_hash:
4973                return &bpf_set_hash_proto;
4974        case BPF_FUNC_perf_event_output:
4975                return &bpf_skb_event_output_proto;
4976        case BPF_FUNC_get_smp_processor_id:
4977                return &bpf_get_smp_processor_id_proto;
4978        case BPF_FUNC_skb_under_cgroup:
4979                return &bpf_skb_under_cgroup_proto;
4980        case BPF_FUNC_get_socket_cookie:
4981                return &bpf_get_socket_cookie_proto;
4982        case BPF_FUNC_get_socket_uid:
4983                return &bpf_get_socket_uid_proto;
4984        case BPF_FUNC_fib_lookup:
4985                return &bpf_skb_fib_lookup_proto;
4986#ifdef CONFIG_XFRM
4987        case BPF_FUNC_skb_get_xfrm_state:
4988                return &bpf_skb_get_xfrm_state_proto;
4989#endif
4990#ifdef CONFIG_SOCK_CGROUP_DATA
4991        case BPF_FUNC_skb_cgroup_id:
4992                return &bpf_skb_cgroup_id_proto;
4993        case BPF_FUNC_skb_ancestor_cgroup_id:
4994                return &bpf_skb_ancestor_cgroup_id_proto;
4995#endif
4996        default:
4997                return bpf_base_func_proto(func_id);
4998        }
4999}
5000
5001static const struct bpf_func_proto *
5002xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5003{
5004        switch (func_id) {
5005        case BPF_FUNC_perf_event_output:
5006                return &bpf_xdp_event_output_proto;
5007        case BPF_FUNC_get_smp_processor_id:
5008                return &bpf_get_smp_processor_id_proto;
5009        case BPF_FUNC_csum_diff:
5010                return &bpf_csum_diff_proto;
5011        case BPF_FUNC_xdp_adjust_head:
5012                return &bpf_xdp_adjust_head_proto;
5013        case BPF_FUNC_xdp_adjust_meta:
5014                return &bpf_xdp_adjust_meta_proto;
5015        case BPF_FUNC_redirect:
5016                return &bpf_xdp_redirect_proto;
5017        case BPF_FUNC_redirect_map:
5018                return &bpf_xdp_redirect_map_proto;
5019        case BPF_FUNC_xdp_adjust_tail:
5020                return &bpf_xdp_adjust_tail_proto;
5021        case BPF_FUNC_fib_lookup:
5022                return &bpf_xdp_fib_lookup_proto;
5023        default:
5024                return bpf_base_func_proto(func_id);
5025        }
5026}
5027
5028static const struct bpf_func_proto *
5029sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5030{
5031        switch (func_id) {
5032        case BPF_FUNC_setsockopt:
5033                return &bpf_setsockopt_proto;
5034        case BPF_FUNC_getsockopt:
5035                return &bpf_getsockopt_proto;
5036        case BPF_FUNC_sock_ops_cb_flags_set:
5037                return &bpf_sock_ops_cb_flags_set_proto;
5038        case BPF_FUNC_sock_map_update:
5039                return &bpf_sock_map_update_proto;
5040        case BPF_FUNC_sock_hash_update:
5041                return &bpf_sock_hash_update_proto;
5042        case BPF_FUNC_get_socket_cookie:
5043                return &bpf_get_socket_cookie_sock_ops_proto;
5044        case BPF_FUNC_get_local_storage:
5045                return &bpf_get_local_storage_proto;
5046        default:
5047                return bpf_base_func_proto(func_id);
5048        }
5049}
5050
5051static const struct bpf_func_proto *
5052sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5053{
5054        switch (func_id) {
5055        case BPF_FUNC_msg_redirect_map:
5056                return &bpf_msg_redirect_map_proto;
5057        case BPF_FUNC_msg_redirect_hash:
5058                return &bpf_msg_redirect_hash_proto;
5059        case BPF_FUNC_msg_apply_bytes:
5060                return &bpf_msg_apply_bytes_proto;
5061        case BPF_FUNC_msg_cork_bytes:
5062                return &bpf_msg_cork_bytes_proto;
5063        case BPF_FUNC_msg_pull_data:
5064                return &bpf_msg_pull_data_proto;
5065        case BPF_FUNC_get_local_storage:
5066                return &bpf_get_local_storage_proto;
5067        default:
5068                return bpf_base_func_proto(func_id);
5069        }
5070}
5071
5072static const struct bpf_func_proto *
5073sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5074{
5075        switch (func_id) {
5076        case BPF_FUNC_skb_store_bytes:
5077                return &bpf_skb_store_bytes_proto;
5078        case BPF_FUNC_skb_load_bytes:
5079                return &bpf_skb_load_bytes_proto;
5080        case BPF_FUNC_skb_pull_data:
5081                return &sk_skb_pull_data_proto;
5082        case BPF_FUNC_skb_change_tail:
5083                return &sk_skb_change_tail_proto;
5084        case BPF_FUNC_skb_change_head:
5085                return &sk_skb_change_head_proto;
5086        case BPF_FUNC_get_socket_cookie:
5087                return &bpf_get_socket_cookie_proto;
5088        case BPF_FUNC_get_socket_uid:
5089                return &bpf_get_socket_uid_proto;
5090        case BPF_FUNC_sk_redirect_map:
5091                return &bpf_sk_redirect_map_proto;
5092        case BPF_FUNC_sk_redirect_hash:
5093                return &bpf_sk_redirect_hash_proto;
5094        case BPF_FUNC_get_local_storage:
5095                return &bpf_get_local_storage_proto;
5096        default:
5097                return bpf_base_func_proto(func_id);
5098        }
5099}
5100
5101static const struct bpf_func_proto *
5102lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5103{
5104        switch (func_id) {
5105        case BPF_FUNC_skb_load_bytes:
5106                return &bpf_skb_load_bytes_proto;
5107        case BPF_FUNC_skb_pull_data:
5108                return &bpf_skb_pull_data_proto;
5109        case BPF_FUNC_csum_diff:
5110                return &bpf_csum_diff_proto;
5111        case BPF_FUNC_get_cgroup_classid:
5112                return &bpf_get_cgroup_classid_proto;
5113        case BPF_FUNC_get_route_realm:
5114                return &bpf_get_route_realm_proto;
5115        case BPF_FUNC_get_hash_recalc:
5116                return &bpf_get_hash_recalc_proto;
5117        case BPF_FUNC_perf_event_output:
5118                return &bpf_skb_event_output_proto;
5119        case BPF_FUNC_get_smp_processor_id:
5120                return &bpf_get_smp_processor_id_proto;
5121        case BPF_FUNC_skb_under_cgroup:
5122                return &bpf_skb_under_cgroup_proto;
5123        default:
5124                return bpf_base_func_proto(func_id);
5125        }
5126}
5127
5128static const struct bpf_func_proto *
5129lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5130{
5131        switch (func_id) {
5132        case BPF_FUNC_lwt_push_encap:
5133                return &bpf_lwt_push_encap_proto;
5134        default:
5135                return lwt_out_func_proto(func_id, prog);
5136        }
5137}
5138
5139static const struct bpf_func_proto *
5140lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5141{
5142        switch (func_id) {
5143        case BPF_FUNC_skb_get_tunnel_key:
5144                return &bpf_skb_get_tunnel_key_proto;
5145        case BPF_FUNC_skb_set_tunnel_key:
5146                return bpf_get_skb_set_tunnel_proto(func_id);
5147        case BPF_FUNC_skb_get_tunnel_opt:
5148                return &bpf_skb_get_tunnel_opt_proto;
5149        case BPF_FUNC_skb_set_tunnel_opt:
5150                return bpf_get_skb_set_tunnel_proto(func_id);
5151        case BPF_FUNC_redirect:
5152                return &bpf_redirect_proto;
5153        case BPF_FUNC_clone_redirect:
5154                return &bpf_clone_redirect_proto;
5155        case BPF_FUNC_skb_change_tail:
5156                return &bpf_skb_change_tail_proto;
5157        case BPF_FUNC_skb_change_head:
5158                return &bpf_skb_change_head_proto;
5159        case BPF_FUNC_skb_store_bytes:
5160                return &bpf_skb_store_bytes_proto;
5161        case BPF_FUNC_csum_update:
5162                return &bpf_csum_update_proto;
5163        case BPF_FUNC_l3_csum_replace:
5164                return &bpf_l3_csum_replace_proto;
5165        case BPF_FUNC_l4_csum_replace:
5166                return &bpf_l4_csum_replace_proto;
5167        case BPF_FUNC_set_hash_invalid:
5168                return &bpf_set_hash_invalid_proto;
5169        default:
5170                return lwt_out_func_proto(func_id, prog);
5171        }
5172}
5173
5174static const struct bpf_func_proto *
5175lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5176{
5177        switch (func_id) {
5178#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
5179        case BPF_FUNC_lwt_seg6_store_bytes:
5180                return &bpf_lwt_seg6_store_bytes_proto;
5181        case BPF_FUNC_lwt_seg6_action:
5182                return &bpf_lwt_seg6_action_proto;
5183        case BPF_FUNC_lwt_seg6_adjust_srh:
5184                return &bpf_lwt_seg6_adjust_srh_proto;
5185#endif
5186        default:
5187                return lwt_out_func_proto(func_id, prog);
5188        }
5189}
5190
5191static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
5192                                    const struct bpf_prog *prog,
5193                                    struct bpf_insn_access_aux *info)
5194{
5195        const int size_default = sizeof(__u32);
5196
5197        if (off < 0 || off >= sizeof(struct __sk_buff))
5198                return false;
5199
5200        /* The verifier guarantees that size > 0. */
5201        if (off % size != 0)
5202                return false;
5203
5204        switch (off) {
5205        case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5206                if (off + size > offsetofend(struct __sk_buff, cb[4]))
5207                        return false;
5208                break;
5209        case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
5210        case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
5211        case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
5212        case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
5213        case bpf_ctx_range(struct __sk_buff, data):
5214        case bpf_ctx_range(struct __sk_buff, data_meta):
5215        case bpf_ctx_range(struct __sk_buff, data_end):
5216                if (size != size_default)
5217                        return false;
5218                break;
5219        default:
5220                /* Only narrow read access allowed for now. */
5221                if (type == BPF_WRITE) {
5222                        if (size != size_default)
5223                                return false;
5224                } else {
5225                        bpf_ctx_record_field_size(info, size_default);
5226                        if (!bpf_ctx_narrow_access_ok(off, size, size_default))
5227                                return false;
5228                }
5229        }
5230
5231        return true;
5232}
5233
5234static bool sk_filter_is_valid_access(int off, int size,
5235                                      enum bpf_access_type type,
5236                                      const struct bpf_prog *prog,
5237                                      struct bpf_insn_access_aux *info)
5238{
5239        switch (off) {
5240        case bpf_ctx_range(struct __sk_buff, tc_classid):
5241        case bpf_ctx_range(struct __sk_buff, data):
5242        case bpf_ctx_range(struct __sk_buff, data_meta):
5243        case bpf_ctx_range(struct __sk_buff, data_end):
5244        case bpf_ctx_range_till(struct __sk_buff, family, local_port):
5245                return false;
5246        }
5247
5248        if (type == BPF_WRITE) {
5249                switch (off) {
5250                case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5251                        break;
5252                default:
5253                        return false;
5254                }
5255        }
5256
5257        return bpf_skb_is_valid_access(off, size, type, prog, info);
5258}
5259
5260static bool lwt_is_valid_access(int off, int size,
5261                                enum bpf_access_type type,
5262                                const struct bpf_prog *prog,
5263                                struct bpf_insn_access_aux *info)
5264{
5265        switch (off) {
5266        case bpf_ctx_range(struct __sk_buff, tc_classid):
5267        case bpf_ctx_range_till(struct __sk_buff, family, local_port):
5268        case bpf_ctx_range(struct __sk_buff, data_meta):
5269                return false;
5270        }
5271
5272        if (type == BPF_WRITE) {
5273                switch (off) {
5274                case bpf_ctx_range(struct __sk_buff, mark):
5275                case bpf_ctx_range(struct __sk_buff, priority):
5276                case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5277                        break;
5278                default:
5279                        return false;
5280                }
5281        }
5282
5283        switch (off) {
5284        case bpf_ctx_range(struct __sk_buff, data):
5285                info->reg_type = PTR_TO_PACKET;
5286                break;
5287        case bpf_ctx_range(struct __sk_buff, data_end):
5288                info->reg_type = PTR_TO_PACKET_END;
5289                break;
5290        }
5291
5292        return bpf_skb_is_valid_access(off, size, type, prog, info);
5293}
5294
5295/* Attach type specific accesses */
5296static bool __sock_filter_check_attach_type(int off,
5297                                            enum bpf_access_type access_type,
5298                                            enum bpf_attach_type attach_type)
5299{
5300        switch (off) {
5301        case offsetof(struct bpf_sock, bound_dev_if):
5302        case offsetof(struct bpf_sock, mark):
5303        case offsetof(struct bpf_sock, priority):
5304                switch (attach_type) {
5305                case BPF_CGROUP_INET_SOCK_CREATE:
5306                        goto full_access;
5307                default:
5308                        return false;
5309                }
5310        case bpf_ctx_range(struct bpf_sock, src_ip4):
5311                switch (attach_type) {
5312                case BPF_CGROUP_INET4_POST_BIND:
5313                        goto read_only;
5314                default:
5315                        return false;
5316                }
5317        case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
5318                switch (attach_type) {
5319                case BPF_CGROUP_INET6_POST_BIND:
5320                        goto read_only;
5321                default:
5322                        return false;
5323                }
5324        case bpf_ctx_range(struct bpf_sock, src_port):
5325                switch (attach_type) {
5326                case BPF_CGROUP_INET4_POST_BIND:
5327                case BPF_CGROUP_INET6_POST_BIND:
5328                        goto read_only;
5329                default:
5330                        return false;
5331                }
5332        }
5333read_only:
5334        return access_type == BPF_READ;
5335full_access:
5336        return true;
5337}
5338
5339static bool __sock_filter_check_size(int off, int size,
5340                                     struct bpf_insn_access_aux *info)
5341{
5342        const int size_default = sizeof(__u32);
5343
5344        switch (off) {
5345        case bpf_ctx_range(struct bpf_sock, src_ip4):
5346        case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
5347                bpf_ctx_record_field_size(info, size_default);
5348                return bpf_ctx_narrow_access_ok(off, size, size_default);
5349        }
5350
5351        return size == size_default;
5352}
5353
5354static bool sock_filter_is_valid_access(int off, int size,
5355                                        enum bpf_access_type type,
5356                                        const struct bpf_prog *prog,
5357                                        struct bpf_insn_access_aux *info)
5358{
5359        if (off < 0 || off >= sizeof(struct bpf_sock))
5360                return false;
5361        if (off % size != 0)
5362                return false;
5363        if (!__sock_filter_check_attach_type(off, type,
5364                                             prog->expected_attach_type))
5365                return false;
5366        if (!__sock_filter_check_size(off, size, info))
5367                return false;
5368        return true;
5369}
5370
5371static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
5372                                const struct bpf_prog *prog, int drop_verdict)
5373{
5374        struct bpf_insn *insn = insn_buf;
5375
5376        if (!direct_write)
5377                return 0;
5378
5379        /* if (!skb->cloned)
5380         *       goto start;
5381         *
5382         * (Fast-path, otherwise approximation that we might be
5383         *  a clone, do the rest in helper.)
5384         */
5385        *insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET());
5386        *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
5387        *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
5388
5389        /* ret = bpf_skb_pull_data(skb, 0); */
5390        *insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
5391        *insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
5392        *insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
5393                               BPF_FUNC_skb_pull_data);
5394        /* if (!ret)
5395         *      goto restore;
5396         * return TC_ACT_SHOT;
5397         */
5398        *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
5399        *insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
5400        *insn++ = BPF_EXIT_INSN();
5401
5402        /* restore: */
5403        *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
5404        /* start: */
5405        *insn++ = prog->insnsi[0];
5406
5407        return insn - insn_buf;
5408}
5409
5410static int bpf_gen_ld_abs(const struct bpf_insn *orig,
5411                          struct bpf_insn *insn_buf)
5412{
5413        bool indirect = BPF_MODE(orig->code) == BPF_IND;
5414        struct bpf_insn *insn = insn_buf;
5415
5416        /* We're guaranteed here that CTX is in R6. */
5417        *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
5418        if (!indirect) {
5419                *insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
5420        } else {
5421                *insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
5422                if (orig->imm)
5423                        *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
5424        }
5425
5426        switch (BPF_SIZE(orig->code)) {
5427        case BPF_B:
5428                *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
5429                break;
5430        case BPF_H:
5431                *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
5432                break;
5433        case BPF_W:
5434                *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
5435                break;
5436        }
5437
5438        *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
5439        *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
5440        *insn++ = BPF_EXIT_INSN();
5441
5442        return insn - insn_buf;
5443}
5444
5445static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
5446                               const struct bpf_prog *prog)
5447{
5448        return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
5449}
5450
5451static bool tc_cls_act_is_valid_access(int off, int size,
5452                                       enum bpf_access_type type,
5453                                       const struct bpf_prog *prog,
5454                                       struct bpf_insn_access_aux *info)
5455{
5456        if (type == BPF_WRITE) {
5457                switch (off) {
5458                case bpf_ctx_range(struct __sk_buff, mark):
5459                case bpf_ctx_range(struct __sk_buff, tc_index):
5460                case bpf_ctx_range(struct __sk_buff, priority):
5461                case bpf_ctx_range(struct __sk_buff, tc_classid):
5462                case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5463                        break;
5464                default:
5465                        return false;
5466                }
5467        }
5468
5469        switch (off) {
5470        case bpf_ctx_range(struct __sk_buff, data):
5471                info->reg_type = PTR_TO_PACKET;
5472                break;
5473        case bpf_ctx_range(struct __sk_buff, data_meta):
5474                info->reg_type = PTR_TO_PACKET_META;
5475                break;
5476        case bpf_ctx_range(struct __sk_buff, data_end):
5477                info->reg_type = PTR_TO_PACKET_END;
5478                break;
5479        case bpf_ctx_range_till(struct __sk_buff, family, local_port):
5480                return false;
5481        }
5482
5483        return bpf_skb_is_valid_access(off, size, type, prog, info);
5484}
5485
5486static bool __is_valid_xdp_access(int off, int size)
5487{
5488        if (off < 0 || off >= sizeof(struct xdp_md))
5489                return false;
5490        if (off % size != 0)
5491                return false;
5492        if (size != sizeof(__u32))
5493                return false;
5494
5495        return true;
5496}
5497
5498static bool xdp_is_valid_access(int off, int size,
5499                                enum bpf_access_type type,
5500                                const struct bpf_prog *prog,
5501                                struct bpf_insn_access_aux *info)
5502{
5503        if (type == BPF_WRITE) {
5504                if (bpf_prog_is_dev_bound(prog->aux)) {
5505                        switch (off) {
5506                        case offsetof(struct xdp_md, rx_queue_index):
5507                                return __is_valid_xdp_access(off, size);
5508                        }
5509                }
5510                return false;
5511        }
5512
5513        switch (off) {
5514        case offsetof(struct xdp_md, data):
5515                info->reg_type = PTR_TO_PACKET;
5516                break;
5517        case offsetof(struct xdp_md, data_meta):
5518                info->reg_type = PTR_TO_PACKET_META;
5519                break;
5520        case offsetof(struct xdp_md, data_end):
5521                info->reg_type = PTR_TO_PACKET_END;
5522                break;
5523        }
5524
5525        return __is_valid_xdp_access(off, size);
5526}
5527
5528void bpf_warn_invalid_xdp_action(u32 act)
5529{
5530        const u32 act_max = XDP_REDIRECT;
5531
5532        WARN_ONCE(1, "%s XDP return value %u, expect packet loss!\n",
5533                  act > act_max ? "Illegal" : "Driver unsupported",
5534                  act);
5535}
5536EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
5537
5538static bool sock_addr_is_valid_access(int off, int size,
5539                                      enum bpf_access_type type,
5540                                      const struct bpf_prog *prog,
5541                                      struct bpf_insn_access_aux *info)
5542{
5543        const int size_default = sizeof(__u32);
5544
5545        if (off < 0 || off >= sizeof(struct bpf_sock_addr))
5546                return false;
5547        if (off % size != 0)
5548                return false;
5549
5550        /* Disallow access to IPv6 fields from IPv4 contex and vise
5551         * versa.
5552         */
5553        switch (off) {
5554        case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
5555                switch (prog->expected_attach_type) {
5556                case BPF_CGROUP_INET4_BIND:
5557                case BPF_CGROUP_INET4_CONNECT:
5558                case BPF_CGROUP_UDP4_SENDMSG:
5559                        break;
5560                default:
5561                        return false;
5562                }
5563                break;
5564        case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
5565                switch (prog->expected_attach_type) {
5566                case BPF_CGROUP_INET6_BIND:
5567                case BPF_CGROUP_INET6_CONNECT:
5568                case BPF_CGROUP_UDP6_SENDMSG:
5569                        break;
5570                default:
5571                        return false;
5572                }
5573                break;
5574        case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
5575                switch (prog->expected_attach_type) {
5576                case BPF_CGROUP_UDP4_SENDMSG:
5577                        break;
5578                default:
5579                        return false;
5580                }
5581                break;
5582        case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
5583                                msg_src_ip6[3]):
5584                switch (prog->expected_attach_type) {
5585                case BPF_CGROUP_UDP6_SENDMSG:
5586                        break;
5587                default:
5588                        return false;
5589                }
5590                break;
5591        }
5592
5593        switch (off) {
5594        case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
5595        case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
5596        case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
5597        case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
5598                                msg_src_ip6[3]):
5599                /* Only narrow read access allowed for now. */
5600                if (type == BPF_READ) {
5601                        bpf_ctx_record_field_size(info, size_default);
5602                        if (!bpf_ctx_narrow_access_ok(off, size, size_default))
5603                                return false;
5604                } else {
5605                        if (size != size_default)
5606                                return false;
5607                }
5608                break;
5609        case bpf_ctx_range(struct bpf_sock_addr, user_port):
5610                if (size != size_default)
5611                        return false;
5612                break;
5613        default:
5614                if (type == BPF_READ) {
5615                        if (size != size_default)
5616                                return false;
5617                } else {
5618                        return false;
5619                }
5620        }
5621
5622        return true;
5623}
5624
5625static bool sock_ops_is_valid_access(int off, int size,
5626                                     enum bpf_access_type type,
5627                                     const struct bpf_prog *prog,
5628                                     struct bpf_insn_access_aux *info)
5629{
5630        const int size_default = sizeof(__u32);
5631
5632        if (off < 0 || off >= sizeof(struct bpf_sock_ops))
5633                return false;
5634
5635        /* The verifier guarantees that size > 0. */
5636        if (off % size != 0)
5637                return false;
5638
5639        if (type == BPF_WRITE) {
5640                switch (off) {
5641                case offsetof(struct bpf_sock_ops, reply):
5642                case offsetof(struct bpf_sock_ops, sk_txhash):
5643                        if (size != size_default)
5644                                return false;
5645                        break;
5646                default:
5647                        return false;
5648                }
5649        } else {
5650                switch (off) {
5651                case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received,
5652                                        bytes_acked):
5653                        if (size != sizeof(__u64))
5654                                return false;
5655                        break;
5656                default:
5657                        if (size != size_default)
5658                                return false;
5659                        break;
5660                }
5661        }
5662
5663        return true;
5664}
5665
5666static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
5667                           const struct bpf_prog *prog)
5668{
5669        return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
5670}
5671
5672static bool sk_skb_is_valid_access(int off, int size,
5673                                   enum bpf_access_type type,
5674                                   const struct bpf_prog *prog,
5675                                   struct bpf_insn_access_aux *info)
5676{
5677        switch (off) {
5678        case bpf_ctx_range(struct __sk_buff, tc_classid):
5679        case bpf_ctx_range(struct __sk_buff, data_meta):
5680                return false;
5681        }
5682
5683        if (type == BPF_WRITE) {
5684                switch (off) {
5685                case bpf_ctx_range(struct __sk_buff, tc_index):
5686                case bpf_ctx_range(struct __sk_buff, priority):
5687                        break;
5688                default:
5689                        return false;
5690                }
5691        }
5692
5693        switch (off) {
5694        case bpf_ctx_range(struct __sk_buff, mark):
5695                return false;
5696        case bpf_ctx_range(struct __sk_buff, data):
5697                info->reg_type = PTR_TO_PACKET;
5698                break;
5699        case bpf_ctx_range(struct __sk_buff, data_end):
5700                info->reg_type = PTR_TO_PACKET_END;
5701                break;
5702        }
5703
5704        return bpf_skb_is_valid_access(off, size, type, prog, info);
5705}
5706
5707static bool sk_msg_is_valid_access(int off, int size,
5708                                   enum bpf_access_type type,
5709                                   const struct bpf_prog *prog,
5710                                   struct bpf_insn_access_aux *info)
5711{
5712        if (type == BPF_WRITE)
5713                return false;
5714
5715        switch (off) {
5716        case offsetof(struct sk_msg_md, data):
5717                info->reg_type = PTR_TO_PACKET;
5718                if (size != sizeof(__u64))
5719                        return false;
5720                break;
5721        case offsetof(struct sk_msg_md, data_end):
5722                info->reg_type = PTR_TO_PACKET_END;
5723                if (size != sizeof(__u64))
5724                        return false;
5725                break;
5726        default:
5727                if (size != sizeof(__u32))
5728                        return false;
5729        }
5730
5731        if (off < 0 || off >= sizeof(struct sk_msg_md))
5732                return false;
5733        if (off % size != 0)
5734                return false;
5735
5736        return true;
5737}
5738
5739static u32 bpf_convert_ctx_access(enum bpf_access_type type,
5740                                  const struct bpf_insn *si,
5741                                  struct bpf_insn *insn_buf,
5742                                  struct bpf_prog *prog, u32 *target_size)
5743{
5744        struct bpf_insn *insn = insn_buf;
5745        int off;
5746
5747        switch (si->off) {
5748        case offsetof(struct __sk_buff, len):
5749                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5750                                      bpf_target_off(struct sk_buff, len, 4,
5751                                                     target_size));
5752                break;
5753
5754        case offsetof(struct __sk_buff, protocol):
5755                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
5756                                      bpf_target_off(struct sk_buff, protocol, 2,
5757                                                     target_size));
5758                break;
5759
5760        case offsetof(struct __sk_buff, vlan_proto):
5761                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
5762                                      bpf_target_off(struct sk_buff, vlan_proto, 2,
5763                                                     target_size));
5764                break;
5765
5766        case offsetof(struct __sk_buff, priority):
5767                if (type == BPF_WRITE)
5768                        *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
5769                                              bpf_target_off(struct sk_buff, priority, 4,
5770                                                             target_size));
5771                else
5772                        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5773                                              bpf_target_off(struct sk_buff, priority, 4,
5774                                                             target_size));
5775                break;
5776
5777        case offsetof(struct __sk_buff, ingress_ifindex):
5778                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5779                                      bpf_target_off(struct sk_buff, skb_iif, 4,
5780                                                     target_size));
5781                break;
5782
5783        case offsetof(struct __sk_buff, ifindex):
5784                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
5785                                      si->dst_reg, si->src_reg,
5786                                      offsetof(struct sk_buff, dev));
5787                *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
5788                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
5789                                      bpf_target_off(struct net_device, ifindex, 4,
5790                                                     target_size));
5791                break;
5792
5793        case offsetof(struct __sk_buff, hash):
5794                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5795                                      bpf_target_off(struct sk_buff, hash, 4,
5796                                                     target_size));
5797                break;
5798
5799        case offsetof(struct __sk_buff, mark):
5800                if (type == BPF_WRITE)
5801                        *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
5802                                              bpf_target_off(struct sk_buff, mark, 4,
5803                                                             target_size));
5804                else
5805                        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5806                                              bpf_target_off(struct sk_buff, mark, 4,
5807                                                             target_size));
5808                break;
5809
5810        case offsetof(struct __sk_buff, pkt_type):
5811                *target_size = 1;
5812                *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
5813                                      PKT_TYPE_OFFSET());
5814                *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
5815#ifdef __BIG_ENDIAN_BITFIELD
5816                *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
5817#endif
5818                break;
5819
5820        case offsetof(struct __sk_buff, queue_mapping):
5821                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
5822                                      bpf_target_off(struct sk_buff, queue_mapping, 2,
5823                                                     target_size));
5824                break;
5825
5826        case offsetof(struct __sk_buff, vlan_present):
5827        case offsetof(struct __sk_buff, vlan_tci):
5828                BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);
5829
5830                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
5831                                      bpf_target_off(struct sk_buff, vlan_tci, 2,
5832                                                     target_size));
5833                if (si->off == offsetof(struct __sk_buff, vlan_tci)) {
5834                        *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg,
5835                                                ~VLAN_TAG_PRESENT);
5836                } else {
5837                        *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 12);
5838                        *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1);
5839                }
5840                break;
5841
5842        case offsetof(struct __sk_buff, cb[0]) ...
5843             offsetofend(struct __sk_buff, cb[4]) - 1:
5844                BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);
5845                BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
5846                              offsetof(struct qdisc_skb_cb, data)) %
5847                             sizeof(__u64));
5848
5849                prog->cb_access = 1;
5850                off  = si->off;
5851                off -= offsetof(struct __sk_buff, cb[0]);
5852                off += offsetof(struct sk_buff, cb);
5853                off += offsetof(struct qdisc_skb_cb, data);
5854                if (type == BPF_WRITE)
5855                        *insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
5856                                              si->src_reg, off);
5857                else
5858                        *insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
5859                                              si->src_reg, off);
5860                break;
5861
5862        case offsetof(struct __sk_buff, tc_classid):
5863                BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, tc_classid) != 2);
5864
5865                off  = si->off;
5866                off -= offsetof(struct __sk_buff, tc_classid);
5867                off += offsetof(struct sk_buff, cb);
5868                off += offsetof(struct qdisc_skb_cb, tc_classid);
5869                *target_size = 2;
5870                if (type == BPF_WRITE)
5871                        *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg,
5872                                              si->src_reg, off);
5873                else
5874                        *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
5875                                              si->src_reg, off);
5876                break;
5877
5878        case offsetof(struct __sk_buff, data):
5879                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
5880                                      si->dst_reg, si->src_reg,
5881                                      offsetof(struct sk_buff, data));
5882                break;
5883
5884        case offsetof(struct __sk_buff, data_meta):
5885                off  = si->off;
5886                off -= offsetof(struct __sk_buff, data_meta);
5887                off += offsetof(struct sk_buff, cb);
5888                off += offsetof(struct bpf_skb_data_end, data_meta);
5889                *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
5890                                      si->src_reg, off);
5891                break;
5892
5893        case offsetof(struct __sk_buff, data_end):
5894                off  = si->off;
5895                off -= offsetof(struct __sk_buff, data_end);
5896                off += offsetof(struct sk_buff, cb);
5897                off += offsetof(struct bpf_skb_data_end, data_end);
5898                *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
5899                                      si->src_reg, off);
5900                break;
5901
5902        case offsetof(struct __sk_buff, tc_index):
5903#ifdef CONFIG_NET_SCHED
5904                if (type == BPF_WRITE)
5905                        *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
5906                                              bpf_target_off(struct sk_buff, tc_index, 2,
5907                                                             target_size));
5908                else
5909                        *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
5910                                              bpf_target_off(struct sk_buff, tc_index, 2,
5911                                                             target_size));
5912#else
5913                *target_size = 2;
5914                if (type == BPF_WRITE)
5915                        *insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
5916                else
5917                        *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
5918#endif
5919                break;
5920
5921        case offsetof(struct __sk_buff, napi_id):
5922#if defined(CONFIG_NET_RX_BUSY_POLL)
5923                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5924                                      bpf_target_off(struct sk_buff, napi_id, 4,
5925                                                     target_size));
5926                *insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
5927                *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
5928#else
5929                *target_size = 4;
5930                *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
5931#endif
5932                break;
5933        case offsetof(struct __sk_buff, family):
5934                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
5935
5936                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
5937                                      si->dst_reg, si->src_reg,
5938                                      offsetof(struct sk_buff, sk));
5939                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
5940                                      bpf_target_off(struct sock_common,
5941                                                     skc_family,
5942                                                     2, target_size));
5943                break;
5944        case offsetof(struct __sk_buff, remote_ip4):
5945                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
5946
5947                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
5948                                      si->dst_reg, si->src_reg,
5949                                      offsetof(struct sk_buff, sk));
5950                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
5951                                      bpf_target_off(struct sock_common,
5952                                                     skc_daddr,
5953                                                     4, target_size));
5954                break;
5955        case offsetof(struct __sk_buff, local_ip4):
5956                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
5957                                          skc_rcv_saddr) != 4);
5958
5959                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
5960                                      si->dst_reg, si->src_reg,
5961                                      offsetof(struct sk_buff, sk));
5962                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
5963                                      bpf_target_off(struct sock_common,
5964                                                     skc_rcv_saddr,
5965                                                     4, target_size));
5966                break;
5967        case offsetof(struct __sk_buff, remote_ip6[0]) ...
5968             offsetof(struct __sk_buff, remote_ip6[3]):
5969#if IS_ENABLED(CONFIG_IPV6)
5970                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
5971                                          skc_v6_daddr.s6_addr32[0]) != 4);
5972
5973                off = si->off;
5974                off -= offsetof(struct __sk_buff, remote_ip6[0]);
5975
5976                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
5977                                      si->dst_reg, si->src_reg,
5978                                      offsetof(struct sk_buff, sk));
5979                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
5980                                      offsetof(struct sock_common,
5981                                               skc_v6_daddr.s6_addr32[0]) +
5982                                      off);
5983#else
5984                *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
5985#endif
5986                break;
5987        case offsetof(struct __sk_buff, local_ip6[0]) ...
5988             offsetof(struct __sk_buff, local_ip6[3]):
5989#if IS_ENABLED(CONFIG_IPV6)
5990                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
5991                                          skc_v6_rcv_saddr.s6_addr32[0]) != 4);
5992
5993                off = si->off;
5994                off -= offsetof(struct __sk_buff, local_ip6[0]);
5995
5996                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
5997                                      si->dst_reg, si->src_reg,
5998                                      offsetof(struct sk_buff, sk));
5999                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6000                                      offsetof(struct sock_common,
6001                                               skc_v6_rcv_saddr.s6_addr32[0]) +
6002                                      off);
6003#else
6004                *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
6005#endif
6006                break;
6007
6008        case offsetof(struct __sk_buff, remote_port):
6009                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
6010
6011                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
6012                                      si->dst_reg, si->src_reg,
6013                                      offsetof(struct sk_buff, sk));
6014                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6015                                      bpf_target_off(struct sock_common,
6016                                                     skc_dport,
6017                                                     2, target_size));
6018#ifndef __BIG_ENDIAN_BITFIELD
6019                *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
6020#endif
6021                break;
6022
6023        case offsetof(struct __sk_buff, local_port):
6024                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
6025
6026                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
6027                                      si->dst_reg, si->src_reg,
6028                                      offsetof(struct sk_buff, sk));
6029                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6030                                      bpf_target_off(struct sock_common,
6031                                                     skc_num, 2, target_size));
6032                break;
6033        }
6034
6035        return insn - insn_buf;
6036}
6037
6038static u32 sock_filter_convert_ctx_access(enum bpf_access_type type,
6039                                          const struct bpf_insn *si,
6040                                          struct bpf_insn *insn_buf,
6041                                          struct bpf_prog *prog, u32 *target_size)
6042{
6043        struct bpf_insn *insn = insn_buf;
6044        int off;
6045
6046        switch (si->off) {
6047        case offsetof(struct bpf_sock, bound_dev_if):
6048                BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_bound_dev_if) != 4);
6049
6050                if (type == BPF_WRITE)
6051                        *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6052                                        offsetof(struct sock, sk_bound_dev_if));
6053                else
6054                        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6055                                      offsetof(struct sock, sk_bound_dev_if));
6056                break;
6057
6058        case offsetof(struct bpf_sock, mark):
6059                BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_mark) != 4);
6060
6061                if (type == BPF_WRITE)
6062                        *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6063                                        offsetof(struct sock, sk_mark));
6064                else
6065                        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6066                                      offsetof(struct sock, sk_mark));
6067                break;
6068
6069        case offsetof(struct bpf_sock, priority):
6070                BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_priority) != 4);
6071
6072                if (type == BPF_WRITE)
6073                        *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6074                                        offsetof(struct sock, sk_priority));
6075                else
6076                        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6077                                      offsetof(struct sock, sk_priority));
6078                break;
6079
6080        case offsetof(struct bpf_sock, family):
6081                BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_family) != 2);
6082
6083                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
6084                                      offsetof(struct sock, sk_family));
6085                break;
6086
6087        case offsetof(struct bpf_sock, type):
6088                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6089                                      offsetof(struct sock, __sk_flags_offset));
6090                *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
6091                *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
6092                break;
6093
6094        case offsetof(struct bpf_sock, protocol):
6095                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6096                                      offsetof(struct sock, __sk_flags_offset));
6097                *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
6098                *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT);
6099                break;
6100
6101        case offsetof(struct bpf_sock, src_ip4):
6102                *insn++ = BPF_LDX_MEM(
6103                        BPF_SIZE(si->code), si->dst_reg, si->src_reg,
6104                        bpf_target_off(struct sock_common, skc_rcv_saddr,
6105                                       FIELD_SIZEOF(struct sock_common,
6106                                                    skc_rcv_saddr),
6107                                       target_size));
6108                break;
6109
6110        case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6111#if IS_ENABLED(CONFIG_IPV6)
6112                off = si->off;
6113                off -= offsetof(struct bpf_sock, src_ip6[0]);
6114                *insn++ = BPF_LDX_MEM(
6115                        BPF_SIZE(si->code), si->dst_reg, si->src_reg,
6116                        bpf_target_off(
6117                                struct sock_common,
6118                                skc_v6_rcv_saddr.s6_addr32[0],
6119                                FIELD_SIZEOF(struct sock_common,
6120                                             skc_v6_rcv_saddr.s6_addr32[0]),
6121                                target_size) + off);
6122#else
6123                (void)off;
6124                *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
6125#endif
6126                break;
6127
6128        case offsetof(struct bpf_sock, src_port):
6129                *insn++ = BPF_LDX_MEM(
6130                        BPF_FIELD_SIZEOF(struct sock_common, skc_num),
6131                        si->dst_reg, si->src_reg,
6132                        bpf_target_off(struct sock_common, skc_num,
6133                                       FIELD_SIZEOF(struct sock_common,
6134                                                    skc_num),
6135                                       target_size));
6136                break;
6137        }
6138
6139        return insn - insn_buf;
6140}
6141
6142static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
6143                                         const struct bpf_insn *si,
6144                                         struct bpf_insn *insn_buf,
6145                                         struct bpf_prog *prog, u32 *target_size)
6146{
6147        struct bpf_insn *insn = insn_buf;
6148
6149        switch (si->off) {
6150        case offsetof(struct __sk_buff, ifindex):
6151                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
6152                                      si->dst_reg, si->src_reg,
6153                                      offsetof(struct sk_buff, dev));
6154                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6155                                      bpf_target_off(struct net_device, ifindex, 4,
6156                                                     target_size));
6157                break;
6158        default:
6159                return bpf_convert_ctx_access(type, si, insn_buf, prog,
6160                                              target_size);
6161        }
6162
6163        return insn - insn_buf;
6164}
6165
6166static u32 xdp_convert_ctx_access(enum bpf_access_type type,
6167                                  const struct bpf_insn *si,
6168                                  struct bpf_insn *insn_buf,
6169                                  struct bpf_prog *prog, u32 *target_size)
6170{
6171        struct bpf_insn *insn = insn_buf;
6172
6173        switch (si->off) {
6174        case offsetof(struct xdp_md, data):
6175                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
6176                                      si->dst_reg, si->src_reg,
6177                                      offsetof(struct xdp_buff, data));
6178                break;
6179        case offsetof(struct xdp_md, data_meta):
6180                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta),
6181                                      si->dst_reg, si->src_reg,
6182                                      offsetof(struct xdp_buff, data_meta));
6183                break;
6184        case offsetof(struct xdp_md, data_end):
6185                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
6186                                      si->dst_reg, si->src_reg,
6187                                      offsetof(struct xdp_buff, data_end));
6188                break;
6189        case offsetof(struct xdp_md, ingress_ifindex):
6190                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
6191                                      si->dst_reg, si->src_reg,
6192                                      offsetof(struct xdp_buff, rxq));
6193                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev),
6194                                      si->dst_reg, si->dst_reg,
6195                                      offsetof(struct xdp_rxq_info, dev));
6196                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6197                                      offsetof(struct net_device, ifindex));
6198                break;
6199        case offsetof(struct xdp_md, rx_queue_index):
6200                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
6201                                      si->dst_reg, si->src_reg,
6202                                      offsetof(struct xdp_buff, rxq));
6203                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6204                                      offsetof(struct xdp_rxq_info,
6205                                               queue_index));
6206                break;
6207        }
6208
6209        return insn - insn_buf;
6210}
6211
6212/* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of
6213 * context Structure, F is Field in context structure that contains a pointer
6214 * to Nested Structure of type NS that has the field NF.
6215 *
6216 * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make
6217 * sure that SIZE is not greater than actual size of S.F.NF.
6218 *
6219 * If offset OFF is provided, the load happens from that offset relative to
6220 * offset of NF.
6221 */
6222#define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF)          \
6223        do {                                                                   \
6224                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg,     \
6225                                      si->src_reg, offsetof(S, F));            \
6226                *insn++ = BPF_LDX_MEM(                                         \
6227                        SIZE, si->dst_reg, si->dst_reg,                        \
6228                        bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),           \
6229                                       target_size)                            \
6230                                + OFF);                                        \
6231        } while (0)
6232
6233#define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF)                              \
6234        SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF,                     \
6235                                             BPF_FIELD_SIZEOF(NS, NF), 0)
6236
6237/* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to
6238 * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation.
6239 *
6240 * It doesn't support SIZE argument though since narrow stores are not
6241 * supported for now.
6242 *
6243 * In addition it uses Temporary Field TF (member of struct S) as the 3rd
6244 * "register" since two registers available in convert_ctx_access are not
6245 * enough: we can't override neither SRC, since it contains value to store, nor
6246 * DST since it contains pointer to context that may be used by later
6247 * instructions. But we need a temporary place to save pointer to nested
6248 * structure whose field we want to store to.
6249 */
6250#define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF, TF)                \
6251        do {                                                                   \
6252                int tmp_reg = BPF_REG_9;                                       \
6253                if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
6254                        --tmp_reg;                                             \
6255                if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
6256                        --tmp_reg;                                             \
6257                *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg,            \
6258                                      offsetof(S, TF));                        \
6259                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg,         \
6260                                      si->dst_reg, offsetof(S, F));            \
6261                *insn++ = BPF_STX_MEM(                                         \
6262                        BPF_FIELD_SIZEOF(NS, NF), tmp_reg, si->src_reg,        \
6263                        bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),           \
6264                                       target_size)                            \
6265                                + OFF);                                        \
6266                *insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg,            \
6267                                      offsetof(S, TF));                        \
6268        } while (0)
6269
6270#define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \
6271                                                      TF)                      \
6272        do {                                                                   \
6273                if (type == BPF_WRITE) {                                       \
6274                        SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF,    \
6275                                                         TF);                  \
6276                } else {                                                       \
6277                        SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(                  \
6278                                S, NS, F, NF, SIZE, OFF);  \
6279                }                                                              \
6280        } while (0)
6281
6282#define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(S, NS, F, NF, TF)                 \
6283        SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(                         \
6284                S, NS, F, NF, BPF_FIELD_SIZEOF(NS, NF), 0, TF)
6285
6286static u32 sock_addr_convert_ctx_access(enum bpf_access_type type,
6287                                        const struct bpf_insn *si,
6288                                        struct bpf_insn *insn_buf,
6289                                        struct bpf_prog *prog, u32 *target_size)
6290{
6291        struct bpf_insn *insn = insn_buf;
6292        int off;
6293
6294        switch (si->off) {
6295        case offsetof(struct bpf_sock_addr, user_family):
6296                SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
6297                                            struct sockaddr, uaddr, sa_family);
6298                break;
6299
6300        case offsetof(struct bpf_sock_addr, user_ip4):
6301                SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
6302                        struct bpf_sock_addr_kern, struct sockaddr_in, uaddr,
6303                        sin_addr, BPF_SIZE(si->code), 0, tmp_reg);
6304                break;
6305
6306        case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
6307                off = si->off;
6308                off -= offsetof(struct bpf_sock_addr, user_ip6[0]);
6309                SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
6310                        struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
6311                        sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off,
6312                        tmp_reg);
6313                break;
6314
6315        case offsetof(struct bpf_sock_addr, user_port):
6316                /* To get port we need to know sa_family first and then treat
6317                 * sockaddr as either sockaddr_in or sockaddr_in6.
6318                 * Though we can simplify since port field has same offset and
6319                 * size in both structures.
6320                 * Here we check this invariant and use just one of the
6321                 * structures if it's true.
6322                 */
6323                BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) !=
6324                             offsetof(struct sockaddr_in6, sin6_port));
6325                BUILD_BUG_ON(FIELD_SIZEOF(struct sockaddr_in, sin_port) !=
6326                             FIELD_SIZEOF(struct sockaddr_in6, sin6_port));
6327                SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(struct bpf_sock_addr_kern,
6328                                                     struct sockaddr_in6, uaddr,
6329                                                     sin6_port, tmp_reg);
6330                break;
6331
6332        case offsetof(struct bpf_sock_addr, family):
6333                SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
6334                                            struct sock, sk, sk_family);
6335                break;
6336
6337        case offsetof(struct bpf_sock_addr, type):
6338                SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
6339                        struct bpf_sock_addr_kern, struct sock, sk,
6340                        __sk_flags_offset, BPF_W, 0);
6341                *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
6342                *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
6343                break;
6344
6345        case offsetof(struct bpf_sock_addr, protocol):
6346                SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
6347                        struct bpf_sock_addr_kern, struct sock, sk,
6348                        __sk_flags_offset, BPF_W, 0);
6349                *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
6350                *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
6351                                        SK_FL_PROTO_SHIFT);
6352                break;
6353
6354        case offsetof(struct bpf_sock_addr, msg_src_ip4):
6355                /* Treat t_ctx as struct in_addr for msg_src_ip4. */
6356                SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
6357                        struct bpf_sock_addr_kern, struct in_addr, t_ctx,
6358                        s_addr, BPF_SIZE(si->code), 0, tmp_reg);
6359                break;
6360
6361        case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
6362                                msg_src_ip6[3]):
6363                off = si->off;
6364                off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]);
6365                /* Treat t_ctx as struct in6_addr for msg_src_ip6. */
6366                SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
6367                        struct bpf_sock_addr_kern, struct in6_addr, t_ctx,
6368                        s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg);
6369                break;
6370        }
6371
6372        return insn - insn_buf;
6373}
6374
6375static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
6376                                       const struct bpf_insn *si,
6377                                       struct bpf_insn *insn_buf,
6378                                       struct bpf_prog *prog,
6379                                       u32 *target_size)
6380{
6381        struct bpf_insn *insn = insn_buf;
6382        int off;
6383
6384        switch (si->off) {
6385        case offsetof(struct bpf_sock_ops, op) ...
6386             offsetof(struct bpf_sock_ops, replylong[3]):
6387                BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, op) !=
6388                             FIELD_SIZEOF(struct bpf_sock_ops_kern, op));
6389                BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, reply) !=
6390                             FIELD_SIZEOF(struct bpf_sock_ops_kern, reply));
6391                BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, replylong) !=
6392                             FIELD_SIZEOF(struct bpf_sock_ops_kern, replylong));
6393                off = si->off;
6394                off -= offsetof(struct bpf_sock_ops, op);
6395                off += offsetof(struct bpf_sock_ops_kern, op);
6396                if (type == BPF_WRITE)
6397                        *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6398                                              off);
6399                else
6400                        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6401                                              off);
6402                break;
6403
6404        case offsetof(struct bpf_sock_ops, family):
6405                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
6406
6407                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6408                                              struct bpf_sock_ops_kern, sk),
6409                                      si->dst_reg, si->src_reg,
6410                                      offsetof(struct bpf_sock_ops_kern, sk));
6411                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6412                                      offsetof(struct sock_common, skc_family));
6413                break;
6414
6415        case offsetof(struct bpf_sock_ops, remote_ip4):
6416                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
6417
6418                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6419                                                struct bpf_sock_ops_kern, sk),
6420                                      si->dst_reg, si->src_reg,
6421                                      offsetof(struct bpf_sock_ops_kern, sk));
6422                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6423                                      offsetof(struct sock_common, skc_daddr));
6424                break;
6425
6426        case offsetof(struct bpf_sock_ops, local_ip4):
6427                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6428                                          skc_rcv_saddr) != 4);
6429
6430                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6431                                              struct bpf_sock_ops_kern, sk),
6432                                      si->dst_reg, si->src_reg,
6433                                      offsetof(struct bpf_sock_ops_kern, sk));
6434                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6435                                      offsetof(struct sock_common,
6436                                               skc_rcv_saddr));
6437                break;
6438
6439        case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
6440             offsetof(struct bpf_sock_ops, remote_ip6[3]):
6441#if IS_ENABLED(CONFIG_IPV6)
6442                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6443                                          skc_v6_daddr.s6_addr32[0]) != 4);
6444
6445                off = si->off;
6446                off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
6447                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6448                                                struct bpf_sock_ops_kern, sk),
6449                                      si->dst_reg, si->src_reg,
6450                                      offsetof(struct bpf_sock_ops_kern, sk));
6451                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6452                                      offsetof(struct sock_common,
6453                                               skc_v6_daddr.s6_addr32[0]) +
6454                                      off);
6455#else
6456                *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
6457#endif
6458                break;
6459
6460        case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
6461             offsetof(struct bpf_sock_ops, local_ip6[3]):
6462#if IS_ENABLED(CONFIG_IPV6)
6463                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6464                                          skc_v6_rcv_saddr.s6_addr32[0]) != 4);
6465
6466                off = si->off;
6467                off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
6468                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6469                                                struct bpf_sock_ops_kern, sk),
6470                                      si->dst_reg, si->src_reg,
6471                                      offsetof(struct bpf_sock_ops_kern, sk));
6472                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6473                                      offsetof(struct sock_common,
6474                                               skc_v6_rcv_saddr.s6_addr32[0]) +
6475                                      off);
6476#else
6477                *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
6478#endif
6479                break;
6480
6481        case offsetof(struct bpf_sock_ops, remote_port):
6482                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
6483
6484                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6485                                                struct bpf_sock_ops_kern, sk),
6486                                      si->dst_reg, si->src_reg,
6487                                      offsetof(struct bpf_sock_ops_kern, sk));
6488                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6489                                      offsetof(struct sock_common, skc_dport));
6490#ifndef __BIG_ENDIAN_BITFIELD
6491                *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
6492#endif
6493                break;
6494
6495        case offsetof(struct bpf_sock_ops, local_port):
6496                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
6497
6498                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6499                                                struct bpf_sock_ops_kern, sk),
6500                                      si->dst_reg, si->src_reg,
6501                                      offsetof(struct bpf_sock_ops_kern, sk));
6502                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6503                                      offsetof(struct sock_common, skc_num));
6504                break;
6505
6506        case offsetof(struct bpf_sock_ops, is_fullsock):
6507                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6508                                                struct bpf_sock_ops_kern,
6509                                                is_fullsock),
6510                                      si->dst_reg, si->src_reg,
6511                                      offsetof(struct bpf_sock_ops_kern,
6512                                               is_fullsock));
6513                break;
6514
6515        case offsetof(struct bpf_sock_ops, state):
6516                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_state) != 1);
6517
6518                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6519                                                struct bpf_sock_ops_kern, sk),
6520                                      si->dst_reg, si->src_reg,
6521                                      offsetof(struct bpf_sock_ops_kern, sk));
6522                *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg,
6523                                      offsetof(struct sock_common, skc_state));
6524                break;
6525
6526        case offsetof(struct bpf_sock_ops, rtt_min):
6527                BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) !=
6528                             sizeof(struct minmax));
6529                BUILD_BUG_ON(sizeof(struct minmax) <
6530                             sizeof(struct minmax_sample));
6531
6532                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6533                                                struct bpf_sock_ops_kern, sk),
6534                                      si->dst_reg, si->src_reg,
6535                                      offsetof(struct bpf_sock_ops_kern, sk));
6536                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6537                                      offsetof(struct tcp_sock, rtt_min) +
6538                                      FIELD_SIZEOF(struct minmax_sample, t));
6539                break;
6540
6541/* Helper macro for adding read access to tcp_sock or sock fields. */
6542#define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
6543        do {                                                                  \
6544                BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >                   \
6545                             FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
6546                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
6547                                                struct bpf_sock_ops_kern,     \
6548                                                is_fullsock),                 \
6549                                      si->dst_reg, si->src_reg,               \
6550                                      offsetof(struct bpf_sock_ops_kern,      \
6551                                               is_fullsock));                 \
6552                *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 2);            \
6553                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
6554                                                struct bpf_sock_ops_kern, sk),\
6555                                      si->dst_reg, si->src_reg,               \
6556                                      offsetof(struct bpf_sock_ops_kern, sk));\
6557                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ,                   \
6558                                                       OBJ_FIELD),            \
6559                                      si->dst_reg, si->dst_reg,               \
6560                                      offsetof(OBJ, OBJ_FIELD));              \
6561        } while (0)
6562
6563/* Helper macro for adding write access to tcp_sock or sock fields.
6564 * The macro is called with two registers, dst_reg which contains a pointer
6565 * to ctx (context) and src_reg which contains the value that should be
6566 * stored. However, we need an additional register since we cannot overwrite
6567 * dst_reg because it may be used later in the program.
6568 * Instead we "borrow" one of the other register. We first save its value
6569 * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore
6570 * it at the end of the macro.
6571 */
6572#define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
6573        do {                                                                  \
6574                int reg = BPF_REG_9;                                          \
6575                BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >                   \
6576                             FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
6577                if (si->dst_reg == reg || si->src_reg == reg)                 \
6578                        reg--;                                                \
6579                if (si->dst_reg == reg || si->src_reg == reg)                 \
6580                        reg--;                                                \
6581                *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg,               \
6582                                      offsetof(struct bpf_sock_ops_kern,      \
6583                                               temp));                        \
6584                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
6585                                                struct bpf_sock_ops_kern,     \
6586                                                is_fullsock),                 \
6587                                      reg, si->dst_reg,                       \
6588                                      offsetof(struct bpf_sock_ops_kern,      \
6589                                               is_fullsock));                 \
6590                *insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);                    \
6591                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
6592                                                struct bpf_sock_ops_kern, sk),\
6593                                      reg, si->dst_reg,                       \
6594                                      offsetof(struct bpf_sock_ops_kern, sk));\
6595                *insn++ = BPF_STX_MEM(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD),       \
6596                                      reg, si->src_reg,                       \
6597                                      offsetof(OBJ, OBJ_FIELD));              \
6598                *insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg,               \
6599                                      offsetof(struct bpf_sock_ops_kern,      \
6600                                               temp));                        \
6601        } while (0)
6602
6603#define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE)            \
6604        do {                                                                  \
6605                if (TYPE == BPF_WRITE)                                        \
6606                        SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
6607                else                                                          \
6608                        SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
6609        } while (0)
6610
6611        case offsetof(struct bpf_sock_ops, snd_cwnd):
6612                SOCK_OPS_GET_FIELD(snd_cwnd, snd_cwnd, struct tcp_sock);
6613                break;
6614
6615        case offsetof(struct bpf_sock_ops, srtt_us):
6616                SOCK_OPS_GET_FIELD(srtt_us, srtt_us, struct tcp_sock);
6617                break;
6618
6619        case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags):
6620                SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags,
6621                                   struct tcp_sock);
6622                break;
6623
6624        case offsetof(struct bpf_sock_ops, snd_ssthresh):
6625                SOCK_OPS_GET_FIELD(snd_ssthresh, snd_ssthresh, struct tcp_sock);
6626                break;
6627
6628        case offsetof(struct bpf_sock_ops, rcv_nxt):
6629                SOCK_OPS_GET_FIELD(rcv_nxt, rcv_nxt, struct tcp_sock);
6630                break;
6631
6632        case offsetof(struct bpf_sock_ops, snd_nxt):
6633                SOCK_OPS_GET_FIELD(snd_nxt, snd_nxt, struct tcp_sock);
6634                break;
6635
6636        case offsetof(struct bpf_sock_ops, snd_una):
6637                SOCK_OPS_GET_FIELD(snd_una, snd_una, struct tcp_sock);
6638                break;
6639
6640        case offsetof(struct bpf_sock_ops, mss_cache):
6641                SOCK_OPS_GET_FIELD(mss_cache, mss_cache, struct tcp_sock);
6642                break;
6643
6644        case offsetof(struct bpf_sock_ops, ecn_flags):
6645                SOCK_OPS_GET_FIELD(ecn_flags, ecn_flags, struct tcp_sock);
6646                break;
6647
6648        case offsetof(struct bpf_sock_ops, rate_delivered):
6649                SOCK_OPS_GET_FIELD(rate_delivered, rate_delivered,
6650                                   struct tcp_sock);
6651                break;
6652
6653        case offsetof(struct bpf_sock_ops, rate_interval_us):
6654                SOCK_OPS_GET_FIELD(rate_interval_us, rate_interval_us,
6655                                   struct tcp_sock);
6656                break;
6657
6658        case offsetof(struct bpf_sock_ops, packets_out):
6659                SOCK_OPS_GET_FIELD(packets_out, packets_out, struct tcp_sock);
6660                break;
6661
6662        case offsetof(struct bpf_sock_ops, retrans_out):
6663                SOCK_OPS_GET_FIELD(retrans_out, retrans_out, struct tcp_sock);
6664                break;
6665
6666        case offsetof(struct bpf_sock_ops, total_retrans):
6667                SOCK_OPS_GET_FIELD(total_retrans, total_retrans,
6668                                   struct tcp_sock);
6669                break;
6670
6671        case offsetof(struct bpf_sock_ops, segs_in):
6672                SOCK_OPS_GET_FIELD(segs_in, segs_in, struct tcp_sock);
6673                break;
6674
6675        case offsetof(struct bpf_sock_ops, data_segs_in):
6676                SOCK_OPS_GET_FIELD(data_segs_in, data_segs_in, struct tcp_sock);
6677                break;
6678
6679        case offsetof(struct bpf_sock_ops, segs_out):
6680                SOCK_OPS_GET_FIELD(segs_out, segs_out, struct tcp_sock);
6681                break;
6682
6683        case offsetof(struct bpf_sock_ops, data_segs_out):
6684                SOCK_OPS_GET_FIELD(data_segs_out, data_segs_out,
6685                                   struct tcp_sock);
6686                break;
6687
6688        case offsetof(struct bpf_sock_ops, lost_out):
6689                SOCK_OPS_GET_FIELD(lost_out, lost_out, struct tcp_sock);
6690                break;
6691
6692        case offsetof(struct bpf_sock_ops, sacked_out):
6693                SOCK_OPS_GET_FIELD(sacked_out, sacked_out, struct tcp_sock);
6694                break;
6695
6696        case offsetof(struct bpf_sock_ops, sk_txhash):
6697                SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash,
6698                                          struct sock, type);
6699                break;
6700
6701        case offsetof(struct bpf_sock_ops, bytes_received):
6702                SOCK_OPS_GET_FIELD(bytes_received, bytes_received,
6703                                   struct tcp_sock);
6704                break;
6705
6706        case offsetof(struct bpf_sock_ops, bytes_acked):
6707                SOCK_OPS_GET_FIELD(bytes_acked, bytes_acked, struct tcp_sock);
6708                break;
6709
6710        }
6711        return insn - insn_buf;
6712}
6713
6714static u32 sk_skb_convert_ctx_access(enum bpf_access_type type,
6715                                     const struct bpf_insn *si,
6716                                     struct bpf_insn *insn_buf,
6717                                     struct bpf_prog *prog, u32 *target_size)
6718{
6719        struct bpf_insn *insn = insn_buf;
6720        int off;
6721
6722        switch (si->off) {
6723        case offsetof(struct __sk_buff, data_end):
6724                off  = si->off;
6725                off -= offsetof(struct __sk_buff, data_end);
6726                off += offsetof(struct sk_buff, cb);
6727                off += offsetof(struct tcp_skb_cb, bpf.data_end);
6728                *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
6729                                      si->src_reg, off);
6730                break;
6731        default:
6732                return bpf_convert_ctx_access(type, si, insn_buf, prog,
6733                                              target_size);
6734        }
6735
6736        return insn - insn_buf;
6737}
6738
6739static u32 sk_msg_convert_ctx_access(enum bpf_access_type type,
6740                                     const struct bpf_insn *si,
6741                                     struct bpf_insn *insn_buf,
6742                                     struct bpf_prog *prog, u32 *target_size)
6743{
6744        struct bpf_insn *insn = insn_buf;
6745#if IS_ENABLED(CONFIG_IPV6)
6746        int off;
6747#endif
6748
6749        switch (si->off) {
6750        case offsetof(struct sk_msg_md, data):
6751                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_buff, data),
6752                                      si->dst_reg, si->src_reg,
6753                                      offsetof(struct sk_msg_buff, data));
6754                break;
6755        case offsetof(struct sk_msg_md, data_end):
6756                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_buff, data_end),
6757                                      si->dst_reg, si->src_reg,
6758                                      offsetof(struct sk_msg_buff, data_end));
6759                break;
6760        case offsetof(struct sk_msg_md, family):
6761                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
6762
6763                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6764                                              struct sk_msg_buff, sk),
6765                                      si->dst_reg, si->src_reg,
6766                                      offsetof(struct sk_msg_buff, sk));
6767                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6768                                      offsetof(struct sock_common, skc_family));
6769                break;
6770
6771        case offsetof(struct sk_msg_md, remote_ip4):
6772                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
6773
6774                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6775                                                struct sk_msg_buff, sk),
6776                                      si->dst_reg, si->src_reg,
6777                                      offsetof(struct sk_msg_buff, sk));
6778                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6779                                      offsetof(struct sock_common, skc_daddr));
6780                break;
6781
6782        case offsetof(struct sk_msg_md, local_ip4):
6783                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6784                                          skc_rcv_saddr) != 4);
6785
6786                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6787                                              struct sk_msg_buff, sk),
6788                                      si->dst_reg, si->src_reg,
6789                                      offsetof(struct sk_msg_buff, sk));
6790                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6791                                      offsetof(struct sock_common,
6792                                               skc_rcv_saddr));
6793                break;
6794
6795        case offsetof(struct sk_msg_md, remote_ip6[0]) ...
6796             offsetof(struct sk_msg_md, remote_ip6[3]):
6797#if IS_ENABLED(CONFIG_IPV6)
6798                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6799                                          skc_v6_daddr.s6_addr32[0]) != 4);
6800
6801                off = si->off;
6802                off -= offsetof(struct sk_msg_md, remote_ip6[0]);
6803                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6804                                                struct sk_msg_buff, sk),
6805                                      si->dst_reg, si->src_reg,
6806                                      offsetof(struct sk_msg_buff, sk));
6807                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6808                                      offsetof(struct sock_common,
6809                                               skc_v6_daddr.s6_addr32[0]) +
6810                                      off);
6811#else
6812                *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
6813#endif
6814                break;
6815
6816        case offsetof(struct sk_msg_md, local_ip6[0]) ...
6817             offsetof(struct sk_msg_md, local_ip6[3]):
6818#if IS_ENABLED(CONFIG_IPV6)
6819                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
6820                                          skc_v6_rcv_saddr.s6_addr32[0]) != 4);
6821
6822                off = si->off;
6823                off -= offsetof(struct sk_msg_md, local_ip6[0]);
6824                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6825                                                struct sk_msg_buff, sk),
6826                                      si->dst_reg, si->src_reg,
6827                                      offsetof(struct sk_msg_buff, sk));
6828                *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6829                                      offsetof(struct sock_common,
6830                                               skc_v6_rcv_saddr.s6_addr32[0]) +
6831                                      off);
6832#else
6833                *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
6834#endif
6835                break;
6836
6837        case offsetof(struct sk_msg_md, remote_port):
6838                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
6839
6840                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6841                                                struct sk_msg_buff, sk),
6842                                      si->dst_reg, si->src_reg,
6843                                      offsetof(struct sk_msg_buff, sk));
6844                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6845                                      offsetof(struct sock_common, skc_dport));
6846#ifndef __BIG_ENDIAN_BITFIELD
6847                *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
6848#endif
6849                break;
6850
6851        case offsetof(struct sk_msg_md, local_port):
6852                BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
6853
6854                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
6855                                                struct sk_msg_buff, sk),
6856                                      si->dst_reg, si->src_reg,
6857                                      offsetof(struct sk_msg_buff, sk));
6858                *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
6859                                      offsetof(struct sock_common, skc_num));
6860                break;
6861        }
6862
6863        return insn - insn_buf;
6864}
6865
6866const struct bpf_verifier_ops sk_filter_verifier_ops = {
6867        .get_func_proto         = sk_filter_func_proto,
6868        .is_valid_access        = sk_filter_is_valid_access,
6869        .convert_ctx_access     = bpf_convert_ctx_access,
6870        .gen_ld_abs             = bpf_gen_ld_abs,
6871};
6872
6873const struct bpf_prog_ops sk_filter_prog_ops = {
6874        .test_run               = bpf_prog_test_run_skb,
6875};
6876
6877const struct bpf_verifier_ops tc_cls_act_verifier_ops = {
6878        .get_func_proto         = tc_cls_act_func_proto,
6879        .is_valid_access        = tc_cls_act_is_valid_access,
6880        .convert_ctx_access     = tc_cls_act_convert_ctx_access,
6881        .gen_prologue           = tc_cls_act_prologue,
6882        .gen_ld_abs             = bpf_gen_ld_abs,
6883};
6884
6885const struct bpf_prog_ops tc_cls_act_prog_ops = {
6886        .test_run               = bpf_prog_test_run_skb,
6887};
6888
6889const struct bpf_verifier_ops xdp_verifier_ops = {
6890        .get_func_proto         = xdp_func_proto,
6891        .is_valid_access        = xdp_is_valid_access,
6892        .convert_ctx_access     = xdp_convert_ctx_access,
6893};
6894
6895const struct bpf_prog_ops xdp_prog_ops = {
6896        .test_run               = bpf_prog_test_run_xdp,
6897};
6898
6899const struct bpf_verifier_ops cg_skb_verifier_ops = {
6900        .get_func_proto         = cg_skb_func_proto,
6901        .is_valid_access        = sk_filter_is_valid_access,
6902        .convert_ctx_access     = bpf_convert_ctx_access,
6903};
6904
6905const struct bpf_prog_ops cg_skb_prog_ops = {
6906        .test_run               = bpf_prog_test_run_skb,
6907};
6908
6909const struct bpf_verifier_ops lwt_in_verifier_ops = {
6910        .get_func_proto         = lwt_in_func_proto,
6911        .is_valid_access        = lwt_is_valid_access,
6912        .convert_ctx_access     = bpf_convert_ctx_access,
6913};
6914
6915const struct bpf_prog_ops lwt_in_prog_ops = {
6916        .test_run               = bpf_prog_test_run_skb,
6917};
6918
6919const struct bpf_verifier_ops lwt_out_verifier_ops = {
6920        .get_func_proto         = lwt_out_func_proto,
6921        .is_valid_access        = lwt_is_valid_access,
6922        .convert_ctx_access     = bpf_convert_ctx_access,
6923};
6924
6925const struct bpf_prog_ops lwt_out_prog_ops = {
6926        .test_run               = bpf_prog_test_run_skb,
6927};
6928
6929const struct bpf_verifier_ops lwt_xmit_verifier_ops = {
6930        .get_func_proto         = lwt_xmit_func_proto,
6931        .is_valid_access        = lwt_is_valid_access,
6932        .convert_ctx_access     = bpf_convert_ctx_access,
6933        .gen_prologue           = tc_cls_act_prologue,
6934};
6935
6936const struct bpf_prog_ops lwt_xmit_prog_ops = {
6937        .test_run               = bpf_prog_test_run_skb,
6938};
6939
6940const struct bpf_verifier_ops lwt_seg6local_verifier_ops = {
6941        .get_func_proto         = lwt_seg6local_func_proto,
6942        .is_valid_access        = lwt_is_valid_access,
6943        .convert_ctx_access     = bpf_convert_ctx_access,
6944};
6945
6946const struct bpf_prog_ops lwt_seg6local_prog_ops = {
6947        .test_run               = bpf_prog_test_run_skb,
6948};
6949
6950const struct bpf_verifier_ops cg_sock_verifier_ops = {
6951        .get_func_proto         = sock_filter_func_proto,
6952        .is_valid_access        = sock_filter_is_valid_access,
6953        .convert_ctx_access     = sock_filter_convert_ctx_access,
6954};
6955
6956const struct bpf_prog_ops cg_sock_prog_ops = {
6957};
6958
6959const struct bpf_verifier_ops cg_sock_addr_verifier_ops = {
6960        .get_func_proto         = sock_addr_func_proto,
6961        .is_valid_access        = sock_addr_is_valid_access,
6962        .convert_ctx_access     = sock_addr_convert_ctx_access,
6963};
6964
6965const struct bpf_prog_ops cg_sock_addr_prog_ops = {
6966};
6967
6968const struct bpf_verifier_ops sock_ops_verifier_ops = {
6969        .get_func_proto         = sock_ops_func_proto,
6970        .is_valid_access        = sock_ops_is_valid_access,
6971        .convert_ctx_access     = sock_ops_convert_ctx_access,
6972};
6973
6974const struct bpf_prog_ops sock_ops_prog_ops = {
6975};
6976
6977const struct bpf_verifier_ops sk_skb_verifier_ops = {
6978        .get_func_proto         = sk_skb_func_proto,
6979        .is_valid_access        = sk_skb_is_valid_access,
6980        .convert_ctx_access     = sk_skb_convert_ctx_access,
6981        .gen_prologue           = sk_skb_prologue,
6982};
6983
6984const struct bpf_prog_ops sk_skb_prog_ops = {
6985};
6986
6987const struct bpf_verifier_ops sk_msg_verifier_ops = {
6988        .get_func_proto         = sk_msg_func_proto,
6989        .is_valid_access        = sk_msg_is_valid_access,
6990        .convert_ctx_access     = sk_msg_convert_ctx_access,
6991};
6992
6993const struct bpf_prog_ops sk_msg_prog_ops = {
6994};
6995
6996int sk_detach_filter(struct sock *sk)
6997{
6998        int ret = -ENOENT;
6999        struct sk_filter *filter;
7000
7001        if (sock_flag(sk, SOCK_FILTER_LOCKED))
7002                return -EPERM;
7003
7004        filter = rcu_dereference_protected(sk->sk_filter,
7005                                           lockdep_sock_is_held(sk));
7006        if (filter) {
7007                RCU_INIT_POINTER(sk->sk_filter, NULL);
7008                sk_filter_uncharge(sk, filter);
7009                ret = 0;
7010        }
7011
7012        return ret;
7013}
7014EXPORT_SYMBOL_GPL(sk_detach_filter);
7015
7016int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
7017                  unsigned int len)
7018{
7019        struct sock_fprog_kern *fprog;
7020        struct sk_filter *filter;
7021        int ret = 0;
7022
7023        lock_sock(sk);
7024        filter = rcu_dereference_protected(sk->sk_filter,
7025                                           lockdep_sock_is_held(sk));
7026        if (!filter)
7027                goto out;
7028
7029        /* We're copying the filter that has been originally attached,
7030         * so no conversion/decode needed anymore. eBPF programs that
7031         * have no original program cannot be dumped through this.
7032         */
7033        ret = -EACCES;
7034        fprog = filter->prog->orig_prog;
7035        if (!fprog)
7036                goto out;
7037
7038        ret = fprog->len;
7039        if (!len)
7040                /* User space only enquires number of filter blocks. */
7041                goto out;
7042
7043        ret = -EINVAL;
7044        if (len < fprog->len)
7045                goto out;
7046
7047        ret = -EFAULT;
7048        if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
7049                goto out;
7050
7051        /* Instead of bytes, the API requests to return the number
7052         * of filter blocks.
7053         */
7054        ret = fprog->len;
7055out:
7056        release_sock(sk);
7057        return ret;
7058}
7059
7060#ifdef CONFIG_INET
7061struct sk_reuseport_kern {
7062        struct sk_buff *skb;
7063        struct sock *sk;
7064        struct sock *selected_sk;
7065        void *data_end;
7066        u32 hash;
7067        u32 reuseport_id;
7068        bool bind_inany;
7069};
7070
7071static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,
7072                                    struct sock_reuseport *reuse,
7073                                    struct sock *sk, struct sk_buff *skb,
7074                                    u32 hash)
7075{
7076        reuse_kern->skb = skb;
7077        reuse_kern->sk = sk;
7078        reuse_kern->selected_sk = NULL;
7079        reuse_kern->data_end = skb->data + skb_headlen(skb);
7080        reuse_kern->hash = hash;
7081        reuse_kern->reuseport_id = reuse->reuseport_id;
7082        reuse_kern->bind_inany = reuse->bind_inany;
7083}
7084
7085struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,
7086                                  struct bpf_prog *prog, struct sk_buff *skb,
7087                                  u32 hash)
7088{
7089        struct sk_reuseport_kern reuse_kern;
7090        enum sk_action action;
7091
7092        bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, hash);
7093        action = BPF_PROG_RUN(prog, &reuse_kern);
7094
7095        if (action == SK_PASS)
7096                return reuse_kern.selected_sk;
7097        else
7098                return ERR_PTR(-ECONNREFUSED);
7099}
7100
7101BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern,
7102           struct bpf_map *, map, void *, key, u32, flags)
7103{
7104        struct sock_reuseport *reuse;
7105        struct sock *selected_sk;
7106
7107        selected_sk = map->ops->map_lookup_elem(map, key);
7108        if (!selected_sk)
7109                return -ENOENT;
7110
7111        reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
7112        if (!reuse)
7113                /* selected_sk is unhashed (e.g. by close()) after the
7114                 * above map_lookup_elem().  Treat selected_sk has already
7115                 * been removed from the map.
7116                 */
7117                return -ENOENT;
7118
7119        if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
7120                struct sock *sk;
7121
7122                if (unlikely(!reuse_kern->reuseport_id))
7123                        /* There is a small race between adding the
7124                         * sk to the map and setting the
7125                         * reuse_kern->reuseport_id.
7126                         * Treat it as the sk has not been added to
7127                         * the bpf map yet.
7128                         */
7129                        return -ENOENT;
7130
7131                sk = reuse_kern->sk;
7132                if (sk->sk_protocol != selected_sk->sk_protocol)
7133                        return -EPROTOTYPE;
7134                else if (sk->sk_family != selected_sk->sk_family)
7135                        return -EAFNOSUPPORT;
7136
7137                /* Catch all. Likely bound to a different sockaddr. */
7138                return -EBADFD;
7139        }
7140
7141        reuse_kern->selected_sk = selected_sk;
7142
7143        return 0;
7144}
7145
7146static const struct bpf_func_proto sk_select_reuseport_proto = {
7147        .func           = sk_select_reuseport,
7148        .gpl_only       = false,
7149        .ret_type       = RET_INTEGER,
7150        .arg1_type      = ARG_PTR_TO_CTX,
7151        .arg2_type      = ARG_CONST_MAP_PTR,
7152        .arg3_type      = ARG_PTR_TO_MAP_KEY,
7153        .arg4_type      = ARG_ANYTHING,
7154};
7155
7156BPF_CALL_4(sk_reuseport_load_bytes,
7157           const struct sk_reuseport_kern *, reuse_kern, u32, offset,
7158           void *, to, u32, len)
7159{
7160        return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
7161}
7162
7163static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
7164        .func           = sk_reuseport_load_bytes,
7165        .gpl_only       = false,
7166        .ret_type       = RET_INTEGER,
7167        .arg1_type      = ARG_PTR_TO_CTX,
7168        .arg2_type      = ARG_ANYTHING,
7169        .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
7170        .arg4_type      = ARG_CONST_SIZE,
7171};
7172
7173BPF_CALL_5(sk_reuseport_load_bytes_relative,
7174           const struct sk_reuseport_kern *, reuse_kern, u32, offset,
7175           void *, to, u32, len, u32, start_header)
7176{
7177        return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
7178                                               len, start_header);
7179}
7180
7181static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
7182        .func           = sk_reuseport_load_bytes_relative,
7183        .gpl_only       = false,
7184        .ret_type       = RET_INTEGER,
7185        .arg1_type      = ARG_PTR_TO_CTX,
7186        .arg2_type      = ARG_ANYTHING,
7187        .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
7188        .arg4_type      = ARG_CONST_SIZE,
7189        .arg5_type      = ARG_ANYTHING,
7190};
7191
7192static const struct bpf_func_proto *
7193sk_reuseport_func_proto(enum bpf_func_id func_id,
7194                        const struct bpf_prog *prog)
7195{
7196        switch (func_id) {
7197        case BPF_FUNC_sk_select_reuseport:
7198                return &sk_select_reuseport_proto;
7199        case BPF_FUNC_skb_load_bytes:
7200                return &sk_reuseport_load_bytes_proto;
7201        case BPF_FUNC_skb_load_bytes_relative:
7202                return &sk_reuseport_load_bytes_relative_proto;
7203        default:
7204                return bpf_base_func_proto(func_id);
7205        }
7206}
7207
7208static bool
7209sk_reuseport_is_valid_access(int off, int size,
7210                             enum bpf_access_type type,
7211                             const struct bpf_prog *prog,
7212                             struct bpf_insn_access_aux *info)
7213{
7214        const u32 size_default = sizeof(__u32);
7215
7216        if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
7217            off % size || type != BPF_READ)
7218                return false;
7219
7220        switch (off) {
7221        case offsetof(struct sk_reuseport_md, data):
7222                info->reg_type = PTR_TO_PACKET;
7223                return size == sizeof(__u64);
7224
7225        case offsetof(struct sk_reuseport_md, data_end):
7226                info->reg_type = PTR_TO_PACKET_END;
7227                return size == sizeof(__u64);
7228
7229        case offsetof(struct sk_reuseport_md, hash):
7230                return size == size_default;
7231
7232        /* Fields that allow narrowing */
7233        case offsetof(struct sk_reuseport_md, eth_protocol):
7234                if (size < FIELD_SIZEOF(struct sk_buff, protocol))
7235                        return false;
7236                /* fall through */
7237        case offsetof(struct sk_reuseport_md, ip_protocol):
7238        case offsetof(struct sk_reuseport_md, bind_inany):
7239        case offsetof(struct sk_reuseport_md, len):
7240                bpf_ctx_record_field_size(info, size_default);
7241                return bpf_ctx_narrow_access_ok(off, size, size_default);
7242
7243        default:
7244                return false;
7245        }
7246}
7247
7248#define SK_REUSEPORT_LOAD_FIELD(F) ({                                   \
7249        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
7250                              si->dst_reg, si->src_reg,                 \
7251                              bpf_target_off(struct sk_reuseport_kern, F, \
7252                                             FIELD_SIZEOF(struct sk_reuseport_kern, F), \
7253                                             target_size));             \
7254        })
7255
7256#define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)                          \
7257        SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,           \
7258                                    struct sk_buff,                     \
7259                                    skb,                                \
7260                                    SKB_FIELD)
7261
7262#define SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(SK_FIELD, BPF_SIZE, EXTRA_OFF) \
7263        SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(struct sk_reuseport_kern,  \
7264                                             struct sock,               \
7265                                             sk,                        \
7266                                             SK_FIELD, BPF_SIZE, EXTRA_OFF)
7267
7268static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
7269                                           const struct bpf_insn *si,
7270                                           struct bpf_insn *insn_buf,
7271                                           struct bpf_prog *prog,
7272                                           u32 *target_size)
7273{
7274        struct bpf_insn *insn = insn_buf;
7275
7276        switch (si->off) {
7277        case offsetof(struct sk_reuseport_md, data):
7278                SK_REUSEPORT_LOAD_SKB_FIELD(data);
7279                break;
7280
7281        case offsetof(struct sk_reuseport_md, len):
7282                SK_REUSEPORT_LOAD_SKB_FIELD(len);
7283                break;
7284
7285        case offsetof(struct sk_reuseport_md, eth_protocol):
7286                SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
7287                break;
7288
7289        case offsetof(struct sk_reuseport_md, ip_protocol):
7290                BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE);
7291                SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(__sk_flags_offset,
7292                                                    BPF_W, 0);
7293                *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
7294                *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
7295                                        SK_FL_PROTO_SHIFT);
7296                /* SK_FL_PROTO_MASK and SK_FL_PROTO_SHIFT are endian
7297                 * aware.  No further narrowing or masking is needed.
7298                 */
7299                *target_size = 1;
7300                break;
7301
7302        case offsetof(struct sk_reuseport_md, data_end):
7303                SK_REUSEPORT_LOAD_FIELD(data_end);
7304                break;
7305
7306        case offsetof(struct sk_reuseport_md, hash):
7307                SK_REUSEPORT_LOAD_FIELD(hash);
7308                break;
7309
7310        case offsetof(struct sk_reuseport_md, bind_inany):
7311                SK_REUSEPORT_LOAD_FIELD(bind_inany);
7312                break;
7313        }
7314
7315        return insn - insn_buf;
7316}
7317
7318const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
7319        .get_func_proto         = sk_reuseport_func_proto,
7320        .is_valid_access        = sk_reuseport_is_valid_access,
7321        .convert_ctx_access     = sk_reuseport_convert_ctx_access,
7322};
7323
7324const struct bpf_prog_ops sk_reuseport_prog_ops = {
7325};
7326#endif /* CONFIG_INET */
7327