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