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