linux/net/core/filter.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 * Linux Socket Filter - Kernel level socket filtering
   4 *
   5 * Based on the design of the Berkeley Packet Filter. The new
   6 * internal format has been designed by PLUMgrid:
   7 *
   8 *      Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
   9 *
  10 * Authors:
  11 *
  12 *      Jay Schulist <jschlst@samba.org>
  13 *      Alexei Starovoitov <ast@plumgrid.com>
  14 *      Daniel Borkmann <dborkman@redhat.com>
  15 *
  16 * Andi Kleen - Fix a few bad bugs and races.
  17 * Kris Katterjohn - Added many additional checks in bpf_check_classic()
  18 */
  19
  20#include <linux/module.h>
  21#include <linux/types.h>
  22#include <linux/mm.h>
  23#include <linux/fcntl.h>
  24#include <linux/socket.h>
  25#include <linux/sock_diag.h>
  26#include <linux/in.h>
  27#include <linux/inet.h>
  28#include <linux/netdevice.h>
  29#include <linux/if_packet.h>
  30#include <linux/if_arp.h>
  31#include <linux/gfp.h>
  32#include <net/inet_common.h>
  33#include <net/ip.h>
  34#include <net/protocol.h>
  35#include <net/netlink.h>
  36#include <linux/skbuff.h>
  37#include <linux/skmsg.h>
  38#include <net/sock.h>
  39#include <net/flow_dissector.h>
  40#include <linux/errno.h>
  41#include <linux/timer.h>
  42#include <linux/uaccess.h>
  43#include <asm/unaligned.h>
  44#include <asm/cmpxchg.h>
  45#include <linux/filter.h>
  46#include <linux/ratelimit.h>
  47#include <linux/seccomp.h>
  48#include <linux/if_vlan.h>
  49#include <linux/bpf.h>
  50#include <net/sch_generic.h>
  51#include <net/cls_cgroup.h>
  52#include <net/dst_metadata.h>
  53#include <net/dst.h>
  54#include <net/sock_reuseport.h>
  55#include <net/busy_poll.h>
  56#include <net/tcp.h>
  57#include <net/xfrm.h>
  58#include <net/udp.h>
  59#include <linux/bpf_trace.h>
  60#include <net/xdp_sock.h>
  61#include <linux/inetdevice.h>
  62#include <net/inet_hashtables.h>
  63#include <net/inet6_hashtables.h>
  64#include <net/ip_fib.h>
  65#include <net/nexthop.h>
  66#include <net/flow.h>
  67#include <net/arp.h>
  68#include <net/ipv6.h>
  69#include <net/net_namespace.h>
  70#include <linux/seg6_local.h>
  71#include <net/seg6.h>
  72#include <net/seg6_local.h>
  73#include <net/lwtunnel.h>
  74#include <net/ipv6_stubs.h>
  75#include <net/bpf_sk_storage.h>
  76
  77/**
  78 *      sk_filter_trim_cap - run a packet through a socket filter
  79 *      @sk: sock associated with &sk_buff
  80 *      @skb: buffer to filter
  81 *      @cap: limit on how short the eBPF program may trim the packet
  82 *
  83 * Run the eBPF program and then cut skb->data to correct size returned by
  84 * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
  85 * than pkt_len we keep whole skb->data. This is the socket level
  86 * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
  87 * be accepted or -EPERM if the packet should be tossed.
  88 *
  89 */
  90int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
  91{
  92        int err;
  93        struct sk_filter *filter;
  94
  95        /*
  96         * If the skb was allocated from pfmemalloc reserves, only
  97         * allow SOCK_MEMALLOC sockets to use it as this socket is
  98         * helping free memory
  99         */
 100        if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
 101                NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
 102                return -ENOMEM;
 103        }
 104        err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
 105        if (err)
 106                return err;
 107
 108        err = security_sock_rcv_skb(sk, skb);
 109        if (err)
 110                return err;
 111
 112        rcu_read_lock();
 113        filter = rcu_dereference(sk->sk_filter);
 114        if (filter) {
 115                struct sock *save_sk = skb->sk;
 116                unsigned int pkt_len;
 117
 118                skb->sk = sk;
 119                pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
 120                skb->sk = save_sk;
 121                err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
 122        }
 123        rcu_read_unlock();
 124
 125        return err;
 126}
 127EXPORT_SYMBOL(sk_filter_trim_cap);
 128
 129BPF_CALL_1(bpf_skb_get_pay_offset, struct sk_buff *, skb)
 130{
 131        return skb_get_poff(skb);
 132}
 133
 134BPF_CALL_3(bpf_skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
 135{
 136        struct nlattr *nla;
 137
 138        if (skb_is_nonlinear(skb))
 139                return 0;
 140
 141        if (skb->len < sizeof(struct nlattr))
 142                return 0;
 143
 144        if (a > skb->len - sizeof(struct nlattr))
 145                return 0;
 146
 147        nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
 148        if (nla)
 149                return (void *) nla - (void *) skb->data;
 150
 151        return 0;
 152}
 153
 154BPF_CALL_3(bpf_skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
 155{
 156        struct nlattr *nla;
 157
 158        if (skb_is_nonlinear(skb))
 159                return 0;
 160
 161        if (skb->len < sizeof(struct nlattr))
 162                return 0;
 163
 164        if (a > skb->len - sizeof(struct nlattr))
 165                return 0;
 166
 167        nla = (struct nlattr *) &skb->data[a];
 168        if (nla->nla_len > skb->len - a)
 169                return 0;
 170
 171        nla = nla_find_nested(nla, x);
 172        if (nla)
 173                return (void *) nla - (void *) skb->data;
 174
 175        return 0;
 176}
 177
 178BPF_CALL_4(bpf_skb_load_helper_8, const struct sk_buff *, skb, const void *,
 179           data, int, headlen, int, offset)
 180{
 181        u8 tmp, *ptr;
 182        const int len = sizeof(tmp);
 183
 184        if (offset >= 0) {
 185                if (headlen - offset >= len)
 186                        return *(u8 *)(data + offset);
 187                if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
 188                        return tmp;
 189        } else {
 190                ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
 191                if (likely(ptr))
 192                        return *(u8 *)ptr;
 193        }
 194
 195        return -EFAULT;
 196}
 197
 198BPF_CALL_2(bpf_skb_load_helper_8_no_cache, const struct sk_buff *, skb,
 199           int, offset)
 200{
 201        return ____bpf_skb_load_helper_8(skb, skb->data, skb->len - skb->data_len,
 202                                         offset);
 203}
 204
 205BPF_CALL_4(bpf_skb_load_helper_16, const struct sk_buff *, skb, const void *,
 206           data, int, headlen, int, offset)
 207{
 208        u16 tmp, *ptr;
 209        const int len = sizeof(tmp);
 210
 211        if (offset >= 0) {
 212                if (headlen - offset >= len)
 213                        return get_unaligned_be16(data + offset);
 214                if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
 215                        return be16_to_cpu(tmp);
 216        } else {
 217                ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
 218                if (likely(ptr))
 219                        return get_unaligned_be16(ptr);
 220        }
 221
 222        return -EFAULT;
 223}
 224
 225BPF_CALL_2(bpf_skb_load_helper_16_no_cache, const struct sk_buff *, skb,
 226           int, offset)
 227{
 228        return ____bpf_skb_load_helper_16(skb, skb->data, skb->len - skb->data_len,
 229                                          offset);
 230}
 231
 232BPF_CALL_4(bpf_skb_load_helper_32, const struct sk_buff *, skb, const void *,
 233           data, int, headlen, int, offset)
 234{
 235        u32 tmp, *ptr;
 236        const int len = sizeof(tmp);
 237
 238        if (likely(offset >= 0)) {
 239                if (headlen - offset >= len)
 240                        return get_unaligned_be32(data + offset);
 241                if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
 242                        return be32_to_cpu(tmp);
 243        } else {
 244                ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
 245                if (likely(ptr))
 246                        return get_unaligned_be32(ptr);
 247        }
 248
 249        return -EFAULT;
 250}
 251
 252BPF_CALL_2(bpf_skb_load_helper_32_no_cache, const struct sk_buff *, skb,
 253           int, offset)
 254{
 255        return ____bpf_skb_load_helper_32(skb, skb->data, skb->len - skb->data_len,
 256                                          offset);
 257}
 258
 259BPF_CALL_0(bpf_get_raw_cpu_id)
 260{
 261        return raw_smp_processor_id();
 262}
 263
 264static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
 265        .func           = bpf_get_raw_cpu_id,
 266        .gpl_only       = false,
 267        .ret_type       = RET_INTEGER,
 268};
 269
 270static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
 271                              struct bpf_insn *insn_buf)
 272{
 273        struct bpf_insn *insn = insn_buf;
 274
 275        switch (skb_field) {
 276        case SKF_AD_MARK:
 277                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);
 278
 279                *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
 280                                      offsetof(struct sk_buff, mark));
 281                break;
 282
 283        case SKF_AD_PKTTYPE:
 284                *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET());
 285                *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
 286#ifdef __BIG_ENDIAN_BITFIELD
 287                *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
 288#endif
 289                break;
 290
 291        case SKF_AD_QUEUE:
 292                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2);
 293
 294                *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
 295                                      offsetof(struct sk_buff, queue_mapping));
 296                break;
 297
 298        case SKF_AD_VLAN_TAG:
 299                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_tci) != 2);
 300
 301                /* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
 302                *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
 303                                      offsetof(struct sk_buff, vlan_tci));
 304                break;
 305        case SKF_AD_VLAN_TAG_PRESENT:
 306                *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_VLAN_PRESENT_OFFSET());
 307                if (PKT_VLAN_PRESENT_BIT)
 308                        *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, PKT_VLAN_PRESENT_BIT);
 309                if (PKT_VLAN_PRESENT_BIT < 7)
 310                        *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1);
 311                break;
 312        }
 313
 314        return insn - insn_buf;
 315}
 316
 317static bool convert_bpf_extensions(struct sock_filter *fp,
 318                                   struct bpf_insn **insnp)
 319{
 320        struct bpf_insn *insn = *insnp;
 321        u32 cnt;
 322
 323        switch (fp->k) {
 324        case SKF_AD_OFF + SKF_AD_PROTOCOL:
 325                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);
 326
 327                /* A = *(u16 *) (CTX + offsetof(protocol)) */
 328                *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
 329                                      offsetof(struct sk_buff, protocol));
 330                /* A = ntohs(A) [emitting a nop or swap16] */
 331                *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
 332                break;
 333
 334        case SKF_AD_OFF + SKF_AD_PKTTYPE:
 335                cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
 336                insn += cnt - 1;
 337                break;
 338
 339        case SKF_AD_OFF + SKF_AD_IFINDEX:
 340        case SKF_AD_OFF + SKF_AD_HATYPE:
 341                BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
 342                BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, type) != 2);
 343
 344                *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
 345                                      BPF_REG_TMP, BPF_REG_CTX,
 346                                      offsetof(struct sk_buff, dev));
 347                /* if (tmp != 0) goto pc + 1 */
 348                *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
 349                *insn++ = BPF_EXIT_INSN();
 350                if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
 351                        *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
 352                                            offsetof(struct net_device, ifindex));
 353                else
 354                        *insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
 355                                            offsetof(struct net_device, type));
 356                break;
 357
 358        case SKF_AD_OFF + SKF_AD_MARK:
 359                cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
 360                insn += cnt - 1;
 361                break;
 362
 363        case SKF_AD_OFF + SKF_AD_RXHASH:
 364                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);
 365
 366                *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
 367                                    offsetof(struct sk_buff, hash));
 368                break;
 369
 370        case SKF_AD_OFF + SKF_AD_QUEUE:
 371                cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
 372                insn += cnt - 1;
 373                break;
 374
 375        case SKF_AD_OFF + SKF_AD_VLAN_TAG:
 376                cnt = convert_skb_access(SKF_AD_VLAN_TAG,
 377                                         BPF_REG_A, BPF_REG_CTX, insn);
 378                insn += cnt - 1;
 379                break;
 380
 381        case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
 382                cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
 383                                         BPF_REG_A, BPF_REG_CTX, insn);
 384                insn += cnt - 1;
 385                break;
 386
 387        case SKF_AD_OFF + SKF_AD_VLAN_TPID:
 388                BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);
 389
 390                /* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
 391                *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
 392                                      offsetof(struct sk_buff, vlan_proto));
 393                /* A = ntohs(A) [emitting a nop or swap16] */
 394                *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
 395                break;
 396
 397        case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
 398        case SKF_AD_OFF + SKF_AD_NLATTR:
 399        case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
 400        case SKF_AD_OFF + SKF_AD_CPU:
 401        case SKF_AD_OFF + SKF_AD_RANDOM:
 402                /* arg1 = CTX */
 403                *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
 404                /* arg2 = A */
 405                *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
 406                /* arg3 = X */
 407                *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
 408                /* Emit call(arg1=CTX, arg2=A, arg3=X) */
 409                switch (fp->k) {
 410                case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
 411                        *insn = BPF_EMIT_CALL(bpf_skb_get_pay_offset);
 412                        break;
 413                case SKF_AD_OFF + SKF_AD_NLATTR:
 414                        *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr);
 415                        break;
 416                case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
 417                        *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr_nest);
 418                        break;
 419                case SKF_AD_OFF + SKF_AD_CPU:
 420                        *insn = BPF_EMIT_CALL(bpf_get_raw_cpu_id);
 421                        break;
 422                case SKF_AD_OFF + SKF_AD_RANDOM:
 423                        *insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
 424                        bpf_user_rnd_init_once();
 425                        break;
 426                }
 427                break;
 428
 429        case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
 430                /* A ^= X */
 431                *insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
 432                break;
 433
 434        default:
 435                /* This is just a dummy call to avoid letting the compiler
 436                 * evict __bpf_call_base() as an optimization. Placed here
 437                 * where no-one bothers.
 438                 */
 439                BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
 440                return false;
 441        }
 442
 443        *insnp = insn;
 444        return true;
 445}
 446
 447static bool convert_bpf_ld_abs(struct sock_filter *fp, struct bpf_insn **insnp)
 448{
 449        const bool unaligned_ok = IS_BUILTIN(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS);
 450        int size = bpf_size_to_bytes(BPF_SIZE(fp->code));
 451        bool endian = BPF_SIZE(fp->code) == BPF_H ||
 452                      BPF_SIZE(fp->code) == BPF_W;
 453        bool indirect = BPF_MODE(fp->code) == BPF_IND;
 454        const int ip_align = NET_IP_ALIGN;
 455        struct bpf_insn *insn = *insnp;
 456        int offset = fp->k;
 457
 458        if (!indirect &&
 459            ((unaligned_ok && offset >= 0) ||
 460             (!unaligned_ok && offset >= 0 &&
 461              offset + ip_align >= 0 &&
 462              offset + ip_align % size == 0))) {
 463                bool ldx_off_ok = offset <= S16_MAX;
 464
 465                *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_H);
 466                if (offset)
 467                        *insn++ = BPF_ALU64_IMM(BPF_SUB, BPF_REG_TMP, offset);
 468                *insn++ = BPF_JMP_IMM(BPF_JSLT, BPF_REG_TMP,
 469                                      size, 2 + endian + (!ldx_off_ok * 2));
 470                if (ldx_off_ok) {
 471                        *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
 472                                              BPF_REG_D, offset);
 473                } else {
 474                        *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_D);
 475                        *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_TMP, offset);
 476                        *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
 477                                              BPF_REG_TMP, 0);
 478                }
 479                if (endian)
 480                        *insn++ = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, size * 8);
 481                *insn++ = BPF_JMP_A(8);
 482        }
 483
 484        *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
 485        *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_D);
 486        *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_H);
 487        if (!indirect) {
 488                *insn++ = BPF_MOV64_IMM(BPF_REG_ARG4, offset);
 489        } else {
 490                *insn++ = BPF_MOV64_REG(BPF_REG_ARG4, BPF_REG_X);
 491                if (fp->k)
 492                        *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_ARG4, offset);
 493        }
 494
 495        switch (BPF_SIZE(fp->code)) {
 496        case BPF_B:
 497                *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8);
 498                break;
 499        case BPF_H:
 500                *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16);
 501                break;
 502        case BPF_W:
 503                *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32);
 504                break;
 505        default:
 506                return false;
 507        }
 508
 509        *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_A, 0, 2);
 510        *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
 511        *insn   = BPF_EXIT_INSN();
 512
 513        *insnp = insn;
 514        return true;
 515}
 516
 517/**
 518 *      bpf_convert_filter - convert filter program
 519 *      @prog: the user passed filter program
 520 *      @len: the length of the user passed filter program
 521 *      @new_prog: allocated 'struct bpf_prog' or NULL
 522 *      @new_len: pointer to store length of converted program
 523 *      @seen_ld_abs: bool whether we've seen ld_abs/ind
 524 *
 525 * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
 526 * style extended BPF (eBPF).
 527 * Conversion workflow:
 528 *
 529 * 1) First pass for calculating the new program length:
 530 *   bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs)
 531 *
 532 * 2) 2nd pass to remap in two passes: 1st pass finds new
 533 *    jump offsets, 2nd pass remapping:
 534 *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len, &seen_ld_abs)
 535 */
 536static int bpf_convert_filter(struct sock_filter *prog, int len,
 537                              struct bpf_prog *new_prog, int *new_len,
 538                              bool *seen_ld_abs)
 539{
 540        int new_flen = 0, pass = 0, target, i, stack_off;
 541        struct bpf_insn *new_insn, *first_insn = NULL;
 542        struct sock_filter *fp;
 543        int *addrs = NULL;
 544        u8 bpf_src;
 545
 546        BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
 547        BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
 548
 549        if (len <= 0 || len > BPF_MAXINSNS)
 550                return -EINVAL;
 551
 552        if (new_prog) {
 553                first_insn = new_prog->insnsi;
 554                addrs = kcalloc(len, sizeof(*addrs),
 555                                GFP_KERNEL | __GFP_NOWARN);
 556                if (!addrs)
 557                        return -ENOMEM;
 558        }
 559
 560do_pass:
 561        new_insn = first_insn;
 562        fp = prog;
 563
 564        /* Classic BPF related prologue emission. */
 565        if (new_prog) {
 566                /* Classic BPF expects A and X to be reset first. These need
 567                 * to be guaranteed to be the first two instructions.
 568                 */
 569                *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
 570                *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
 571
 572                /* All programs must keep CTX in callee saved BPF_REG_CTX.
 573                 * In eBPF case it's done by the compiler, here we need to
 574                 * do this ourself. Initial CTX is present in BPF_REG_ARG1.
 575                 */
 576                *new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
 577                if (*seen_ld_abs) {
 578                        /* For packet access in classic BPF, cache skb->data
 579                         * in callee-saved BPF R8 and skb->len - skb->data_len
 580                         * (headlen) in BPF R9. Since classic BPF is read-only
 581                         * on CTX, we only need to cache it once.
 582                         */
 583                        *new_insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
 584                                                  BPF_REG_D, BPF_REG_CTX,
 585                                                  offsetof(struct sk_buff, data));
 586                        *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_H, BPF_REG_CTX,
 587                                                  offsetof(struct sk_buff, len));
 588                        *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_TMP, BPF_REG_CTX,
 589                                                  offsetof(struct sk_buff, data_len));
 590                        *new_insn++ = BPF_ALU32_REG(BPF_SUB, BPF_REG_H, BPF_REG_TMP);
 591                }
 592        } else {
 593                new_insn += 3;
 594        }
 595
 596        for (i = 0; i < len; fp++, i++) {
 597                struct bpf_insn tmp_insns[32] = { };
 598                struct bpf_insn *insn = tmp_insns;
 599
 600                if (addrs)
 601                        addrs[i] = new_insn - first_insn;
 602
 603                switch (fp->code) {
 604                /* All arithmetic insns and skb loads map as-is. */
 605                case BPF_ALU | BPF_ADD | BPF_X:
 606                case BPF_ALU | BPF_ADD | BPF_K:
 607                case BPF_ALU | BPF_SUB | BPF_X:
 608                case BPF_ALU | BPF_SUB | BPF_K:
 609                case BPF_ALU | BPF_AND | BPF_X:
 610                case BPF_ALU | BPF_AND | BPF_K:
 611                case BPF_ALU | BPF_OR | BPF_X:
 612                case BPF_ALU | BPF_OR | BPF_K:
 613                case BPF_ALU | BPF_LSH | BPF_X:
 614                case BPF_ALU | BPF_LSH | BPF_K:
 615                case BPF_ALU | BPF_RSH | BPF_X:
 616                case BPF_ALU | BPF_RSH | BPF_K:
 617                case BPF_ALU | BPF_XOR | BPF_X:
 618                case BPF_ALU | BPF_XOR | BPF_K:
 619                case BPF_ALU | BPF_MUL | BPF_X:
 620                case BPF_ALU | BPF_MUL | BPF_K:
 621                case BPF_ALU | BPF_DIV | BPF_X:
 622                case BPF_ALU | BPF_DIV | BPF_K:
 623                case BPF_ALU | BPF_MOD | BPF_X:
 624                case BPF_ALU | BPF_MOD | BPF_K:
 625                case BPF_ALU | BPF_NEG:
 626                case BPF_LD | BPF_ABS | BPF_W:
 627                case BPF_LD | BPF_ABS | BPF_H:
 628                case BPF_LD | BPF_ABS | BPF_B:
 629                case BPF_LD | BPF_IND | BPF_W:
 630                case BPF_LD | BPF_IND | BPF_H:
 631                case BPF_LD | BPF_IND | BPF_B:
 632                        /* Check for overloaded BPF extension and
 633                         * directly convert it if found, otherwise
 634                         * just move on with mapping.
 635                         */
 636                        if (BPF_CLASS(fp->code) == BPF_LD &&
 637                            BPF_MODE(fp->code) == BPF_ABS &&
 638                            convert_bpf_extensions(fp, &insn))
 639                                break;
 640                        if (BPF_CLASS(fp->code) == BPF_LD &&
 641                            convert_bpf_ld_abs(fp, &insn)) {
 642                                *seen_ld_abs = true;
 643                                break;
 644                        }
 645
 646                        if (fp->code == (BPF_ALU | BPF_DIV | BPF_X) ||
 647                            fp->code == (BPF_ALU | BPF_MOD | BPF_X)) {
 648                                *insn++ = BPF_MOV32_REG(BPF_REG_X, BPF_REG_X);
 649                                /* Error with exception code on div/mod by 0.
 650                                 * For cBPF programs, this was always return 0.
 651                                 */
 652                                *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_X, 0, 2);
 653                                *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
 654                                *insn++ = BPF_EXIT_INSN();
 655                        }
 656
 657                        *insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
 658                        break;
 659
 660                /* Jump transformation cannot use BPF block macros
 661                 * everywhere as offset calculation and target updates
 662                 * require a bit more work than the rest, i.e. jump
 663                 * opcodes map as-is, but offsets need adjustment.
 664                 */
 665
 666#define BPF_EMIT_JMP                                                    \
 667        do {                                                            \
 668                const s32 off_min = S16_MIN, off_max = S16_MAX;         \
 669                s32 off;                                                \
 670                                                                        \
 671                if (target >= len || target < 0)                        \
 672                        goto err;                                       \
 673                off = addrs ? addrs[target] - addrs[i] - 1 : 0;         \
 674                /* Adjust pc relative offset for 2nd or 3rd insn. */    \
 675                off -= insn - tmp_insns;                                \
 676                /* Reject anything not fitting into insn->off. */       \
 677                if (off < off_min || off > off_max)                     \
 678                        goto err;                                       \
 679                insn->off = off;                                        \
 680        } while (0)
 681
 682                case BPF_JMP | BPF_JA:
 683                        target = i + fp->k + 1;
 684                        insn->code = fp->code;
 685                        BPF_EMIT_JMP;
 686                        break;
 687
 688                case BPF_JMP | BPF_JEQ | BPF_K:
 689                case BPF_JMP | BPF_JEQ | BPF_X:
 690                case BPF_JMP | BPF_JSET | BPF_K:
 691                case BPF_JMP | BPF_JSET | BPF_X:
 692                case BPF_JMP | BPF_JGT | BPF_K:
 693                case BPF_JMP | BPF_JGT | BPF_X:
 694                case BPF_JMP | BPF_JGE | BPF_K:
 695                case BPF_JMP | BPF_JGE | BPF_X:
 696                        if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
 697                                /* BPF immediates are signed, zero extend
 698                                 * immediate into tmp register and use it
 699                                 * in compare insn.
 700                                 */
 701                                *insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
 702
 703                                insn->dst_reg = BPF_REG_A;
 704                                insn->src_reg = BPF_REG_TMP;
 705                                bpf_src = BPF_X;
 706                        } else {
 707                                insn->dst_reg = BPF_REG_A;
 708                                insn->imm = fp->k;
 709                                bpf_src = BPF_SRC(fp->code);
 710                                insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
 711                        }
 712
 713                        /* Common case where 'jump_false' is next insn. */
 714                        if (fp->jf == 0) {
 715                                insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
 716                                target = i + fp->jt + 1;
 717                                BPF_EMIT_JMP;
 718                                break;
 719                        }
 720
 721                        /* Convert some jumps when 'jump_true' is next insn. */
 722                        if (fp->jt == 0) {
 723                                switch (BPF_OP(fp->code)) {
 724                                case BPF_JEQ:
 725                                        insn->code = BPF_JMP | BPF_JNE | bpf_src;
 726                                        break;
 727                                case BPF_JGT:
 728                                        insn->code = BPF_JMP | BPF_JLE | bpf_src;
 729                                        break;
 730                                case BPF_JGE:
 731                                        insn->code = BPF_JMP | BPF_JLT | bpf_src;
 732                                        break;
 733                                default:
 734                                        goto jmp_rest;
 735                                }
 736
 737                                target = i + fp->jf + 1;
 738                                BPF_EMIT_JMP;
 739                                break;
 740                        }
 741jmp_rest:
 742                        /* Other jumps are mapped into two insns: Jxx and JA. */
 743                        target = i + fp->jt + 1;
 744                        insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
 745                        BPF_EMIT_JMP;
 746                        insn++;
 747
 748                        insn->code = BPF_JMP | BPF_JA;
 749                        target = i + fp->jf + 1;
 750                        BPF_EMIT_JMP;
 751                        break;
 752
 753                /* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
 754                case BPF_LDX | BPF_MSH | BPF_B: {
 755                        struct sock_filter tmp = {
 756                                .code   = BPF_LD | BPF_ABS | BPF_B,
 757                                .k      = fp->k,
 758                        };
 759
 760                        *seen_ld_abs = true;
 761
 762                        /* X = A */
 763                        *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
 764                        /* A = BPF_R0 = *(u8 *) (skb->data + K) */
 765                        convert_bpf_ld_abs(&tmp, &insn);
 766                        insn++;
 767                        /* A &= 0xf */
 768                        *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
 769                        /* A <<= 2 */
 770                        *insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
 771                        /* tmp = X */
 772                        *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_X);
 773                        /* X = A */
 774                        *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
 775                        /* A = tmp */
 776                        *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
 777                        break;
 778                }
 779                /* RET_K is remaped into 2 insns. RET_A case doesn't need an
 780                 * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
 781                 */
 782                case BPF_RET | BPF_A:
 783                case BPF_RET | BPF_K:
 784                        if (BPF_RVAL(fp->code) == BPF_K)
 785                                *insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
 786                                                        0, fp->k);
 787                        *insn = BPF_EXIT_INSN();
 788                        break;
 789
 790                /* Store to stack. */
 791                case BPF_ST:
 792                case BPF_STX:
 793                        stack_off = fp->k * 4  + 4;
 794                        *insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
 795                                            BPF_ST ? BPF_REG_A : BPF_REG_X,
 796                                            -stack_off);
 797                        /* check_load_and_stores() verifies that classic BPF can
 798                         * load from stack only after write, so tracking
 799                         * stack_depth for ST|STX insns is enough
 800                         */
 801                        if (new_prog && new_prog->aux->stack_depth < stack_off)
 802                                new_prog->aux->stack_depth = stack_off;
 803                        break;
 804
 805                /* Load from stack. */
 806                case BPF_LD | BPF_MEM:
 807                case BPF_LDX | BPF_MEM:
 808                        stack_off = fp->k * 4  + 4;
 809                        *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
 810                                            BPF_REG_A : BPF_REG_X, BPF_REG_FP,
 811                                            -stack_off);
 812                        break;
 813
 814                /* A = K or X = K */
 815                case BPF_LD | BPF_IMM:
 816                case BPF_LDX | BPF_IMM:
 817                        *insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
 818                                              BPF_REG_A : BPF_REG_X, fp->k);
 819                        break;
 820
 821                /* X = A */
 822                case BPF_MISC | BPF_TAX:
 823                        *insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
 824                        break;
 825
 826                /* A = X */
 827                case BPF_MISC | BPF_TXA:
 828                        *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
 829                        break;
 830
 831                /* A = skb->len or X = skb->len */
 832                case BPF_LD | BPF_W | BPF_LEN:
 833                case BPF_LDX | BPF_W | BPF_LEN:
 834                        *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
 835                                            BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
 836                                            offsetof(struct sk_buff, len));
 837                        break;
 838
 839                /* Access seccomp_data fields. */
 840                case BPF_LDX | BPF_ABS | BPF_W:
 841                        /* A = *(u32 *) (ctx + K) */
 842                        *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
 843                        break;
 844
 845                /* Unknown instruction. */
 846                default:
 847                        goto err;
 848                }
 849
 850                insn++;
 851                if (new_prog)
 852                        memcpy(new_insn, tmp_insns,
 853                               sizeof(*insn) * (insn - tmp_insns));
 854                new_insn += insn - tmp_insns;
 855        }
 856
 857        if (!new_prog) {
 858                /* Only calculating new length. */
 859                *new_len = new_insn - first_insn;
 860                if (*seen_ld_abs)
 861                        *new_len += 4; /* Prologue bits. */
 862                return 0;
 863        }
 864
 865        pass++;
 866        if (new_flen != new_insn - first_insn) {
 867                new_flen = new_insn - first_insn;
 868                if (pass > 2)
 869                        goto err;
 870                goto do_pass;
 871        }
 872
 873        kfree(addrs);
 874        BUG_ON(*new_len != new_flen);
 875        return 0;
 876err:
 877        kfree(addrs);
 878        return -EINVAL;
 879}
 880
 881/* Security:
 882 *
 883 * As we dont want to clear mem[] array for each packet going through
 884 * __bpf_prog_run(), we check that filter loaded by user never try to read
 885 * a cell if not previously written, and we check all branches to be sure
 886 * a malicious user doesn't try to abuse us.
 887 */
 888static int check_load_and_stores(const struct sock_filter *filter, int flen)
 889{
 890        u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
 891        int pc, ret = 0;
 892
 893        BUILD_BUG_ON(BPF_MEMWORDS > 16);
 894
 895        masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
 896        if (!masks)
 897                return -ENOMEM;
 898
 899        memset(masks, 0xff, flen * sizeof(*masks));
 900
 901        for (pc = 0; pc < flen; pc++) {
 902                memvalid &= masks[pc];
 903
 904                switch (filter[pc].code) {
 905                case BPF_ST:
 906                case BPF_STX:
 907                        memvalid |= (1 << filter[pc].k);
 908                        break;
 909                case BPF_LD | BPF_MEM:
 910                case BPF_LDX | BPF_MEM:
 911                        if (!(memvalid & (1 << filter[pc].k))) {
 912                                ret = -EINVAL;
 913                                goto error;
 914                        }
 915                        break;
 916                case BPF_JMP | BPF_JA:
 917                        /* A jump must set masks on target */
 918                        masks[pc + 1 + filter[pc].k] &= memvalid;
 919                        memvalid = ~0;
 920                        break;
 921                case BPF_JMP | BPF_JEQ | BPF_K:
 922                case BPF_JMP | BPF_JEQ | BPF_X:
 923                case BPF_JMP | BPF_JGE | BPF_K:
 924                case BPF_JMP | BPF_JGE | BPF_X:
 925                case BPF_JMP | BPF_JGT | BPF_K:
 926                case BPF_JMP | BPF_JGT | BPF_X:
 927                case BPF_JMP | BPF_JSET | BPF_K:
 928                case BPF_JMP | BPF_JSET | BPF_X:
 929                        /* A jump must set masks on targets */
 930                        masks[pc + 1 + filter[pc].jt] &= memvalid;
 931                        masks[pc + 1 + filter[pc].jf] &= memvalid;
 932                        memvalid = ~0;
 933                        break;
 934                }
 935        }
 936error:
 937        kfree(masks);
 938        return ret;
 939}
 940
 941static bool chk_code_allowed(u16 code_to_probe)
 942{
 943        static const bool codes[] = {
 944                /* 32 bit ALU operations */
 945                [BPF_ALU | BPF_ADD | BPF_K] = true,
 946                [BPF_ALU | BPF_ADD | BPF_X] = true,
 947                [BPF_ALU | BPF_SUB | BPF_K] = true,
 948                [BPF_ALU | BPF_SUB | BPF_X] = true,
 949                [BPF_ALU | BPF_MUL | BPF_K] = true,
 950                [BPF_ALU | BPF_MUL | BPF_X] = true,
 951                [BPF_ALU | BPF_DIV | BPF_K] = true,
 952                [BPF_ALU | BPF_DIV | BPF_X] = true,
 953                [BPF_ALU | BPF_MOD | BPF_K] = true,
 954                [BPF_ALU | BPF_MOD | BPF_X] = true,
 955                [BPF_ALU | BPF_AND | BPF_K] = true,
 956                [BPF_ALU | BPF_AND | BPF_X] = true,
 957                [BPF_ALU | BPF_OR | BPF_K] = true,
 958                [BPF_ALU | BPF_OR | BPF_X] = true,
 959                [BPF_ALU | BPF_XOR | BPF_K] = true,
 960                [BPF_ALU | BPF_XOR | BPF_X] = true,
 961                [BPF_ALU | BPF_LSH | BPF_K] = true,
 962                [BPF_ALU | BPF_LSH | BPF_X] = true,
 963                [BPF_ALU | BPF_RSH | BPF_K] = true,
 964                [BPF_ALU | BPF_RSH | BPF_X] = true,
 965                [BPF_ALU | BPF_NEG] = true,
 966                /* Load instructions */
 967                [BPF_LD | BPF_W | BPF_ABS] = true,
 968                [BPF_LD | BPF_H | BPF_ABS] = true,
 969                [BPF_LD | BPF_B | BPF_ABS] = true,
 970                [BPF_LD | BPF_W | BPF_LEN] = true,
 971                [BPF_LD | BPF_W | BPF_IND] = true,
 972                [BPF_LD | BPF_H | BPF_IND] = true,
 973                [BPF_LD | BPF_B | BPF_IND] = true,
 974                [BPF_LD | BPF_IMM] = true,
 975                [BPF_LD | BPF_MEM] = true,
 976                [BPF_LDX | BPF_W | BPF_LEN] = true,
 977                [BPF_LDX | BPF_B | BPF_MSH] = true,
 978                [BPF_LDX | BPF_IMM] = true,
 979                [BPF_LDX | BPF_MEM] = true,
 980                /* Store instructions */
 981                [BPF_ST] = true,
 982                [BPF_STX] = true,
 983                /* Misc instructions */
 984                [BPF_MISC | BPF_TAX] = true,
 985                [BPF_MISC | BPF_TXA] = true,
 986                /* Return instructions */
 987                [BPF_RET | BPF_K] = true,
 988                [BPF_RET | BPF_A] = true,
 989                /* Jump instructions */
 990                [BPF_JMP | BPF_JA] = true,
 991                [BPF_JMP | BPF_JEQ | BPF_K] = true,
 992                [BPF_JMP | BPF_JEQ | BPF_X] = true,
 993                [BPF_JMP | BPF_JGE | BPF_K] = true,
 994                [BPF_JMP | BPF_JGE | BPF_X] = true,
 995                [BPF_JMP | BPF_JGT | BPF_K] = true,
 996                [BPF_JMP | BPF_JGT | BPF_X] = true,
 997                [BPF_JMP | BPF_JSET | BPF_K] = true,
 998                [BPF_JMP | BPF_JSET | BPF_X] = true,
 999        };
1000
1001        if (code_to_probe >= ARRAY_SIZE(codes))
1002                return false;
1003
1004        return codes[code_to_probe];
1005}
1006
1007static bool bpf_check_basics_ok(const struct sock_filter *filter,
1008                                unsigned int flen)
1009{
1010        if (filter == NULL)
1011                return false;
1012        if (flen == 0 || flen > BPF_MAXINSNS)
1013                return false;
1014
1015        return true;
1016}
1017
1018/**
1019 *      bpf_check_classic - verify socket filter code
1020 *      @filter: filter to verify
1021 *      @flen: length of filter
1022 *
1023 * Check the user's filter code. If we let some ugly
1024 * filter code slip through kaboom! The filter must contain
1025 * no references or jumps that are out of range, no illegal
1026 * instructions, and must end with a RET instruction.
1027 *
1028 * All jumps are forward as they are not signed.
1029 *
1030 * Returns 0 if the rule set is legal or -EINVAL if not.
1031 */
1032static int bpf_check_classic(const struct sock_filter *filter,
1033                             unsigned int flen)
1034{
1035        bool anc_found;
1036        int pc;
1037
1038        /* Check the filter code now */
1039        for (pc = 0; pc < flen; pc++) {
1040                const struct sock_filter *ftest = &filter[pc];
1041
1042                /* May we actually operate on this code? */
1043                if (!chk_code_allowed(ftest->code))
1044                        return -EINVAL;
1045
1046                /* Some instructions need special checks */
1047                switch (ftest->code) {
1048                case BPF_ALU | BPF_DIV | BPF_K:
1049                case BPF_ALU | BPF_MOD | BPF_K:
1050                        /* Check for division by zero */
1051                        if (ftest->k == 0)
1052                                return -EINVAL;
1053                        break;
1054                case BPF_ALU | BPF_LSH | BPF_K:
1055                case BPF_ALU | BPF_RSH | BPF_K:
1056                        if (ftest->k >= 32)
1057                                return -EINVAL;
1058                        break;
1059                case BPF_LD | BPF_MEM:
1060                case BPF_LDX | BPF_MEM:
1061                case BPF_ST:
1062                case BPF_STX:
1063                        /* Check for invalid memory addresses */
1064                        if (ftest->k >= BPF_MEMWORDS)
1065                                return -EINVAL;
1066                        break;
1067                case BPF_JMP | BPF_JA:
1068                        /* Note, the large ftest->k might cause loops.
1069                         * Compare this with conditional jumps below,
1070                         * where offsets are limited. --ANK (981016)
1071                         */
1072                        if (ftest->k >= (unsigned int)(flen - pc - 1))
1073                                return -EINVAL;
1074                        break;
1075                case BPF_JMP | BPF_JEQ | BPF_K:
1076                case BPF_JMP | BPF_JEQ | BPF_X:
1077                case BPF_JMP | BPF_JGE | BPF_K:
1078                case BPF_JMP | BPF_JGE | BPF_X:
1079                case BPF_JMP | BPF_JGT | BPF_K:
1080                case BPF_JMP | BPF_JGT | BPF_X:
1081                case BPF_JMP | BPF_JSET | BPF_K:
1082                case BPF_JMP | BPF_JSET | BPF_X:
1083                        /* Both conditionals must be safe */
1084                        if (pc + ftest->jt + 1 >= flen ||
1085                            pc + ftest->jf + 1 >= flen)
1086                                return -EINVAL;
1087                        break;
1088                case BPF_LD | BPF_W | BPF_ABS:
1089                case BPF_LD | BPF_H | BPF_ABS:
1090                case BPF_LD | BPF_B | BPF_ABS:
1091                        anc_found = false;
1092                        if (bpf_anc_helper(ftest) & BPF_ANC)
1093                                anc_found = true;
1094                        /* Ancillary operation unknown or unsupported */
1095                        if (anc_found == false && ftest->k >= SKF_AD_OFF)
1096                                return -EINVAL;
1097                }
1098        }
1099
1100        /* Last instruction must be a RET code */
1101        switch (filter[flen - 1].code) {
1102        case BPF_RET | BPF_K:
1103        case BPF_RET | BPF_A:
1104                return check_load_and_stores(filter, flen);
1105        }
1106
1107        return -EINVAL;
1108}
1109
1110static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
1111                                      const struct sock_fprog *fprog)
1112{
1113        unsigned int fsize = bpf_classic_proglen(fprog);
1114        struct sock_fprog_kern *fkprog;
1115
1116        fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
1117        if (!fp->orig_prog)
1118                return -ENOMEM;
1119
1120        fkprog = fp->orig_prog;
1121        fkprog->len = fprog->len;
1122
1123        fkprog->filter = kmemdup(fp->insns, fsize,
1124                                 GFP_KERNEL | __GFP_NOWARN);
1125        if (!fkprog->filter) {
1126                kfree(fp->orig_prog);
1127                return -ENOMEM;
1128        }
1129
1130        return 0;
1131}
1132
1133static void bpf_release_orig_filter(struct bpf_prog *fp)
1134{
1135        struct sock_fprog_kern *fprog = fp->orig_prog;
1136
1137        if (fprog) {
1138                kfree(fprog->filter);
1139                kfree(fprog);
1140        }
1141}
1142
1143static void __bpf_prog_release(struct bpf_prog *prog)
1144{
1145        if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
1146                bpf_prog_put(prog);
1147        } else {
1148                bpf_release_orig_filter(prog);
1149                bpf_prog_free(prog);
1150        }
1151}
1152
1153static void __sk_filter_release(struct sk_filter *fp)
1154{
1155        __bpf_prog_release(fp->prog);
1156        kfree(fp);
1157}
1158
1159/**
1160 *      sk_filter_release_rcu - Release a socket filter by rcu_head
1161 *      @rcu: rcu_head that contains the sk_filter to free
1162 */
1163static void sk_filter_release_rcu(struct rcu_head *rcu)
1164{
1165        struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
1166
1167        __sk_filter_release(fp);
1168}
1169
1170/**
1171 *      sk_filter_release - release a socket filter
1172 *      @fp: filter to remove
1173 *
1174 *      Remove a filter from a socket and release its resources.
1175 */
1176static void sk_filter_release(struct sk_filter *fp)
1177{
1178        if (refcount_dec_and_test(&fp->refcnt))
1179                call_rcu(&fp->rcu, sk_filter_release_rcu);
1180}
1181
1182void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
1183{
1184        u32 filter_size = bpf_prog_size(fp->prog->len);
1185
1186        atomic_sub(filter_size, &sk->sk_omem_alloc);
1187        sk_filter_release(fp);
1188}
1189
1190/* try to charge the socket memory if there is space available
1191 * return true on success
1192 */
1193static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1194{
1195        u32 filter_size = bpf_prog_size(fp->prog->len);
1196
1197        /* same check as in sock_kmalloc() */
1198        if (filter_size <= sysctl_optmem_max &&
1199            atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
1200                atomic_add(filter_size, &sk->sk_omem_alloc);
1201                return true;
1202        }
1203        return false;
1204}
1205
1206bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1207{
1208        if (!refcount_inc_not_zero(&fp->refcnt))
1209                return false;
1210
1211        if (!__sk_filter_charge(sk, fp)) {
1212                sk_filter_release(fp);
1213                return false;
1214        }
1215        return true;
1216}
1217
1218static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
1219{
1220        struct sock_filter *old_prog;
1221        struct bpf_prog *old_fp;
1222        int err, new_len, old_len = fp->len;
1223        bool seen_ld_abs = false;
1224
1225        /* We are free to overwrite insns et al right here as it
1226         * won't be used at this point in time anymore internally
1227         * after the migration to the internal BPF instruction
1228         * representation.
1229         */
1230        BUILD_BUG_ON(sizeof(struct sock_filter) !=
1231                     sizeof(struct bpf_insn));
1232
1233        /* Conversion cannot happen on overlapping memory areas,
1234         * so we need to keep the user BPF around until the 2nd
1235         * pass. At this time, the user BPF is stored in fp->insns.
1236         */
1237        old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
1238                           GFP_KERNEL | __GFP_NOWARN);
1239        if (!old_prog) {
1240                err = -ENOMEM;
1241                goto out_err;
1242        }
1243
1244        /* 1st pass: calculate the new program length. */
1245        err = bpf_convert_filter(old_prog, old_len, NULL, &new_len,
1246                                 &seen_ld_abs);
1247        if (err)
1248                goto out_err_free;
1249
1250        /* Expand fp for appending the new filter representation. */
1251        old_fp = fp;
1252        fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1253        if (!fp) {
1254                /* The old_fp is still around in case we couldn't
1255                 * allocate new memory, so uncharge on that one.
1256                 */
1257                fp = old_fp;
1258                err = -ENOMEM;
1259                goto out_err_free;
1260        }
1261
1262        fp->len = new_len;
1263
1264        /* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1265        err = bpf_convert_filter(old_prog, old_len, fp, &new_len,
1266                                 &seen_ld_abs);
1267        if (err)
1268                /* 2nd bpf_convert_filter() can fail only if it fails
1269                 * to allocate memory, remapping must succeed. Note,
1270                 * that at this time old_fp has already been released
1271                 * by krealloc().
1272                 */
1273                goto out_err_free;
1274
1275        fp = bpf_prog_select_runtime(fp, &err);
1276        if (err)
1277                goto out_err_free;
1278
1279        kfree(old_prog);
1280        return fp;
1281
1282out_err_free:
1283        kfree(old_prog);
1284out_err:
1285        __bpf_prog_release(fp);
1286        return ERR_PTR(err);
1287}
1288
1289static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
1290                                           bpf_aux_classic_check_t trans)
1291{
1292        int err;
1293
1294        fp->bpf_func = NULL;
1295        fp->jited = 0;
1296
1297        err = bpf_check_classic(fp->insns, fp->len);
1298        if (err) {
1299                __bpf_prog_release(fp);
1300                return ERR_PTR(err);
1301        }
1302
1303        /* There might be additional checks and transformations
1304         * needed on classic filters, f.e. in case of seccomp.
1305         */
1306        if (trans) {
1307                err = trans(fp->insns, fp->len);
1308                if (err) {
1309                        __bpf_prog_release(fp);
1310                        return ERR_PTR(err);
1311                }
1312        }
1313
1314        /* Probe if we can JIT compile the filter and if so, do
1315         * the compilation of the filter.
1316         */
1317        bpf_jit_compile(fp);
1318
1319        /* JIT compiler couldn't process this filter, so do the
1320         * internal BPF translation for the optimized interpreter.
1321         */
1322        if (!fp->jited)
1323                fp = bpf_migrate_filter(fp);
1324
1325        return fp;
1326}
1327
1328/**
1329 *      bpf_prog_create - create an unattached filter
1330 *      @pfp: the unattached filter that is created
1331 *      @fprog: the filter program
1332 *
1333 * Create a filter independent of any socket. We first run some
1334 * sanity checks on it to make sure it does not explode on us later.
1335 * If an error occurs or there is insufficient memory for the filter
1336 * a negative errno code is returned. On success the return is zero.
1337 */
1338int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1339{
1340        unsigned int fsize = bpf_classic_proglen(fprog);
1341        struct bpf_prog *fp;
1342
1343        /* Make sure new filter is there and in the right amounts. */
1344        if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1345                return -EINVAL;
1346
1347        fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1348        if (!fp)
1349                return -ENOMEM;
1350
1351        memcpy(fp->insns, fprog->filter, fsize);
1352
1353        fp->len = fprog->len;
1354        /* Since unattached filters are not copied back to user
1355         * space through sk_get_filter(), we do not need to hold
1356         * a copy here, and can spare us the work.
1357         */
1358        fp->orig_prog = NULL;
1359
1360        /* bpf_prepare_filter() already takes care of freeing
1361         * memory in case something goes wrong.
1362         */
1363        fp = bpf_prepare_filter(fp, NULL);
1364        if (IS_ERR(fp))
1365                return PTR_ERR(fp);
1366
1367        *pfp = fp;
1368        return 0;
1369}
1370EXPORT_SYMBOL_GPL(bpf_prog_create);
1371
1372/**
1373 *      bpf_prog_create_from_user - create an unattached filter from user buffer
1374 *      @pfp: the unattached filter that is created
1375 *      @fprog: the filter program
1376 *      @trans: post-classic verifier transformation handler
1377 *      @save_orig: save classic BPF program
1378 *
1379 * This function effectively does the same as bpf_prog_create(), only
1380 * that it builds up its insns buffer from user space provided buffer.
1381 * It also allows for passing a bpf_aux_classic_check_t handler.
1382 */
1383int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1384                              bpf_aux_classic_check_t trans, bool save_orig)
1385{
1386        unsigned int fsize = bpf_classic_proglen(fprog);
1387        struct bpf_prog *fp;
1388        int err;
1389
1390        /* Make sure new filter is there and in the right amounts. */
1391        if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1392                return -EINVAL;
1393
1394        fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1395        if (!fp)
1396                return -ENOMEM;
1397
1398        if (copy_from_user(fp->insns, fprog->filter, fsize)) {
1399                __bpf_prog_free(fp);
1400                return -EFAULT;
1401        }
1402
1403        fp->len = fprog->len;
1404        fp->orig_prog = NULL;
1405
1406        if (save_orig) {
1407                err = bpf_prog_store_orig_filter(fp, fprog);
1408                if (err) {
1409                        __bpf_prog_free(fp);
1410                        return -ENOMEM;
1411                }
1412        }
1413
1414        /* bpf_prepare_filter() already takes care of freeing
1415         * memory in case something goes wrong.
1416         */
1417        fp = bpf_prepare_filter(fp, trans);
1418        if (IS_ERR(fp))
1419                return PTR_ERR(fp);
1420
1421        *pfp = fp;
1422        return 0;
1423}
1424EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1425
1426void bpf_prog_destroy(struct bpf_prog *fp)
1427{
1428        __bpf_prog_release(fp);
1429}
1430EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1431
1432static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1433{
1434        struct sk_filter *fp, *old_fp;
1435
1436        fp = kmalloc(sizeof(*fp), GFP_KERNEL);
1437        if (!fp)
1438                return -ENOMEM;
1439
1440        fp->prog = prog;
1441
1442        if (!__sk_filter_charge(sk, fp)) {
1443                kfree(fp);
1444                return -ENOMEM;
1445        }
1446        refcount_set(&fp->refcnt, 1);
1447
1448        old_fp = rcu_dereference_protected(sk->sk_filter,
1449                                           lockdep_sock_is_held(sk));
1450        rcu_assign_pointer(sk->sk_filter, fp);
1451
1452        if (old_fp)
1453                sk_filter_uncharge(sk, old_fp);
1454
1455        return 0;
1456}
1457
1458static
1459struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
1460{
1461        unsigned int fsize = bpf_classic_proglen(fprog);
1462        struct bpf_prog *prog;
1463        int err;
1464
1465        if (sock_flag(sk, SOCK_FILTER_LOCKED))
1466                return ERR_PTR(-EPERM);
1467
1468        /* Make sure new filter is there and in the right amounts. */
1469        if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1470                return ERR_PTR(-EINVAL);
1471
1472        prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1473        if (!prog)
1474                return ERR_PTR(-ENOMEM);
1475
1476        if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1477                __bpf_prog_free(prog);
1478                return ERR_PTR(-EFAULT);
1479        }
1480
1481        prog->len = fprog->len;
1482
1483        err = bpf_prog_store_orig_filter(prog, fprog);
1484        if (err) {
1485                __bpf_prog_free(prog);
1486                return ERR_PTR(-ENOMEM);
1487        }
1488
1489        /* bpf_prepare_filter() already takes care of freeing
1490         * memory in case something goes wrong.
1491         */
1492        return bpf_prepare_filter(prog, NULL);
1493}
1494
1495/**
1496 *      sk_attach_filter - attach a socket filter
1497 *      @fprog: the filter program
1498 *      @sk: the socket to use
1499 *
1500 * Attach the user's filter code. We first run some sanity checks on
1501 * it to make sure it does not explode on us later. If an error
1502 * occurs or there is insufficient memory for the filter a negative
1503 * errno code is returned. On success the return is zero.
1504 */
1505int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1506{
1507        struct bpf_prog *prog = __get_filter(fprog, sk);
1508        int err;
1509
1510        if (IS_ERR(prog))
1511                return PTR_ERR(prog);
1512
1513        err = __sk_attach_prog(prog, sk);
1514        if (err < 0) {
1515                __bpf_prog_release(prog);
1516                return err;
1517        }
1518
1519        return 0;
1520}
1521EXPORT_SYMBOL_GPL(sk_attach_filter);
1522
1523int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1524{
1525        struct bpf_prog *prog = __get_filter(fprog, sk);
1526        int err;
1527
1528        if (IS_ERR(prog))
1529                return PTR_ERR(prog);
1530
1531        if (bpf_prog_size(prog->len) > sysctl_optmem_max)
1532                err = -ENOMEM;
1533        else
1534                err = reuseport_attach_prog(sk, prog);
1535
1536        if (err)
1537                __bpf_prog_release(prog);
1538
1539        return err;
1540}
1541
1542static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
1543{
1544        if (sock_flag(sk, SOCK_FILTER_LOCKED))
1545                return ERR_PTR(-EPERM);
1546
1547        return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1548}
1549
1550int sk_attach_bpf(u32 ufd, struct sock *sk)
1551{
1552        struct bpf_prog *prog = __get_bpf(ufd, sk);
1553        int err;
1554
1555        if (IS_ERR(prog))
1556                return PTR_ERR(prog);
1557
1558        err = __sk_attach_prog(prog, sk);
1559        if (err < 0) {
1560                bpf_prog_put(prog);
1561                return err;
1562        }
1563
1564        return 0;
1565}
1566
1567int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
1568{
1569        struct bpf_prog *prog;
1570        int err;
1571
1572        if (sock_flag(sk, SOCK_FILTER_LOCKED))
1573                return -EPERM;
1574
1575        prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1576        if (IS_ERR(prog) && PTR_ERR(prog) == -EINVAL)
1577                prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SK_REUSEPORT);
1578        if (IS_ERR(prog))
1579                return PTR_ERR(prog);
1580
1581        if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) {
1582                /* Like other non BPF_PROG_TYPE_SOCKET_FILTER
1583                 * bpf prog (e.g. sockmap).  It depends on the
1584                 * limitation imposed by bpf_prog_load().
1585                 * Hence, sysctl_optmem_max is not checked.
1586                 */
1587                if ((sk->sk_type != SOCK_STREAM &&
1588                     sk->sk_type != SOCK_DGRAM) ||
1589                    (sk->sk_protocol != IPPROTO_UDP &&
1590                     sk->sk_protocol != IPPROTO_TCP) ||
1591                    (sk->sk_family != AF_INET &&
1592                     sk->sk_family != AF_INET6)) {
1593                        err = -ENOTSUPP;
1594                        goto err_prog_put;
1595                }
1596        } else {
1597                /* BPF_PROG_TYPE_SOCKET_FILTER */
1598                if (bpf_prog_size(prog->len) > sysctl_optmem_max) {
1599                        err = -ENOMEM;
1600                        goto err_prog_put;
1601                }
1602        }
1603
1604        err = reuseport_attach_prog(sk, prog);
1605err_prog_put:
1606        if (err)
1607                bpf_prog_put(prog);
1608
1609        return err;
1610}
1611
1612void sk_reuseport_prog_free(struct bpf_prog *prog)
1613{
1614        if (!prog)
1615                return;
1616
1617        if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT)
1618                bpf_prog_put(prog);
1619        else
1620                bpf_prog_destroy(prog);
1621}
1622
1623struct bpf_scratchpad {
1624        union {
1625                __be32 diff[MAX_BPF_STACK / sizeof(__be32)];
1626                u8     buff[MAX_BPF_STACK];
1627        };
1628};
1629
1630static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp);
1631
1632static inline int __bpf_try_make_writable(struct sk_buff *skb,
1633                                          unsigned int write_len)
1634{
1635        return skb_ensure_writable(skb, write_len);
1636}
1637
1638static inline int bpf_try_make_writable(struct sk_buff *skb,
1639                                        unsigned int write_len)
1640{
1641        int err = __bpf_try_make_writable(skb, write_len);
1642
1643        bpf_compute_data_pointers(skb);
1644        return err;
1645}
1646
1647static int bpf_try_make_head_writable(struct sk_buff *skb)
1648{
1649        return bpf_try_make_writable(skb, skb_headlen(skb));
1650}
1651
1652static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
1653{
1654        if (skb_at_tc_ingress(skb))
1655                skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1656}
1657
1658static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
1659{
1660        if (skb_at_tc_ingress(skb))
1661                skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1662}
1663
1664BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
1665           const void *, from, u32, len, u64, flags)
1666{
1667        void *ptr;
1668
1669        if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1670                return -EINVAL;
1671        if (unlikely(offset > 0xffff))
1672                return -EFAULT;
1673        if (unlikely(bpf_try_make_writable(skb, offset + len)))
1674                return -EFAULT;
1675
1676        ptr = skb->data + offset;
1677        if (flags & BPF_F_RECOMPUTE_CSUM)
1678                __skb_postpull_rcsum(skb, ptr, len, offset);
1679
1680        memcpy(ptr, from, len);
1681
1682        if (flags & BPF_F_RECOMPUTE_CSUM)
1683                __skb_postpush_rcsum(skb, ptr, len, offset);
1684        if (flags & BPF_F_INVALIDATE_HASH)
1685                skb_clear_hash(skb);
1686
1687        return 0;
1688}
1689
1690static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1691        .func           = bpf_skb_store_bytes,
1692        .gpl_only       = false,
1693        .ret_type       = RET_INTEGER,
1694        .arg1_type      = ARG_PTR_TO_CTX,
1695        .arg2_type      = ARG_ANYTHING,
1696        .arg3_type      = ARG_PTR_TO_MEM,
1697        .arg4_type      = ARG_CONST_SIZE,
1698        .arg5_type      = ARG_ANYTHING,
1699};
1700
1701BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
1702           void *, to, u32, len)
1703{
1704        void *ptr;
1705
1706        if (unlikely(offset > 0xffff))
1707                goto err_clear;
1708
1709        ptr = skb_header_pointer(skb, offset, len, to);
1710        if (unlikely(!ptr))
1711                goto err_clear;
1712        if (ptr != to)
1713                memcpy(to, ptr, len);
1714
1715        return 0;
1716err_clear:
1717        memset(to, 0, len);
1718        return -EFAULT;
1719}
1720
1721static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1722        .func           = bpf_skb_load_bytes,
1723        .gpl_only       = false,
1724        .ret_type       = RET_INTEGER,
1725        .arg1_type      = ARG_PTR_TO_CTX,
1726        .arg2_type      = ARG_ANYTHING,
1727        .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1728        .arg4_type      = ARG_CONST_SIZE,
1729};
1730
1731BPF_CALL_4(bpf_flow_dissector_load_bytes,
1732           const struct bpf_flow_dissector *, ctx, u32, offset,
1733           void *, to, u32, len)
1734{
1735        void *ptr;
1736
1737        if (unlikely(offset > 0xffff))
1738                goto err_clear;
1739
1740        if (unlikely(!ctx->skb))
1741                goto err_clear;
1742
1743        ptr = skb_header_pointer(ctx->skb, offset, len, to);
1744        if (unlikely(!ptr))
1745                goto err_clear;
1746        if (ptr != to)
1747                memcpy(to, ptr, len);
1748
1749        return 0;
1750err_clear:
1751        memset(to, 0, len);
1752        return -EFAULT;
1753}
1754
1755static const struct bpf_func_proto bpf_flow_dissector_load_bytes_proto = {
1756        .func           = bpf_flow_dissector_load_bytes,
1757        .gpl_only       = false,
1758        .ret_type       = RET_INTEGER,
1759        .arg1_type      = ARG_PTR_TO_CTX,
1760        .arg2_type      = ARG_ANYTHING,
1761        .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1762        .arg4_type      = ARG_CONST_SIZE,
1763};
1764
1765BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb,
1766           u32, offset, void *, to, u32, len, u32, start_header)
1767{
1768        u8 *end = skb_tail_pointer(skb);
1769        u8 *net = skb_network_header(skb);
1770        u8 *mac = skb_mac_header(skb);
1771        u8 *ptr;
1772
1773        if (unlikely(offset > 0xffff || len > (end - mac)))
1774                goto err_clear;
1775
1776        switch (start_header) {
1777        case BPF_HDR_START_MAC:
1778                ptr = mac + offset;
1779                break;
1780        case BPF_HDR_START_NET:
1781                ptr = net + offset;
1782                break;
1783        default:
1784                goto err_clear;
1785        }
1786
1787        if (likely(ptr >= mac && ptr + len <= end)) {
1788                memcpy(to, ptr, len);
1789                return 0;
1790        }
1791
1792err_clear:
1793        memset(to, 0, len);
1794        return -EFAULT;
1795}
1796
1797static const struct bpf_func_proto bpf_skb_load_bytes_relative_proto = {
1798        .func           = bpf_skb_load_bytes_relative,
1799        .gpl_only       = false,
1800        .ret_type       = RET_INTEGER,
1801        .arg1_type      = ARG_PTR_TO_CTX,
1802        .arg2_type      = ARG_ANYTHING,
1803        .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1804        .arg4_type      = ARG_CONST_SIZE,
1805        .arg5_type      = ARG_ANYTHING,
1806};
1807
1808BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
1809{
1810        /* Idea is the following: should the needed direct read/write
1811         * test fail during runtime, we can pull in more data and redo
1812         * again, since implicitly, we invalidate previous checks here.
1813         *
1814         * Or, since we know how much we need to make read/writeable,
1815         * this can be done once at the program beginning for direct
1816         * access case. By this we overcome limitations of only current
1817         * headroom being accessible.
1818         */
1819        return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
1820}
1821
1822static const struct bpf_func_proto bpf_skb_pull_data_proto = {
1823        .func           = bpf_skb_pull_data,
1824        .gpl_only       = false,
1825        .ret_type       = RET_INTEGER,
1826        .arg1_type      = ARG_PTR_TO_CTX,
1827        .arg2_type      = ARG_ANYTHING,
1828};
1829
1830BPF_CALL_1(bpf_sk_fullsock, struct sock *, sk)
1831{
1832        return sk_fullsock(sk) ? (unsigned long)sk : (unsigned long)NULL;
1833}
1834
1835static const struct bpf_func_proto bpf_sk_fullsock_proto = {
1836        .func           = bpf_sk_fullsock,
1837        .gpl_only       = false,
1838        .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
1839        .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
1840};
1841
1842static inline int sk_skb_try_make_writable(struct sk_buff *skb,
1843                                           unsigned int write_len)
1844{
1845        int err = __bpf_try_make_writable(skb, write_len);
1846
1847        bpf_compute_data_end_sk_skb(skb);
1848        return err;
1849}
1850
1851BPF_CALL_2(sk_skb_pull_data, struct sk_buff *, skb, u32, len)
1852{
1853        /* Idea is the following: should the needed direct read/write
1854         * test fail during runtime, we can pull in more data and redo
1855         * again, since implicitly, we invalidate previous checks here.
1856         *
1857         * Or, since we know how much we need to make read/writeable,
1858         * this can be done once at the program beginning for direct
1859         * access case. By this we overcome limitations of only current
1860         * headroom being accessible.
1861         */
1862        return sk_skb_try_make_writable(skb, len ? : skb_headlen(skb));
1863}
1864
1865static const struct bpf_func_proto sk_skb_pull_data_proto = {
1866        .func           = sk_skb_pull_data,
1867        .gpl_only       = false,
1868        .ret_type       = RET_INTEGER,
1869        .arg1_type      = ARG_PTR_TO_CTX,
1870        .arg2_type      = ARG_ANYTHING,
1871};
1872
1873BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
1874           u64, from, u64, to, u64, flags)
1875{
1876        __sum16 *ptr;
1877
1878        if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
1879                return -EINVAL;
1880        if (unlikely(offset > 0xffff || offset & 1))
1881                return -EFAULT;
1882        if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1883                return -EFAULT;
1884
1885        ptr = (__sum16 *)(skb->data + offset);
1886        switch (flags & BPF_F_HDR_FIELD_MASK) {
1887        case 0:
1888                if (unlikely(from != 0))
1889                        return -EINVAL;
1890
1891                csum_replace_by_diff(ptr, to);
1892                break;
1893        case 2:
1894                csum_replace2(ptr, from, to);
1895                break;
1896        case 4:
1897                csum_replace4(ptr, from, to);
1898                break;
1899        default:
1900                return -EINVAL;
1901        }
1902
1903        return 0;
1904}
1905
1906static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1907        .func           = bpf_l3_csum_replace,
1908        .gpl_only       = false,
1909        .ret_type       = RET_INTEGER,
1910        .arg1_type      = ARG_PTR_TO_CTX,
1911        .arg2_type      = ARG_ANYTHING,
1912        .arg3_type      = ARG_ANYTHING,
1913        .arg4_type      = ARG_ANYTHING,
1914        .arg5_type      = ARG_ANYTHING,
1915};
1916
1917BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
1918           u64, from, u64, to, u64, flags)
1919{
1920        bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1921        bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1922        bool do_mforce = flags & BPF_F_MARK_ENFORCE;
1923        __sum16 *ptr;
1924
1925        if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
1926                               BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK)))
1927                return -EINVAL;
1928        if (unlikely(offset > 0xffff || offset & 1))
1929                return -EFAULT;
1930        if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1931                return -EFAULT;
1932
1933        ptr = (__sum16 *)(skb->data + offset);
1934        if (is_mmzero && !do_mforce && !*ptr)
1935                return 0;
1936
1937        switch (flags & BPF_F_HDR_FIELD_MASK) {
1938        case 0:
1939                if (unlikely(from != 0))
1940                        return -EINVAL;
1941
1942                inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
1943                break;
1944        case 2:
1945                inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
1946                break;
1947        case 4:
1948                inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
1949                break;
1950        default:
1951                return -EINVAL;
1952        }
1953
1954        if (is_mmzero && !*ptr)
1955                *ptr = CSUM_MANGLED_0;
1956        return 0;
1957}
1958
1959static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1960        .func           = bpf_l4_csum_replace,
1961        .gpl_only       = false,
1962        .ret_type       = RET_INTEGER,
1963        .arg1_type      = ARG_PTR_TO_CTX,
1964        .arg2_type      = ARG_ANYTHING,
1965        .arg3_type      = ARG_ANYTHING,
1966        .arg4_type      = ARG_ANYTHING,
1967        .arg5_type      = ARG_ANYTHING,
1968};
1969
1970BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
1971           __be32 *, to, u32, to_size, __wsum, seed)
1972{
1973        struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1974        u32 diff_size = from_size + to_size;
1975        int i, j = 0;
1976
1977        /* This is quite flexible, some examples:
1978         *
1979         * from_size == 0, to_size > 0,  seed := csum --> pushing data
1980         * from_size > 0,  to_size == 0, seed := csum --> pulling data
1981         * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
1982         *
1983         * Even for diffing, from_size and to_size don't need to be equal.
1984         */
1985        if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) ||
1986                     diff_size > sizeof(sp->diff)))
1987                return -EINVAL;
1988
1989        for (i = 0; i < from_size / sizeof(__be32); i++, j++)
1990                sp->diff[j] = ~from[i];
1991        for (i = 0; i <   to_size / sizeof(__be32); i++, j++)
1992                sp->diff[j] = to[i];
1993
1994        return csum_partial(sp->diff, diff_size, seed);
1995}
1996
1997static const struct bpf_func_proto bpf_csum_diff_proto = {
1998        .func           = bpf_csum_diff,
1999        .gpl_only       = false,
2000        .pkt_access     = true,
2001        .ret_type       = RET_INTEGER,
2002        .arg1_type      = ARG_PTR_TO_MEM_OR_NULL,
2003        .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
2004        .arg3_type      = ARG_PTR_TO_MEM_OR_NULL,
2005        .arg4_type      = ARG_CONST_SIZE_OR_ZERO,
2006        .arg5_type      = ARG_ANYTHING,
2007};
2008
2009BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
2010{
2011        /* The interface is to be used in combination with bpf_csum_diff()
2012         * for direct packet writes. csum rotation for alignment as well
2013         * as emulating csum_sub() can be done from the eBPF program.
2014         */
2015        if (skb->ip_summed == CHECKSUM_COMPLETE)
2016                return (skb->csum = csum_add(skb->csum, csum));
2017
2018        return -ENOTSUPP;
2019}
2020
2021static const struct bpf_func_proto bpf_csum_update_proto = {
2022        .func           = bpf_csum_update,
2023        .gpl_only       = false,
2024        .ret_type       = RET_INTEGER,
2025        .arg1_type      = ARG_PTR_TO_CTX,
2026        .arg2_type      = ARG_ANYTHING,
2027};
2028
2029static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
2030{
2031        return dev_forward_skb(dev, skb);
2032}
2033
2034static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
2035                                      struct sk_buff *skb)
2036{
2037        int ret = ____dev_forward_skb(dev, skb);
2038
2039        if (likely(!ret)) {
2040                skb->dev = dev;
2041                ret = netif_rx(skb);
2042        }
2043
2044        return ret;
2045}
2046
2047static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
2048{
2049        int ret;
2050
2051        if (dev_xmit_recursion()) {
2052                net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2053                kfree_skb(skb);
2054                return -ENETDOWN;
2055        }
2056
2057        skb->dev = dev;
2058
2059        dev_xmit_recursion_inc();
2060        ret = dev_queue_xmit(skb);
2061        dev_xmit_recursion_dec();
2062
2063        return ret;
2064}
2065
2066static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
2067                                 u32 flags)
2068{
2069        unsigned int mlen = skb_network_offset(skb);
2070
2071        if (mlen) {
2072                __skb_pull(skb, mlen);
2073
2074                /* At ingress, the mac header has already been pulled once.
2075                 * At egress, skb_pospull_rcsum has to be done in case that
2076                 * the skb is originated from ingress (i.e. a forwarded skb)
2077                 * to ensure that rcsum starts at net header.
2078                 */
2079                if (!skb_at_tc_ingress(skb))
2080                        skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
2081        }
2082        skb_pop_mac_header(skb);
2083        skb_reset_mac_len(skb);
2084        return flags & BPF_F_INGRESS ?
2085               __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
2086}
2087
2088static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
2089                                 u32 flags)
2090{
2091        /* Verify that a link layer header is carried */
2092        if (unlikely(skb->mac_header >= skb->network_header)) {
2093                kfree_skb(skb);
2094                return -ERANGE;
2095        }
2096
2097        bpf_push_mac_rcsum(skb);
2098        return flags & BPF_F_INGRESS ?
2099               __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
2100}
2101
2102static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
2103                          u32 flags)
2104{
2105        if (dev_is_mac_header_xmit(dev))
2106                return __bpf_redirect_common(skb, dev, flags);
2107        else
2108                return __bpf_redirect_no_mac(skb, dev, flags);
2109}
2110
2111BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
2112{
2113        struct net_device *dev;
2114        struct sk_buff *clone;
2115        int ret;
2116
2117        if (unlikely(flags & ~(BPF_F_INGRESS)))
2118                return -EINVAL;
2119
2120        dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
2121        if (unlikely(!dev))
2122                return -EINVAL;
2123
2124        clone = skb_clone(skb, GFP_ATOMIC);
2125        if (unlikely(!clone))
2126                return -ENOMEM;
2127
2128        /* For direct write, we need to keep the invariant that the skbs
2129         * we're dealing with need to be uncloned. Should uncloning fail
2130         * here, we need to free the just generated clone to unclone once
2131         * again.
2132         */
2133        ret = bpf_try_make_head_writable(skb);
2134        if (unlikely(ret)) {
2135                kfree_skb(clone);
2136                return -ENOMEM;
2137        }
2138
2139        return __bpf_redirect(clone, dev, flags);
2140}
2141
2142static const struct bpf_func_proto bpf_clone_redirect_proto = {
2143        .func           = bpf_clone_redirect,
2144        .gpl_only       = false,
2145        .ret_type       = RET_INTEGER,
2146        .arg1_type      = ARG_PTR_TO_CTX,
2147        .arg2_type      = ARG_ANYTHING,
2148        .arg3_type      = ARG_ANYTHING,
2149};
2150
2151DEFINE_PER_CPU(struct bpf_redirect_info, bpf_redirect_info);
2152EXPORT_PER_CPU_SYMBOL_GPL(bpf_redirect_info);
2153
2154BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
2155{
2156        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2157
2158        if (unlikely(flags & ~(BPF_F_INGRESS)))
2159                return TC_ACT_SHOT;
2160
2161        ri->flags = flags;
2162        ri->tgt_index = ifindex;
2163
2164        return TC_ACT_REDIRECT;
2165}
2166
2167int skb_do_redirect(struct sk_buff *skb)
2168{
2169        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2170        struct net_device *dev;
2171
2172        dev = dev_get_by_index_rcu(dev_net(skb->dev), ri->tgt_index);
2173        ri->tgt_index = 0;
2174        if (unlikely(!dev)) {
2175                kfree_skb(skb);
2176                return -EINVAL;
2177        }
2178
2179        return __bpf_redirect(skb, dev, ri->flags);
2180}
2181
2182static const struct bpf_func_proto bpf_redirect_proto = {
2183        .func           = bpf_redirect,
2184        .gpl_only       = false,
2185        .ret_type       = RET_INTEGER,
2186        .arg1_type      = ARG_ANYTHING,
2187        .arg2_type      = ARG_ANYTHING,
2188};
2189
2190BPF_CALL_2(bpf_msg_apply_bytes, struct sk_msg *, msg, u32, bytes)
2191{
2192        msg->apply_bytes = bytes;
2193        return 0;
2194}
2195
2196static const struct bpf_func_proto bpf_msg_apply_bytes_proto = {
2197        .func           = bpf_msg_apply_bytes,
2198        .gpl_only       = false,
2199        .ret_type       = RET_INTEGER,
2200        .arg1_type      = ARG_PTR_TO_CTX,
2201        .arg2_type      = ARG_ANYTHING,
2202};
2203
2204BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg *, msg, u32, bytes)
2205{
2206        msg->cork_bytes = bytes;
2207        return 0;
2208}
2209
2210static const struct bpf_func_proto bpf_msg_cork_bytes_proto = {
2211        .func           = bpf_msg_cork_bytes,
2212        .gpl_only       = false,
2213        .ret_type       = RET_INTEGER,
2214        .arg1_type      = ARG_PTR_TO_CTX,
2215        .arg2_type      = ARG_ANYTHING,
2216};
2217
2218BPF_CALL_4(bpf_msg_pull_data, struct sk_msg *, msg, u32, start,
2219           u32, end, u64, flags)
2220{
2221        u32 len = 0, offset = 0, copy = 0, poffset = 0, bytes = end - start;
2222        u32 first_sge, last_sge, i, shift, bytes_sg_total;
2223        struct scatterlist *sge;
2224        u8 *raw, *to, *from;
2225        struct page *page;
2226
2227        if (unlikely(flags || end <= start))
2228                return -EINVAL;
2229
2230        /* First find the starting scatterlist element */
2231        i = msg->sg.start;
2232        do {
2233                len = sk_msg_elem(msg, i)->length;
2234                if (start < offset + len)
2235                        break;
2236                offset += len;
2237                sk_msg_iter_var_next(i);
2238        } while (i != msg->sg.end);
2239
2240        if (unlikely(start >= offset + len))
2241                return -EINVAL;
2242
2243        first_sge = i;
2244        /* The start may point into the sg element so we need to also
2245         * account for the headroom.
2246         */
2247        bytes_sg_total = start - offset + bytes;
2248        if (!msg->sg.copy[i] && bytes_sg_total <= len)
2249                goto out;
2250
2251        /* At this point we need to linearize multiple scatterlist
2252         * elements or a single shared page. Either way we need to
2253         * copy into a linear buffer exclusively owned by BPF. Then
2254         * place the buffer in the scatterlist and fixup the original
2255         * entries by removing the entries now in the linear buffer
2256         * and shifting the remaining entries. For now we do not try
2257         * to copy partial entries to avoid complexity of running out
2258         * of sg_entry slots. The downside is reading a single byte
2259         * will copy the entire sg entry.
2260         */
2261        do {
2262                copy += sk_msg_elem(msg, i)->length;
2263                sk_msg_iter_var_next(i);
2264                if (bytes_sg_total <= copy)
2265                        break;
2266        } while (i != msg->sg.end);
2267        last_sge = i;
2268
2269        if (unlikely(bytes_sg_total > copy))
2270                return -EINVAL;
2271
2272        page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2273                           get_order(copy));
2274        if (unlikely(!page))
2275                return -ENOMEM;
2276
2277        raw = page_address(page);
2278        i = first_sge;
2279        do {
2280                sge = sk_msg_elem(msg, i);
2281                from = sg_virt(sge);
2282                len = sge->length;
2283                to = raw + poffset;
2284
2285                memcpy(to, from, len);
2286                poffset += len;
2287                sge->length = 0;
2288                put_page(sg_page(sge));
2289
2290                sk_msg_iter_var_next(i);
2291        } while (i != last_sge);
2292
2293        sg_set_page(&msg->sg.data[first_sge], page, copy, 0);
2294
2295        /* To repair sg ring we need to shift entries. If we only
2296         * had a single entry though we can just replace it and
2297         * be done. Otherwise walk the ring and shift the entries.
2298         */
2299        WARN_ON_ONCE(last_sge == first_sge);
2300        shift = last_sge > first_sge ?
2301                last_sge - first_sge - 1 :
2302                MAX_SKB_FRAGS - first_sge + last_sge - 1;
2303        if (!shift)
2304                goto out;
2305
2306        i = first_sge;
2307        sk_msg_iter_var_next(i);
2308        do {
2309                u32 move_from;
2310
2311                if (i + shift >= MAX_MSG_FRAGS)
2312                        move_from = i + shift - MAX_MSG_FRAGS;
2313                else
2314                        move_from = i + shift;
2315                if (move_from == msg->sg.end)
2316                        break;
2317
2318                msg->sg.data[i] = msg->sg.data[move_from];
2319                msg->sg.data[move_from].length = 0;
2320                msg->sg.data[move_from].page_link = 0;
2321                msg->sg.data[move_from].offset = 0;
2322                sk_msg_iter_var_next(i);
2323        } while (1);
2324
2325        msg->sg.end = msg->sg.end - shift > msg->sg.end ?
2326                      msg->sg.end - shift + MAX_MSG_FRAGS :
2327                      msg->sg.end - shift;
2328out:
2329        msg->data = sg_virt(&msg->sg.data[first_sge]) + start - offset;
2330        msg->data_end = msg->data + bytes;
2331        return 0;
2332}
2333
2334static const struct bpf_func_proto bpf_msg_pull_data_proto = {
2335        .func           = bpf_msg_pull_data,
2336        .gpl_only       = false,
2337        .ret_type       = RET_INTEGER,
2338        .arg1_type      = ARG_PTR_TO_CTX,
2339        .arg2_type      = ARG_ANYTHING,
2340        .arg3_type      = ARG_ANYTHING,
2341        .arg4_type      = ARG_ANYTHING,
2342};
2343
2344BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start,
2345           u32, len, u64, flags)
2346{
2347        struct scatterlist sge, nsge, nnsge, rsge = {0}, *psge;
2348        u32 new, i = 0, l, space, copy = 0, offset = 0;
2349        u8 *raw, *to, *from;
2350        struct page *page;
2351
2352        if (unlikely(flags))
2353                return -EINVAL;
2354
2355        /* First find the starting scatterlist element */
2356        i = msg->sg.start;
2357        do {
2358                l = sk_msg_elem(msg, i)->length;
2359
2360                if (start < offset + l)
2361                        break;
2362                offset += l;
2363                sk_msg_iter_var_next(i);
2364        } while (i != msg->sg.end);
2365
2366        if (start >= offset + l)
2367                return -EINVAL;
2368
2369        space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2370
2371        /* If no space available will fallback to copy, we need at
2372         * least one scatterlist elem available to push data into
2373         * when start aligns to the beginning of an element or two
2374         * when it falls inside an element. We handle the start equals
2375         * offset case because its the common case for inserting a
2376         * header.
2377         */
2378        if (!space || (space == 1 && start != offset))
2379                copy = msg->sg.data[i].length;
2380
2381        page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2382                           get_order(copy + len));
2383        if (unlikely(!page))
2384                return -ENOMEM;
2385
2386        if (copy) {
2387                int front, back;
2388
2389                raw = page_address(page);
2390
2391                psge = sk_msg_elem(msg, i);
2392                front = start - offset;
2393                back = psge->length - front;
2394                from = sg_virt(psge);
2395
2396                if (front)
2397                        memcpy(raw, from, front);
2398
2399                if (back) {
2400                        from += front;
2401                        to = raw + front + len;
2402
2403                        memcpy(to, from, back);
2404                }
2405
2406                put_page(sg_page(psge));
2407        } else if (start - offset) {
2408                psge = sk_msg_elem(msg, i);
2409                rsge = sk_msg_elem_cpy(msg, i);
2410
2411                psge->length = start - offset;
2412                rsge.length -= psge->length;
2413                rsge.offset += start;
2414
2415                sk_msg_iter_var_next(i);
2416                sg_unmark_end(psge);
2417                sk_msg_iter_next(msg, end);
2418        }
2419
2420        /* Slot(s) to place newly allocated data */
2421        new = i;
2422
2423        /* Shift one or two slots as needed */
2424        if (!copy) {
2425                sge = sk_msg_elem_cpy(msg, i);
2426
2427                sk_msg_iter_var_next(i);
2428                sg_unmark_end(&sge);
2429                sk_msg_iter_next(msg, end);
2430
2431                nsge = sk_msg_elem_cpy(msg, i);
2432                if (rsge.length) {
2433                        sk_msg_iter_var_next(i);
2434                        nnsge = sk_msg_elem_cpy(msg, i);
2435                }
2436
2437                while (i != msg->sg.end) {
2438                        msg->sg.data[i] = sge;
2439                        sge = nsge;
2440                        sk_msg_iter_var_next(i);
2441                        if (rsge.length) {
2442                                nsge = nnsge;
2443                                nnsge = sk_msg_elem_cpy(msg, i);
2444                        } else {
2445                                nsge = sk_msg_elem_cpy(msg, i);
2446                        }
2447                }
2448        }
2449
2450        /* Place newly allocated data buffer */
2451        sk_mem_charge(msg->sk, len);
2452        msg->sg.size += len;
2453        msg->sg.copy[new] = false;
2454        sg_set_page(&msg->sg.data[new], page, len + copy, 0);
2455        if (rsge.length) {
2456                get_page(sg_page(&rsge));
2457                sk_msg_iter_var_next(new);
2458                msg->sg.data[new] = rsge;
2459        }
2460
2461        sk_msg_compute_data_pointers(msg);
2462        return 0;
2463}
2464
2465static const struct bpf_func_proto bpf_msg_push_data_proto = {
2466        .func           = bpf_msg_push_data,
2467        .gpl_only       = false,
2468        .ret_type       = RET_INTEGER,
2469        .arg1_type      = ARG_PTR_TO_CTX,
2470        .arg2_type      = ARG_ANYTHING,
2471        .arg3_type      = ARG_ANYTHING,
2472        .arg4_type      = ARG_ANYTHING,
2473};
2474
2475static void sk_msg_shift_left(struct sk_msg *msg, int i)
2476{
2477        int prev;
2478
2479        do {
2480                prev = i;
2481                sk_msg_iter_var_next(i);
2482                msg->sg.data[prev] = msg->sg.data[i];
2483        } while (i != msg->sg.end);
2484
2485        sk_msg_iter_prev(msg, end);
2486}
2487
2488static void sk_msg_shift_right(struct sk_msg *msg, int i)
2489{
2490        struct scatterlist tmp, sge;
2491
2492        sk_msg_iter_next(msg, end);
2493        sge = sk_msg_elem_cpy(msg, i);
2494        sk_msg_iter_var_next(i);
2495        tmp = sk_msg_elem_cpy(msg, i);
2496
2497        while (i != msg->sg.end) {
2498                msg->sg.data[i] = sge;
2499                sk_msg_iter_var_next(i);
2500                sge = tmp;
2501                tmp = sk_msg_elem_cpy(msg, i);
2502        }
2503}
2504
2505BPF_CALL_4(bpf_msg_pop_data, struct sk_msg *, msg, u32, start,
2506           u32, len, u64, flags)
2507{
2508        u32 i = 0, l, space, offset = 0;
2509        u64 last = start + len;
2510        int pop;
2511
2512        if (unlikely(flags))
2513                return -EINVAL;
2514
2515        /* First find the starting scatterlist element */
2516        i = msg->sg.start;
2517        do {
2518                l = sk_msg_elem(msg, i)->length;
2519
2520                if (start < offset + l)
2521                        break;
2522                offset += l;
2523                sk_msg_iter_var_next(i);
2524        } while (i != msg->sg.end);
2525
2526        /* Bounds checks: start and pop must be inside message */
2527        if (start >= offset + l || last >= msg->sg.size)
2528                return -EINVAL;
2529
2530        space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2531
2532        pop = len;
2533        /* --------------| offset
2534         * -| start      |-------- len -------|
2535         *
2536         *  |----- a ----|-------- pop -------|----- b ----|
2537         *  |______________________________________________| length
2538         *
2539         *
2540         * a:   region at front of scatter element to save
2541         * b:   region at back of scatter element to save when length > A + pop
2542         * pop: region to pop from element, same as input 'pop' here will be
2543         *      decremented below per iteration.
2544         *
2545         * Two top-level cases to handle when start != offset, first B is non
2546         * zero and second B is zero corresponding to when a pop includes more
2547         * than one element.
2548         *
2549         * Then if B is non-zero AND there is no space allocate space and
2550         * compact A, B regions into page. If there is space shift ring to
2551         * the rigth free'ing the next element in ring to place B, leaving
2552         * A untouched except to reduce length.
2553         */
2554        if (start != offset) {
2555                struct scatterlist *nsge, *sge = sk_msg_elem(msg, i);
2556                int a = start;
2557                int b = sge->length - pop - a;
2558
2559                sk_msg_iter_var_next(i);
2560
2561                if (pop < sge->length - a) {
2562                        if (space) {
2563                                sge->length = a;
2564                                sk_msg_shift_right(msg, i);
2565                                nsge = sk_msg_elem(msg, i);
2566                                get_page(sg_page(sge));
2567                                sg_set_page(nsge,
2568                                            sg_page(sge),
2569                                            b, sge->offset + pop + a);
2570                        } else {
2571                                struct page *page, *orig;
2572                                u8 *to, *from;
2573
2574                                page = alloc_pages(__GFP_NOWARN |
2575                                                   __GFP_COMP   | GFP_ATOMIC,
2576                                                   get_order(a + b));
2577                                if (unlikely(!page))
2578                                        return -ENOMEM;
2579
2580                                sge->length = a;
2581                                orig = sg_page(sge);
2582                                from = sg_virt(sge);
2583                                to = page_address(page);
2584                                memcpy(to, from, a);
2585                                memcpy(to + a, from + a + pop, b);
2586                                sg_set_page(sge, page, a + b, 0);
2587                                put_page(orig);
2588                        }
2589                        pop = 0;
2590                } else if (pop >= sge->length - a) {
2591                        sge->length = a;
2592                        pop -= (sge->length - a);
2593                }
2594        }
2595
2596        /* From above the current layout _must_ be as follows,
2597         *
2598         * -| offset
2599         * -| start
2600         *
2601         *  |---- pop ---|---------------- b ------------|
2602         *  |____________________________________________| length
2603         *
2604         * Offset and start of the current msg elem are equal because in the
2605         * previous case we handled offset != start and either consumed the
2606         * entire element and advanced to the next element OR pop == 0.
2607         *
2608         * Two cases to handle here are first pop is less than the length
2609         * leaving some remainder b above. Simply adjust the element's layout
2610         * in this case. Or pop >= length of the element so that b = 0. In this
2611         * case advance to next element decrementing pop.
2612         */
2613        while (pop) {
2614                struct scatterlist *sge = sk_msg_elem(msg, i);
2615
2616                if (pop < sge->length) {
2617                        sge->length -= pop;
2618                        sge->offset += pop;
2619                        pop = 0;
2620                } else {
2621                        pop -= sge->length;
2622                        sk_msg_shift_left(msg, i);
2623                }
2624                sk_msg_iter_var_next(i);
2625        }
2626
2627        sk_mem_uncharge(msg->sk, len - pop);
2628        msg->sg.size -= (len - pop);
2629        sk_msg_compute_data_pointers(msg);
2630        return 0;
2631}
2632
2633static const struct bpf_func_proto bpf_msg_pop_data_proto = {
2634        .func           = bpf_msg_pop_data,
2635        .gpl_only       = false,
2636        .ret_type       = RET_INTEGER,
2637        .arg1_type      = ARG_PTR_TO_CTX,
2638        .arg2_type      = ARG_ANYTHING,
2639        .arg3_type      = ARG_ANYTHING,
2640        .arg4_type      = ARG_ANYTHING,
2641};
2642
2643BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
2644{
2645        return task_get_classid(skb);
2646}
2647
2648static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
2649        .func           = bpf_get_cgroup_classid,
2650        .gpl_only       = false,
2651        .ret_type       = RET_INTEGER,
2652        .arg1_type      = ARG_PTR_TO_CTX,
2653};
2654
2655BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
2656{
2657        return dst_tclassid(skb);
2658}
2659
2660static const struct bpf_func_proto bpf_get_route_realm_proto = {
2661        .func           = bpf_get_route_realm,
2662        .gpl_only       = false,
2663        .ret_type       = RET_INTEGER,
2664        .arg1_type      = ARG_PTR_TO_CTX,
2665};
2666
2667BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
2668{
2669        /* If skb_clear_hash() was called due to mangling, we can
2670         * trigger SW recalculation here. Later access to hash
2671         * can then use the inline skb->hash via context directly
2672         * instead of calling this helper again.
2673         */
2674        return skb_get_hash(skb);
2675}
2676
2677static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
2678        .func           = bpf_get_hash_recalc,
2679        .gpl_only       = false,
2680        .ret_type       = RET_INTEGER,
2681        .arg1_type      = ARG_PTR_TO_CTX,
2682};
2683
2684BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
2685{
2686        /* After all direct packet write, this can be used once for
2687         * triggering a lazy recalc on next skb_get_hash() invocation.
2688         */
2689        skb_clear_hash(skb);
2690        return 0;
2691}
2692
2693static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
2694        .func           = bpf_set_hash_invalid,
2695        .gpl_only       = false,
2696        .ret_type       = RET_INTEGER,
2697        .arg1_type      = ARG_PTR_TO_CTX,
2698};
2699
2700BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
2701{
2702        /* Set user specified hash as L4(+), so that it gets returned
2703         * on skb_get_hash() call unless BPF prog later on triggers a
2704         * skb_clear_hash().
2705         */
2706        __skb_set_sw_hash(skb, hash, true);
2707        return 0;
2708}
2709
2710static const struct bpf_func_proto bpf_set_hash_proto = {
2711        .func           = bpf_set_hash,
2712        .gpl_only       = false,
2713        .ret_type       = RET_INTEGER,
2714        .arg1_type      = ARG_PTR_TO_CTX,
2715        .arg2_type      = ARG_ANYTHING,
2716};
2717
2718BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
2719           u16, vlan_tci)
2720{
2721        int ret;
2722
2723        if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
2724                     vlan_proto != htons(ETH_P_8021AD)))
2725                vlan_proto = htons(ETH_P_8021Q);
2726
2727        bpf_push_mac_rcsum(skb);
2728        ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
2729        bpf_pull_mac_rcsum(skb);
2730
2731        bpf_compute_data_pointers(skb);
2732        return ret;
2733}
2734
2735static const struct bpf_func_proto bpf_skb_vlan_push_proto = {
2736        .func           = bpf_skb_vlan_push,
2737        .gpl_only       = false,
2738        .ret_type       = RET_INTEGER,
2739        .arg1_type      = ARG_PTR_TO_CTX,
2740        .arg2_type      = ARG_ANYTHING,
2741        .arg3_type      = ARG_ANYTHING,
2742};
2743
2744BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
2745{
2746        int ret;
2747
2748        bpf_push_mac_rcsum(skb);
2749        ret = skb_vlan_pop(skb);
2750        bpf_pull_mac_rcsum(skb);
2751
2752        bpf_compute_data_pointers(skb);
2753        return ret;
2754}
2755
2756static const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
2757        .func           = bpf_skb_vlan_pop,
2758        .gpl_only       = false,
2759        .ret_type       = RET_INTEGER,
2760        .arg1_type      = ARG_PTR_TO_CTX,
2761};
2762
2763static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
2764{
2765        /* Caller already did skb_cow() with len as headroom,
2766         * so no need to do it here.
2767         */
2768        skb_push(skb, len);
2769        memmove(skb->data, skb->data + len, off);
2770        memset(skb->data + off, 0, len);
2771
2772        /* No skb_postpush_rcsum(skb, skb->data + off, len)
2773         * needed here as it does not change the skb->csum
2774         * result for checksum complete when summing over
2775         * zeroed blocks.
2776         */
2777        return 0;
2778}
2779
2780static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
2781{
2782        /* skb_ensure_writable() is not needed here, as we're
2783         * already working on an uncloned skb.
2784         */
2785        if (unlikely(!pskb_may_pull(skb, off + len)))
2786                return -ENOMEM;
2787
2788        skb_postpull_rcsum(skb, skb->data + off, len);
2789        memmove(skb->data + len, skb->data, off);
2790        __skb_pull(skb, len);
2791
2792        return 0;
2793}
2794
2795static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
2796{
2797        bool trans_same = skb->transport_header == skb->network_header;
2798        int ret;
2799
2800        /* There's no need for __skb_push()/__skb_pull() pair to
2801         * get to the start of the mac header as we're guaranteed
2802         * to always start from here under eBPF.
2803         */
2804        ret = bpf_skb_generic_push(skb, off, len);
2805        if (likely(!ret)) {
2806                skb->mac_header -= len;
2807                skb->network_header -= len;
2808                if (trans_same)
2809                        skb->transport_header = skb->network_header;
2810        }
2811
2812        return ret;
2813}
2814
2815static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
2816{
2817        bool trans_same = skb->transport_header == skb->network_header;
2818        int ret;
2819
2820        /* Same here, __skb_push()/__skb_pull() pair not needed. */
2821        ret = bpf_skb_generic_pop(skb, off, len);
2822        if (likely(!ret)) {
2823                skb->mac_header += len;
2824                skb->network_header += len;
2825                if (trans_same)
2826                        skb->transport_header = skb->network_header;
2827        }
2828
2829        return ret;
2830}
2831
2832static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
2833{
2834        const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2835        u32 off = skb_mac_header_len(skb);
2836        int ret;
2837
2838        if (skb_is_gso(skb) && !skb_is_gso_tcp(skb))
2839                return -ENOTSUPP;
2840
2841        ret = skb_cow(skb, len_diff);
2842        if (unlikely(ret < 0))
2843                return ret;
2844
2845        ret = bpf_skb_net_hdr_push(skb, off, len_diff);
2846        if (unlikely(ret < 0))
2847                return ret;
2848
2849        if (skb_is_gso(skb)) {
2850                struct skb_shared_info *shinfo = skb_shinfo(skb);
2851
2852                /* SKB_GSO_TCPV4 needs to be changed into
2853                 * SKB_GSO_TCPV6.
2854                 */
2855                if (shinfo->gso_type & SKB_GSO_TCPV4) {
2856                        shinfo->gso_type &= ~SKB_GSO_TCPV4;
2857                        shinfo->gso_type |=  SKB_GSO_TCPV6;
2858                }
2859
2860                /* Due to IPv6 header, MSS needs to be downgraded. */
2861                skb_decrease_gso_size(shinfo, len_diff);
2862                /* Header must be checked, and gso_segs recomputed. */
2863                shinfo->gso_type |= SKB_GSO_DODGY;
2864                shinfo->gso_segs = 0;
2865        }
2866
2867        skb->protocol = htons(ETH_P_IPV6);
2868        skb_clear_hash(skb);
2869
2870        return 0;
2871}
2872
2873static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
2874{
2875        const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2876        u32 off = skb_mac_header_len(skb);
2877        int ret;
2878
2879        if (skb_is_gso(skb) && !skb_is_gso_tcp(skb))
2880                return -ENOTSUPP;
2881
2882        ret = skb_unclone(skb, GFP_ATOMIC);
2883        if (unlikely(ret < 0))
2884                return ret;
2885
2886        ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
2887        if (unlikely(ret < 0))
2888                return ret;
2889
2890        if (skb_is_gso(skb)) {
2891                struct skb_shared_info *shinfo = skb_shinfo(skb);
2892
2893                /* SKB_GSO_TCPV6 needs to be changed into
2894                 * SKB_GSO_TCPV4.
2895                 */
2896                if (shinfo->gso_type & SKB_GSO_TCPV6) {
2897                        shinfo->gso_type &= ~SKB_GSO_TCPV6;
2898                        shinfo->gso_type |=  SKB_GSO_TCPV4;
2899                }
2900
2901                /* Due to IPv4 header, MSS can be upgraded. */
2902                skb_increase_gso_size(shinfo, len_diff);
2903                /* Header must be checked, and gso_segs recomputed. */
2904                shinfo->gso_type |= SKB_GSO_DODGY;
2905                shinfo->gso_segs = 0;
2906        }
2907
2908        skb->protocol = htons(ETH_P_IP);
2909        skb_clear_hash(skb);
2910
2911        return 0;
2912}
2913
2914static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
2915{
2916        __be16 from_proto = skb->protocol;
2917
2918        if (from_proto == htons(ETH_P_IP) &&
2919              to_proto == htons(ETH_P_IPV6))
2920                return bpf_skb_proto_4_to_6(skb);
2921
2922        if (from_proto == htons(ETH_P_IPV6) &&
2923              to_proto == htons(ETH_P_IP))
2924                return bpf_skb_proto_6_to_4(skb);
2925
2926        return -ENOTSUPP;
2927}
2928
2929BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
2930           u64, flags)
2931{
2932        int ret;
2933
2934        if (unlikely(flags))
2935                return -EINVAL;
2936
2937        /* General idea is that this helper does the basic groundwork
2938         * needed for changing the protocol, and eBPF program fills the
2939         * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
2940         * and other helpers, rather than passing a raw buffer here.
2941         *
2942         * The rationale is to keep this minimal and without a need to
2943         * deal with raw packet data. F.e. even if we would pass buffers
2944         * here, the program still needs to call the bpf_lX_csum_replace()
2945         * helpers anyway. Plus, this way we keep also separation of
2946         * concerns, since f.e. bpf_skb_store_bytes() should only take
2947         * care of stores.
2948         *
2949         * Currently, additional options and extension header space are
2950         * not supported, but flags register is reserved so we can adapt
2951         * that. For offloads, we mark packet as dodgy, so that headers
2952         * need to be verified first.
2953         */
2954        ret = bpf_skb_proto_xlat(skb, proto);
2955        bpf_compute_data_pointers(skb);
2956        return ret;
2957}
2958
2959static const struct bpf_func_proto bpf_skb_change_proto_proto = {
2960        .func           = bpf_skb_change_proto,
2961        .gpl_only       = false,
2962        .ret_type       = RET_INTEGER,
2963        .arg1_type      = ARG_PTR_TO_CTX,
2964        .arg2_type      = ARG_ANYTHING,
2965        .arg3_type      = ARG_ANYTHING,
2966};
2967
2968BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
2969{
2970        /* We only allow a restricted subset to be changed for now. */
2971        if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
2972                     !skb_pkt_type_ok(pkt_type)))
2973                return -EINVAL;
2974
2975        skb->pkt_type = pkt_type;
2976        return 0;
2977}
2978
2979static const struct bpf_func_proto bpf_skb_change_type_proto = {
2980        .func           = bpf_skb_change_type,
2981        .gpl_only       = false,
2982        .ret_type       = RET_INTEGER,
2983        .arg1_type      = ARG_PTR_TO_CTX,
2984        .arg2_type      = ARG_ANYTHING,
2985};
2986
2987static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
2988{
2989        switch (skb->protocol) {
2990        case htons(ETH_P_IP):
2991                return sizeof(struct iphdr);
2992        case htons(ETH_P_IPV6):
2993                return sizeof(struct ipv6hdr);
2994        default:
2995                return ~0U;
2996        }
2997}
2998
2999#define BPF_F_ADJ_ROOM_ENCAP_L3_MASK    (BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 | \
3000                                         BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3001
3002#define BPF_F_ADJ_ROOM_MASK             (BPF_F_ADJ_ROOM_FIXED_GSO | \
3003                                         BPF_F_ADJ_ROOM_ENCAP_L3_MASK | \
3004                                         BPF_F_ADJ_ROOM_ENCAP_L4_GRE | \
3005                                         BPF_F_ADJ_ROOM_ENCAP_L4_UDP | \
3006                                         BPF_F_ADJ_ROOM_ENCAP_L2( \
3007                                          BPF_ADJ_ROOM_ENCAP_L2_MASK))
3008
3009static int bpf_skb_net_grow(struct sk_buff *skb, u32 off, u32 len_diff,
3010                            u64 flags)
3011{
3012        u8 inner_mac_len = flags >> BPF_ADJ_ROOM_ENCAP_L2_SHIFT;
3013        bool encap = flags & BPF_F_ADJ_ROOM_ENCAP_L3_MASK;
3014        u16 mac_len = 0, inner_net = 0, inner_trans = 0;
3015        unsigned int gso_type = SKB_GSO_DODGY;
3016        int ret;
3017
3018        if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3019                /* udp gso_size delineates datagrams, only allow if fixed */
3020                if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3021                    !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3022                        return -ENOTSUPP;
3023        }
3024
3025        ret = skb_cow_head(skb, len_diff);
3026        if (unlikely(ret < 0))
3027                return ret;
3028
3029        if (encap) {
3030                if (skb->protocol != htons(ETH_P_IP) &&
3031                    skb->protocol != htons(ETH_P_IPV6))
3032                        return -ENOTSUPP;
3033
3034                if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 &&
3035                    flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3036                        return -EINVAL;
3037
3038                if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE &&
3039                    flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3040                        return -EINVAL;
3041
3042                if (skb->encapsulation)
3043                        return -EALREADY;
3044
3045                mac_len = skb->network_header - skb->mac_header;
3046                inner_net = skb->network_header;
3047                if (inner_mac_len > len_diff)
3048                        return -EINVAL;
3049                inner_trans = skb->transport_header;
3050        }
3051
3052        ret = bpf_skb_net_hdr_push(skb, off, len_diff);
3053        if (unlikely(ret < 0))
3054                return ret;
3055
3056        if (encap) {
3057                skb->inner_mac_header = inner_net - inner_mac_len;
3058                skb->inner_network_header = inner_net;
3059                skb->inner_transport_header = inner_trans;
3060                skb_set_inner_protocol(skb, skb->protocol);
3061
3062                skb->encapsulation = 1;
3063                skb_set_network_header(skb, mac_len);
3064
3065                if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3066                        gso_type |= SKB_GSO_UDP_TUNNEL;
3067                else if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE)
3068                        gso_type |= SKB_GSO_GRE;
3069                else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3070                        gso_type |= SKB_GSO_IPXIP6;
3071                else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3072                        gso_type |= SKB_GSO_IPXIP4;
3073
3074                if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE ||
3075                    flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP) {
3076                        int nh_len = flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 ?
3077                                        sizeof(struct ipv6hdr) :
3078                                        sizeof(struct iphdr);
3079
3080                        skb_set_transport_header(skb, mac_len + nh_len);
3081                }
3082
3083                /* Match skb->protocol to new outer l3 protocol */
3084                if (skb->protocol == htons(ETH_P_IP) &&
3085                    flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3086                        skb->protocol = htons(ETH_P_IPV6);
3087                else if (skb->protocol == htons(ETH_P_IPV6) &&
3088                         flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3089                        skb->protocol = htons(ETH_P_IP);
3090        }
3091
3092        if (skb_is_gso(skb)) {
3093                struct skb_shared_info *shinfo = skb_shinfo(skb);
3094
3095                /* Due to header grow, MSS needs to be downgraded. */
3096                if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3097                        skb_decrease_gso_size(shinfo, len_diff);
3098
3099                /* Header must be checked, and gso_segs recomputed. */
3100                shinfo->gso_type |= gso_type;
3101                shinfo->gso_segs = 0;
3102        }
3103
3104        return 0;
3105}
3106
3107static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff,
3108                              u64 flags)
3109{
3110        int ret;
3111
3112        if (flags & ~BPF_F_ADJ_ROOM_FIXED_GSO)
3113                return -EINVAL;
3114
3115        if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3116                /* udp gso_size delineates datagrams, only allow if fixed */
3117                if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3118                    !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3119                        return -ENOTSUPP;
3120        }
3121
3122        ret = skb_unclone(skb, GFP_ATOMIC);
3123        if (unlikely(ret < 0))
3124                return ret;
3125
3126        ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
3127        if (unlikely(ret < 0))
3128                return ret;
3129
3130        if (skb_is_gso(skb)) {
3131                struct skb_shared_info *shinfo = skb_shinfo(skb);
3132
3133                /* Due to header shrink, MSS can be upgraded. */
3134                if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3135                        skb_increase_gso_size(shinfo, len_diff);
3136
3137                /* Header must be checked, and gso_segs recomputed. */
3138                shinfo->gso_type |= SKB_GSO_DODGY;
3139                shinfo->gso_segs = 0;
3140        }
3141
3142        return 0;
3143}
3144
3145static u32 __bpf_skb_max_len(const struct sk_buff *skb)
3146{
3147        return skb->dev ? skb->dev->mtu + skb->dev->hard_header_len :
3148                          SKB_MAX_ALLOC;
3149}
3150
3151BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
3152           u32, mode, u64, flags)
3153{
3154        u32 len_cur, len_diff_abs = abs(len_diff);
3155        u32 len_min = bpf_skb_net_base_len(skb);
3156        u32 len_max = __bpf_skb_max_len(skb);
3157        __be16 proto = skb->protocol;
3158        bool shrink = len_diff < 0;
3159        u32 off;
3160        int ret;
3161
3162        if (unlikely(flags & ~BPF_F_ADJ_ROOM_MASK))
3163                return -EINVAL;
3164        if (unlikely(len_diff_abs > 0xfffU))
3165                return -EFAULT;
3166        if (unlikely(proto != htons(ETH_P_IP) &&
3167                     proto != htons(ETH_P_IPV6)))
3168                return -ENOTSUPP;
3169
3170        off = skb_mac_header_len(skb);
3171        switch (mode) {
3172        case BPF_ADJ_ROOM_NET:
3173                off += bpf_skb_net_base_len(skb);
3174                break;
3175        case BPF_ADJ_ROOM_MAC:
3176                break;
3177        default:
3178                return -ENOTSUPP;
3179        }
3180
3181        len_cur = skb->len - skb_network_offset(skb);
3182        if ((shrink && (len_diff_abs >= len_cur ||
3183                        len_cur - len_diff_abs < len_min)) ||
3184            (!shrink && (skb->len + len_diff_abs > len_max &&
3185                         !skb_is_gso(skb))))
3186                return -ENOTSUPP;
3187
3188        ret = shrink ? bpf_skb_net_shrink(skb, off, len_diff_abs, flags) :
3189                       bpf_skb_net_grow(skb, off, len_diff_abs, flags);
3190
3191        bpf_compute_data_pointers(skb);
3192        return ret;
3193}
3194
3195static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
3196        .func           = bpf_skb_adjust_room,
3197        .gpl_only       = false,
3198        .ret_type       = RET_INTEGER,
3199        .arg1_type      = ARG_PTR_TO_CTX,
3200        .arg2_type      = ARG_ANYTHING,
3201        .arg3_type      = ARG_ANYTHING,
3202        .arg4_type      = ARG_ANYTHING,
3203};
3204
3205static u32 __bpf_skb_min_len(const struct sk_buff *skb)
3206{
3207        u32 min_len = skb_network_offset(skb);
3208
3209        if (skb_transport_header_was_set(skb))
3210                min_len = skb_transport_offset(skb);
3211        if (skb->ip_summed == CHECKSUM_PARTIAL)
3212                min_len = skb_checksum_start_offset(skb) +
3213                          skb->csum_offset + sizeof(__sum16);
3214        return min_len;
3215}
3216
3217static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
3218{
3219        unsigned int old_len = skb->len;
3220        int ret;
3221
3222        ret = __skb_grow_rcsum(skb, new_len);
3223        if (!ret)
3224                memset(skb->data + old_len, 0, new_len - old_len);
3225        return ret;
3226}
3227
3228static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
3229{
3230        return __skb_trim_rcsum(skb, new_len);
3231}
3232
3233static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len,
3234                                        u64 flags)
3235{
3236        u32 max_len = __bpf_skb_max_len(skb);
3237        u32 min_len = __bpf_skb_min_len(skb);
3238        int ret;
3239
3240        if (unlikely(flags || new_len > max_len || new_len < min_len))
3241                return -EINVAL;
3242        if (skb->encapsulation)
3243                return -ENOTSUPP;
3244
3245        /* The basic idea of this helper is that it's performing the
3246         * needed work to either grow or trim an skb, and eBPF program
3247         * rewrites the rest via helpers like bpf_skb_store_bytes(),
3248         * bpf_lX_csum_replace() and others rather than passing a raw
3249         * buffer here. This one is a slow path helper and intended
3250         * for replies with control messages.
3251         *
3252         * Like in bpf_skb_change_proto(), we want to keep this rather
3253         * minimal and without protocol specifics so that we are able
3254         * to separate concerns as in bpf_skb_store_bytes() should only
3255         * be the one responsible for writing buffers.
3256         *
3257         * It's really expected to be a slow path operation here for
3258         * control message replies, so we're implicitly linearizing,
3259         * uncloning and drop offloads from the skb by this.
3260         */
3261        ret = __bpf_try_make_writable(skb, skb->len);
3262        if (!ret) {
3263                if (new_len > skb->len)
3264                        ret = bpf_skb_grow_rcsum(skb, new_len);
3265                else if (new_len < skb->len)
3266                        ret = bpf_skb_trim_rcsum(skb, new_len);
3267                if (!ret && skb_is_gso(skb))
3268                        skb_gso_reset(skb);
3269        }
3270        return ret;
3271}
3272
3273BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3274           u64, flags)
3275{
3276        int ret = __bpf_skb_change_tail(skb, new_len, flags);
3277
3278        bpf_compute_data_pointers(skb);
3279        return ret;
3280}
3281
3282static const struct bpf_func_proto bpf_skb_change_tail_proto = {
3283        .func           = bpf_skb_change_tail,
3284        .gpl_only       = false,
3285        .ret_type       = RET_INTEGER,
3286        .arg1_type      = ARG_PTR_TO_CTX,
3287        .arg2_type      = ARG_ANYTHING,
3288        .arg3_type      = ARG_ANYTHING,
3289};
3290
3291BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3292           u64, flags)
3293{
3294        int ret = __bpf_skb_change_tail(skb, new_len, flags);
3295
3296        bpf_compute_data_end_sk_skb(skb);
3297        return ret;
3298}
3299
3300static const struct bpf_func_proto sk_skb_change_tail_proto = {
3301        .func           = sk_skb_change_tail,
3302        .gpl_only       = false,
3303        .ret_type       = RET_INTEGER,
3304        .arg1_type      = ARG_PTR_TO_CTX,
3305        .arg2_type      = ARG_ANYTHING,
3306        .arg3_type      = ARG_ANYTHING,
3307};
3308
3309static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room,
3310                                        u64 flags)
3311{
3312        u32 max_len = __bpf_skb_max_len(skb);
3313        u32 new_len = skb->len + head_room;
3314        int ret;
3315
3316        if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
3317                     new_len < skb->len))
3318                return -EINVAL;
3319
3320        ret = skb_cow(skb, head_room);
3321        if (likely(!ret)) {
3322                /* Idea for this helper is that we currently only
3323                 * allow to expand on mac header. This means that
3324                 * skb->protocol network header, etc, stay as is.
3325                 * Compared to bpf_skb_change_tail(), we're more
3326                 * flexible due to not needing to linearize or
3327                 * reset GSO. Intention for this helper is to be
3328                 * used by an L3 skb that needs to push mac header
3329                 * for redirection into L2 device.
3330                 */
3331                __skb_push(skb, head_room);
3332                memset(skb->data, 0, head_room);
3333                skb_reset_mac_header(skb);
3334        }
3335
3336        return ret;
3337}
3338
3339BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
3340           u64, flags)
3341{
3342        int ret = __bpf_skb_change_head(skb, head_room, flags);
3343
3344        bpf_compute_data_pointers(skb);
3345        return ret;
3346}
3347
3348static const struct bpf_func_proto bpf_skb_change_head_proto = {
3349        .func           = bpf_skb_change_head,
3350        .gpl_only       = false,
3351        .ret_type       = RET_INTEGER,
3352        .arg1_type      = ARG_PTR_TO_CTX,
3353        .arg2_type      = ARG_ANYTHING,
3354        .arg3_type      = ARG_ANYTHING,
3355};
3356
3357BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room,
3358           u64, flags)
3359{
3360        int ret = __bpf_skb_change_head(skb, head_room, flags);
3361
3362        bpf_compute_data_end_sk_skb(skb);
3363        return ret;
3364}
3365
3366static const struct bpf_func_proto sk_skb_change_head_proto = {
3367        .func           = sk_skb_change_head,
3368        .gpl_only       = false,
3369        .ret_type       = RET_INTEGER,
3370        .arg1_type      = ARG_PTR_TO_CTX,
3371        .arg2_type      = ARG_ANYTHING,
3372        .arg3_type      = ARG_ANYTHING,
3373};
3374static unsigned long xdp_get_metalen(const struct xdp_buff *xdp)
3375{
3376        return xdp_data_meta_unsupported(xdp) ? 0 :
3377               xdp->data - xdp->data_meta;
3378}
3379
3380BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
3381{
3382        void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3383        unsigned long metalen = xdp_get_metalen(xdp);
3384        void *data_start = xdp_frame_end + metalen;
3385        void *data = xdp->data + offset;
3386
3387        if (unlikely(data < data_start ||
3388                     data > xdp->data_end - ETH_HLEN))
3389                return -EINVAL;
3390
3391        if (metalen)
3392                memmove(xdp->data_meta + offset,
3393                        xdp->data_meta, metalen);
3394        xdp->data_meta += offset;
3395        xdp->data = data;
3396
3397        return 0;
3398}
3399
3400static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
3401        .func           = bpf_xdp_adjust_head,
3402        .gpl_only       = false,
3403        .ret_type       = RET_INTEGER,
3404        .arg1_type      = ARG_PTR_TO_CTX,
3405        .arg2_type      = ARG_ANYTHING,
3406};
3407
3408BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
3409{
3410        void *data_end = xdp->data_end + offset;
3411
3412        /* only shrinking is allowed for now. */
3413        if (unlikely(offset >= 0))
3414                return -EINVAL;
3415
3416        if (unlikely(data_end < xdp->data + ETH_HLEN))
3417                return -EINVAL;
3418
3419        xdp->data_end = data_end;
3420
3421        return 0;
3422}
3423
3424static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
3425        .func           = bpf_xdp_adjust_tail,
3426        .gpl_only       = false,
3427        .ret_type       = RET_INTEGER,
3428        .arg1_type      = ARG_PTR_TO_CTX,
3429        .arg2_type      = ARG_ANYTHING,
3430};
3431
3432BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
3433{
3434        void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3435        void *meta = xdp->data_meta + offset;
3436        unsigned long metalen = xdp->data - meta;
3437
3438        if (xdp_data_meta_unsupported(xdp))
3439                return -ENOTSUPP;
3440        if (unlikely(meta < xdp_frame_end ||
3441                     meta > xdp->data))
3442                return -EINVAL;
3443        if (unlikely((metalen & (sizeof(__u32) - 1)) ||
3444                     (metalen > 32)))
3445                return -EACCES;
3446
3447        xdp->data_meta = meta;
3448
3449        return 0;
3450}
3451
3452static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
3453        .func           = bpf_xdp_adjust_meta,
3454        .gpl_only       = false,
3455        .ret_type       = RET_INTEGER,
3456        .arg1_type      = ARG_PTR_TO_CTX,
3457        .arg2_type      = ARG_ANYTHING,
3458};
3459
3460static int __bpf_tx_xdp(struct net_device *dev,
3461                        struct bpf_map *map,
3462                        struct xdp_buff *xdp,
3463                        u32 index)
3464{
3465        struct xdp_frame *xdpf;
3466        int err, sent;
3467
3468        if (!dev->netdev_ops->ndo_xdp_xmit) {
3469                return -EOPNOTSUPP;
3470        }
3471
3472        err = xdp_ok_fwd_dev(dev, xdp->data_end - xdp->data);
3473        if (unlikely(err))
3474                return err;
3475
3476        xdpf = convert_to_xdp_frame(xdp);
3477        if (unlikely(!xdpf))
3478                return -EOVERFLOW;
3479
3480        sent = dev->netdev_ops->ndo_xdp_xmit(dev, 1, &xdpf, XDP_XMIT_FLUSH);
3481        if (sent <= 0)
3482                return sent;
3483        return 0;
3484}
3485
3486static noinline int
3487xdp_do_redirect_slow(struct net_device *dev, struct xdp_buff *xdp,
3488                     struct bpf_prog *xdp_prog, struct bpf_redirect_info *ri)
3489{
3490        struct net_device *fwd;
3491        u32 index = ri->tgt_index;
3492        int err;
3493
3494        fwd = dev_get_by_index_rcu(dev_net(dev), index);
3495        ri->tgt_index = 0;
3496        if (unlikely(!fwd)) {
3497                err = -EINVAL;
3498                goto err;
3499        }
3500
3501        err = __bpf_tx_xdp(fwd, NULL, xdp, 0);
3502        if (unlikely(err))
3503                goto err;
3504
3505        _trace_xdp_redirect(dev, xdp_prog, index);
3506        return 0;
3507err:
3508        _trace_xdp_redirect_err(dev, xdp_prog, index, err);
3509        return err;
3510}
3511
3512static int __bpf_tx_xdp_map(struct net_device *dev_rx, void *fwd,
3513                            struct bpf_map *map,
3514                            struct xdp_buff *xdp,
3515                            u32 index)
3516{
3517        int err;
3518
3519        switch (map->map_type) {
3520        case BPF_MAP_TYPE_DEVMAP: {
3521                struct bpf_dtab_netdev *dst = fwd;
3522
3523                err = dev_map_enqueue(dst, xdp, dev_rx);
3524                if (unlikely(err))
3525                        return err;
3526                break;
3527        }
3528        case BPF_MAP_TYPE_CPUMAP: {
3529                struct bpf_cpu_map_entry *rcpu = fwd;
3530
3531                err = cpu_map_enqueue(rcpu, xdp, dev_rx);
3532                if (unlikely(err))
3533                        return err;
3534                break;
3535        }
3536        case BPF_MAP_TYPE_XSKMAP: {
3537                struct xdp_sock *xs = fwd;
3538
3539                err = __xsk_map_redirect(map, xdp, xs);
3540                return err;
3541        }
3542        default:
3543                break;
3544        }
3545        return 0;
3546}
3547
3548void xdp_do_flush_map(void)
3549{
3550        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3551        struct bpf_map *map = ri->map_to_flush;
3552
3553        ri->map_to_flush = NULL;
3554        if (map) {
3555                switch (map->map_type) {
3556                case BPF_MAP_TYPE_DEVMAP:
3557                        __dev_map_flush(map);
3558                        break;
3559                case BPF_MAP_TYPE_CPUMAP:
3560                        __cpu_map_flush(map);
3561                        break;
3562                case BPF_MAP_TYPE_XSKMAP:
3563                        __xsk_map_flush(map);
3564                        break;
3565                default:
3566                        break;
3567                }
3568        }
3569}
3570EXPORT_SYMBOL_GPL(xdp_do_flush_map);
3571
3572static inline void *__xdp_map_lookup_elem(struct bpf_map *map, u32 index)
3573{
3574        switch (map->map_type) {
3575        case BPF_MAP_TYPE_DEVMAP:
3576                return __dev_map_lookup_elem(map, index);
3577        case BPF_MAP_TYPE_CPUMAP:
3578                return __cpu_map_lookup_elem(map, index);
3579        case BPF_MAP_TYPE_XSKMAP:
3580                return __xsk_map_lookup_elem(map, index);
3581        default:
3582                return NULL;
3583        }
3584}
3585
3586void bpf_clear_redirect_map(struct bpf_map *map)
3587{
3588        struct bpf_redirect_info *ri;
3589        int cpu;
3590
3591        for_each_possible_cpu(cpu) {
3592                ri = per_cpu_ptr(&bpf_redirect_info, cpu);
3593                /* Avoid polluting remote cacheline due to writes if
3594                 * not needed. Once we pass this test, we need the
3595                 * cmpxchg() to make sure it hasn't been changed in
3596                 * the meantime by remote CPU.
3597                 */
3598                if (unlikely(READ_ONCE(ri->map) == map))
3599                        cmpxchg(&ri->map, map, NULL);
3600        }
3601}
3602
3603static int xdp_do_redirect_map(struct net_device *dev, struct xdp_buff *xdp,
3604                               struct bpf_prog *xdp_prog, struct bpf_map *map,
3605                               struct bpf_redirect_info *ri)
3606{
3607        u32 index = ri->tgt_index;
3608        void *fwd = ri->tgt_value;
3609        int err;
3610
3611        ri->tgt_index = 0;
3612        ri->tgt_value = NULL;
3613        WRITE_ONCE(ri->map, NULL);
3614
3615        if (ri->map_to_flush && unlikely(ri->map_to_flush != map))
3616                xdp_do_flush_map();
3617
3618        err = __bpf_tx_xdp_map(dev, fwd, map, xdp, index);
3619        if (unlikely(err))
3620                goto err;
3621
3622        ri->map_to_flush = map;
3623        _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3624        return 0;
3625err:
3626        _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3627        return err;
3628}
3629
3630int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
3631                    struct bpf_prog *xdp_prog)
3632{
3633        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3634        struct bpf_map *map = READ_ONCE(ri->map);
3635
3636        if (likely(map))
3637                return xdp_do_redirect_map(dev, xdp, xdp_prog, map, ri);
3638
3639        return xdp_do_redirect_slow(dev, xdp, xdp_prog, ri);
3640}
3641EXPORT_SYMBOL_GPL(xdp_do_redirect);
3642
3643static int xdp_do_generic_redirect_map(struct net_device *dev,
3644                                       struct sk_buff *skb,
3645                                       struct xdp_buff *xdp,
3646                                       struct bpf_prog *xdp_prog,
3647                                       struct bpf_map *map)
3648{
3649        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3650        u32 index = ri->tgt_index;
3651        void *fwd = ri->tgt_value;
3652        int err = 0;
3653
3654        ri->tgt_index = 0;
3655        ri->tgt_value = NULL;
3656        WRITE_ONCE(ri->map, NULL);
3657
3658        if (map->map_type == BPF_MAP_TYPE_DEVMAP) {
3659                struct bpf_dtab_netdev *dst = fwd;
3660
3661                err = dev_map_generic_redirect(dst, skb, xdp_prog);
3662                if (unlikely(err))
3663                        goto err;
3664        } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
3665                struct xdp_sock *xs = fwd;
3666
3667                err = xsk_generic_rcv(xs, xdp);
3668                if (err)
3669                        goto err;
3670                consume_skb(skb);
3671        } else {
3672                /* TODO: Handle BPF_MAP_TYPE_CPUMAP */
3673                err = -EBADRQC;
3674                goto err;
3675        }
3676
3677        _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3678        return 0;
3679err:
3680        _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3681        return err;
3682}
3683
3684int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
3685                            struct xdp_buff *xdp, struct bpf_prog *xdp_prog)
3686{
3687        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3688        struct bpf_map *map = READ_ONCE(ri->map);
3689        u32 index = ri->tgt_index;
3690        struct net_device *fwd;
3691        int err = 0;
3692
3693        if (map)
3694                return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog,
3695                                                   map);
3696        ri->tgt_index = 0;
3697        fwd = dev_get_by_index_rcu(dev_net(dev), index);
3698        if (unlikely(!fwd)) {
3699                err = -EINVAL;
3700                goto err;
3701        }
3702
3703        err = xdp_ok_fwd_dev(fwd, skb->len);
3704        if (unlikely(err))
3705                goto err;
3706
3707        skb->dev = fwd;
3708        _trace_xdp_redirect(dev, xdp_prog, index);
3709        generic_xdp_tx(skb, xdp_prog);
3710        return 0;
3711err:
3712        _trace_xdp_redirect_err(dev, xdp_prog, index, err);
3713        return err;
3714}
3715EXPORT_SYMBOL_GPL(xdp_do_generic_redirect);
3716
3717BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
3718{
3719        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3720
3721        if (unlikely(flags))
3722                return XDP_ABORTED;
3723
3724        ri->flags = flags;
3725        ri->tgt_index = ifindex;
3726        ri->tgt_value = NULL;
3727        WRITE_ONCE(ri->map, NULL);
3728
3729        return XDP_REDIRECT;
3730}
3731
3732static const struct bpf_func_proto bpf_xdp_redirect_proto = {
3733        .func           = bpf_xdp_redirect,
3734        .gpl_only       = false,
3735        .ret_type       = RET_INTEGER,
3736        .arg1_type      = ARG_ANYTHING,
3737        .arg2_type      = ARG_ANYTHING,
3738};
3739
3740BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u32, ifindex,
3741           u64, flags)
3742{
3743        struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3744
3745        /* Lower bits of the flags are used as return code on lookup failure */
3746        if (unlikely(flags > XDP_TX))
3747                return XDP_ABORTED;
3748
3749        ri->tgt_value = __xdp_map_lookup_elem(map, ifindex);
3750        if (unlikely(!ri->tgt_value)) {
3751                /* If the lookup fails we want to clear out the state in the
3752                 * redirect_info struct completely, so that if an eBPF program
3753                 * performs multiple lookups, the last one always takes
3754                 * precedence.
3755                 */
3756                WRITE_ONCE(ri->map, NULL);
3757                return flags;
3758        }
3759
3760        ri->flags = flags;
3761        ri->tgt_index = ifindex;
3762        WRITE_ONCE(ri->map, map);
3763
3764        return XDP_REDIRECT;
3765}
3766
3767static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
3768        .func           = bpf_xdp_redirect_map,
3769        .gpl_only       = false,
3770        .ret_type       = RET_INTEGER,
3771        .arg1_type      = ARG_CONST_MAP_PTR,
3772        .arg2_type      = ARG_ANYTHING,
3773        .arg3_type      = ARG_ANYTHING,
3774};
3775
3776static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
3777                                  unsigned long off, unsigned long len)
3778{
3779        void *ptr = skb_header_pointer(skb, off, len, dst_buff);
3780
3781        if (unlikely(!ptr))
3782                return len;
3783        if (ptr != dst_buff)
3784                memcpy(dst_buff, ptr, len);
3785
3786        return 0;
3787}
3788
3789BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
3790           u64, flags, void *, meta, u64, meta_size)
3791{
3792        u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
3793
3794        if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
3795                return -EINVAL;
3796        if (unlikely(skb_size > skb->len))
3797                return -EFAULT;
3798
3799        return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
3800                                bpf_skb_copy);
3801}
3802
3803static const struct bpf_func_proto bpf_skb_event_output_proto = {
3804        .func           = bpf_skb_event_output,
3805        .gpl_only       = true,
3806        .ret_type       = RET_INTEGER,
3807        .arg1_type      = ARG_PTR_TO_CTX,
3808        .arg2_type      = ARG_CONST_MAP_PTR,
3809        .arg3_type      = ARG_ANYTHING,
3810        .arg4_type      = ARG_PTR_TO_MEM,
3811        .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
3812};
3813
3814static unsigned short bpf_tunnel_key_af(u64 flags)
3815{
3816        return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
3817}
3818
3819BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
3820           u32, size, u64, flags)
3821{
3822        const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3823        u8 compat[sizeof(struct bpf_tunnel_key)];
3824        void *to_orig = to;
3825        int err;
3826
3827        if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) {
3828                err = -EINVAL;
3829                goto err_clear;
3830        }
3831        if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
3832                err = -EPROTO;
3833                goto err_clear;
3834        }
3835        if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3836                err = -EINVAL;
3837                switch (size) {
3838                case offsetof(struct bpf_tunnel_key, tunnel_label):
3839                case offsetof(struct bpf_tunnel_key, tunnel_ext):
3840                        goto set_compat;
3841                case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3842                        /* Fixup deprecated structure layouts here, so we have
3843                         * a common path later on.
3844                         */
3845                        if (ip_tunnel_info_af(info) != AF_INET)
3846                                goto err_clear;
3847set_compat:
3848                        to = (struct bpf_tunnel_key *)compat;
3849                        break;
3850                default:
3851                        goto err_clear;
3852                }
3853        }
3854
3855        to->tunnel_id = be64_to_cpu(info->key.tun_id);
3856        to->tunnel_tos = info->key.tos;
3857        to->tunnel_ttl = info->key.ttl;
3858        to->tunnel_ext = 0;
3859
3860        if (flags & BPF_F_TUNINFO_IPV6) {
3861                memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
3862                       sizeof(to->remote_ipv6));
3863                to->tunnel_label = be32_to_cpu(info->key.label);
3864        } else {
3865                to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
3866                memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
3867                to->tunnel_label = 0;
3868        }
3869
3870        if (unlikely(size != sizeof(struct bpf_tunnel_key)))
3871                memcpy(to_orig, to, size);
3872
3873        return 0;
3874err_clear:
3875        memset(to_orig, 0, size);
3876        return err;
3877}
3878
3879static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
3880        .func           = bpf_skb_get_tunnel_key,
3881        .gpl_only       = false,
3882        .ret_type       = RET_INTEGER,
3883        .arg1_type      = ARG_PTR_TO_CTX,
3884        .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
3885        .arg3_type      = ARG_CONST_SIZE,
3886        .arg4_type      = ARG_ANYTHING,
3887};
3888
3889BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
3890{
3891        const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3892        int err;
3893
3894        if (unlikely(!info ||
3895                     !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
3896                err = -ENOENT;
3897                goto err_clear;
3898        }
3899        if (unlikely(size < info->options_len)) {
3900                err = -ENOMEM;
3901                goto err_clear;
3902        }
3903
3904        ip_tunnel_info_opts_get(to, info);
3905        if (size > info->options_len)
3906                memset(to + info->options_len, 0, size - info->options_len);
3907
3908        return info->options_len;
3909err_clear:
3910        memset(to, 0, size);
3911        return err;
3912}
3913
3914static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
3915        .func           = bpf_skb_get_tunnel_opt,
3916        .gpl_only       = false,
3917        .ret_type       = RET_INTEGER,
3918        .arg1_type      = ARG_PTR_TO_CTX,
3919        .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
3920        .arg3_type      = ARG_CONST_SIZE,
3921};
3922
3923static struct metadata_dst __percpu *md_dst;
3924
3925BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
3926           const struct bpf_tunnel_key *, from, u32, size, u64, flags)
3927{
3928        struct metadata_dst *md = this_cpu_ptr(md_dst);
3929        u8 compat[sizeof(struct bpf_tunnel_key)];
3930        struct ip_tunnel_info *info;
3931
3932        if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
3933                               BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER)))
3934                return -EINVAL;
3935        if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3936                switch (size) {
3937                case offsetof(struct bpf_tunnel_key, tunnel_label):
3938                case offsetof(struct bpf_tunnel_key, tunnel_ext):
3939                case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3940                        /* Fixup deprecated structure layouts here, so we have
3941                         * a common path later on.
3942                         */
3943                        memcpy(compat, from, size);
3944                        memset(compat + size, 0, sizeof(compat) - size);
3945                        from = (const struct bpf_tunnel_key *) compat;
3946                        break;
3947                default:
3948                        return -EINVAL;
3949                }
3950        }
3951        if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
3952                     from->tunnel_ext))
3953                return -EINVAL;
3954
3955        skb_dst_drop(skb);
3956        dst_hold((struct dst_entry *) md);
3957        skb_dst_set(skb, (struct dst_entry *) md);
3958
3959        info = &md->u.tun_info;
3960        memset(info, 0, sizeof(*info));
3961        info->mode = IP_TUNNEL_INFO_TX;
3962
3963        info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
3964        if (flags & BPF_F_DONT_FRAGMENT)
3965                info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;
3966        if (flags & BPF_F_ZERO_CSUM_TX)
3967                info->key.tun_flags &= ~TUNNEL_CSUM;
3968        if (flags & BPF_F_SEQ_NUMBER)
3969                info->key.tun_flags |= TUNNEL_SEQ;
3970
3971        info->key.tun_id = cpu_to_be64(from->tunnel_id);
3972        info->key.tos = from->tunnel_tos;
3973        info->key.ttl = from->tunnel_ttl;
3974
3975        if (flags & BPF_F_TUNINFO_IPV6) {
3976                info->mode |= IP_TUNNEL_INFO_IPV6;
3977                memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
3978                       sizeof(from->remote_ipv6));
3979                info->key.label = cpu_to_be32(from->tunnel_label) &
3980                                  IPV6_FLOWLABEL_MASK;
3981        } else {
3982                info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
3983        }
3984
3985        return 0;
3986}
3987
3988static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
3989        .func           = bpf_skb_set_tunnel_key,
3990        .gpl_only       = false,
3991        .ret_type       = RET_INTEGER,
3992        .arg1_type      = ARG_PTR_TO_CTX,
3993        .arg2_type      = ARG_PTR_TO_MEM,
3994        .arg3_type      = ARG_CONST_SIZE,
3995        .arg4_type      = ARG_ANYTHING,
3996};
3997
3998BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
3999           const u8 *, from, u32, size)
4000{
4001        struct ip_tunnel_info *info = skb_tunnel_info(skb);
4002        const struct metadata_dst *md = this_cpu_ptr(md_dst);
4003
4004        if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
4005                return -EINVAL;
4006        if (unlikely(size > IP_TUNNEL_OPTS_MAX))
4007                return -ENOMEM;
4008
4009        ip_tunnel_info_opts_set(info, from, size, TUNNEL_OPTIONS_PRESENT);
4010
4011        return 0;
4012}
4013
4014static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
4015        .func           = bpf_skb_set_tunnel_opt,
4016        .gpl_only       = false,
4017        .ret_type       = RET_INTEGER,
4018        .arg1_type      = ARG_PTR_TO_CTX,
4019        .arg2_type      = ARG_PTR_TO_MEM,
4020        .arg3_type      = ARG_CONST_SIZE,
4021};
4022
4023static const struct bpf_func_proto *
4024bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
4025{
4026        if (!md_dst) {
4027                struct metadata_dst __percpu *tmp;
4028
4029                tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
4030                                                METADATA_IP_TUNNEL,
4031                                                GFP_KERNEL);
4032                if (!tmp)
4033                        return NULL;
4034                if (cmpxchg(&md_dst, NULL, tmp))
4035                        metadata_dst_free_percpu(tmp);
4036        }
4037
4038        switch (which) {
4039        case BPF_FUNC_skb_set_tunnel_key:
4040                return &bpf_skb_set_tunnel_key_proto;
4041        case BPF_FUNC_skb_set_tunnel_opt:
4042                return &bpf_skb_set_tunnel_opt_proto;
4043        default:
4044                return NULL;
4045        }
4046}
4047
4048BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
4049           u32, idx)
4050{
4051        struct bpf_array *array = container_of(map, struct bpf_array, map);
4052        struct cgroup *cgrp;
4053        struct sock *sk;
4054
4055        sk = skb_to_full_sk(skb);
4056        if (!sk || !sk_fullsock(sk))
4057                return -ENOENT;
4058        if (unlikely(idx >= array->map.max_entries))
4059                return -E2BIG;
4060
4061        cgrp = READ_ONCE(array->ptrs[idx]);
4062        if (unlikely(!cgrp))
4063                return -EAGAIN;
4064
4065        return sk_under_cgroup_hierarchy(sk, cgrp);
4066}
4067
4068static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
4069        .func           = bpf_skb_under_cgroup,
4070        .gpl_only       = false,
4071        .ret_type       = RET_INTEGER,
4072        .arg1_type      = ARG_PTR_TO_CTX,
4073        .arg2_type      = ARG_CONST_MAP_PTR,
4074        .arg3_type      = ARG_ANYTHING,
4075};
4076
4077#ifdef CONFIG_SOCK_CGROUP_DATA
4078BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
4079{
4080        struct sock *sk = skb_to_full_sk(skb);
4081        struct cgroup *cgrp;
4082
4083        if (!sk || !sk_fullsock(sk))
4084                return 0;
4085
4086        cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4087        return cgrp->kn->id.id;
4088}
4089
4090static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
4091        .func           = bpf_skb_cgroup_id,
4092        .gpl_only       = false,
4093        .ret_type       = RET_INTEGER,
4094        .arg1_type      = ARG_PTR_TO_CTX,
4095};
4096
4097BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
4098           ancestor_level)
4099{
4100        struct sock *sk = skb_to_full_sk(skb);
4101        struct cgroup *ancestor;
4102        struct cgroup *cgrp;
4103
4104        if (!sk || !sk_fullsock(sk))
4105                return 0;
4106
4107        cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4108        ancestor = cgroup_ancestor(cgrp, ancestor_level);
4109        if (!ancestor)
4110                return 0;
4111
4112        return ancestor->kn->id.id;
4113}
4114
4115static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
4116        .func           = bpf_skb_ancestor_cgroup_id,
4117        .gpl_only       = false,
4118        .ret_type       = RET_INTEGER,
4119        .arg1_type      = ARG_PTR_TO_CTX,
4120        .arg2_type      = ARG_ANYTHING,
4121};
4122#endif
4123
4124static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff,
4125                                  unsigned long off, unsigned long len)
4126{
4127        memcpy(dst_buff, src_buff + off, len);
4128        return 0;
4129}
4130
4131BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
4132           u64, flags, void *, meta, u64, meta_size)
4133{
4134        u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
4135
4136        if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
4137                return -EINVAL;
4138        if (unlikely(xdp_size > (unsigned long)(xdp->data_end - xdp->data)))
4139                return -EFAULT;
4140
4141        return bpf_event_output(map, flags, meta, meta_size, xdp->data,
4142                                xdp_size, bpf_xdp_copy);
4143}
4144
4145static const struct bpf_func_proto bpf_xdp_event_output_proto = {
4146        .func           = bpf_xdp_event_output,
4147        .gpl_only       = true,
4148        .ret_type       = RET_INTEGER,
4149        .arg1_type      = ARG_PTR_TO_CTX,
4150        .arg2_type      = ARG_CONST_MAP_PTR,
4151        .arg3_type      = ARG_ANYTHING,
4152        .arg4_type      = ARG_PTR_TO_MEM,
4153        .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
4154};
4155
4156BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
4157{
4158        return skb->sk ? sock_gen_cookie(skb->sk) : 0;
4159}
4160
4161static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
4162        .func           = bpf_get_socket_cookie,
4163        .gpl_only       = false,
4164        .ret_type       = RET_INTEGER,
4165        .arg1_type      = ARG_PTR_TO_CTX,
4166};
4167
4168BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
4169{
4170        return sock_gen_cookie(ctx->sk);
4171}
4172
4173static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
4174        .func           = bpf_get_socket_cookie_sock_addr,
4175        .gpl_only       = false,
4176        .ret_type       = RET_INTEGER,
4177        .arg1_type      = ARG_PTR_TO_CTX,
4178};
4179
4180BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
4181{
4182        return sock_gen_cookie(ctx->sk);
4183}
4184
4185static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
4186        .func           = bpf_get_socket_cookie_sock_ops,
4187        .gpl_only       = false,
4188        .ret_type       = RET_INTEGER,
4189        .arg1_type      = ARG_PTR_TO_CTX,
4190};
4191
4192BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
4193{
4194        struct sock *sk = sk_to_full_sk(skb->sk);
4195        kuid_t kuid;
4196
4197        if (!sk || !sk_fullsock(sk))
4198                return overflowuid;
4199        kuid = sock_net_uid(sock_net(sk), sk);
4200        return from_kuid_munged(sock_net(sk)->user_ns, kuid);
4201}
4202
4203static const struct bpf_func_proto bpf_get_socket_uid_proto = {
4204        .func           = bpf_get_socket_uid,
4205        .gpl_only       = false,
4206        .ret_type       = RET_INTEGER,
4207        .arg1_type      = ARG_PTR_TO_CTX,
4208};
4209
4210BPF_CALL_5(bpf_sockopt_event_output, struct bpf_sock_ops_kern *, bpf_sock,
4211           struct bpf_map *, map, u64, flags, void *, data, u64, size)
4212{
4213        if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
4214                return -EINVAL;
4215
4216        return bpf_event_output(map, flags, data, size, NULL, 0, NULL);
4217}
4218
4219static const struct bpf_func_proto bpf_sockopt_event_output_proto =  {
4220        .func           = bpf_sockopt_event_output,
4221        .gpl_only       = true,
4222        .ret_type       = RET_INTEGER,
4223        .arg1_type      = ARG_PTR_TO_CTX,
4224        .arg2_type      = ARG_CONST_MAP_PTR,
4225        .arg3_type      = ARG_ANYTHING,
4226        .arg4_type      = ARG_PTR_TO_MEM,
4227        .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
4228};
4229
4230BPF_CALL_5(bpf_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4231           int, level, int, optname, char *, optval, int, optlen)
4232{
4233        struct sock *sk = bpf_sock->sk;
4234        int ret = 0;
4235        int val;
4236
4237        if (!sk_fullsock(sk))
4238                return -EINVAL;
4239
4240        if (level == SOL_SOCKET) {
4241                if (optlen != sizeof(int))
4242                        return -EINVAL;
4243                val = *((int *)optval);
4244
4245                /* Only some socketops are supported */
4246                switch (optname) {
4247                case SO_RCVBUF:
4248                        val = min_t(u32, val, sysctl_rmem_max);
4249                        sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
4250                        sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);
4251                        break;
4252                case SO_SNDBUF:
4253                        val = min_t(u32, val, sysctl_wmem_max);
4254                        sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
4255                        sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
4256                        break;
4257                case SO_MAX_PACING_RATE: /* 32bit version */
4258                        if (val != ~0U)
4259                                cmpxchg(&sk->sk_pacing_status,
4260                                        SK_PACING_NONE,
4261                                        SK_PACING_NEEDED);
4262                        sk->sk_max_pacing_rate = (val == ~0U) ? ~0UL : val;
4263                        sk->sk_pacing_rate = min(sk->sk_pacing_rate,
4264                                                 sk->sk_max_pacing_rate);
4265                        break;
4266                case SO_PRIORITY:
4267                        sk->sk_priority = val;
4268                        break;
4269                case SO_RCVLOWAT:
4270                        if (val < 0)
4271                                val = INT_MAX;
4272                        sk->sk_rcvlowat = val ? : 1;
4273                        break;
4274                case SO_MARK:
4275                        if (sk->sk_mark != val) {
4276                                sk->sk_mark = val;
4277                                sk_dst_reset(sk);
4278                        }
4279                        break;
4280                default:
4281                        ret = -EINVAL;
4282                }
4283#ifdef CONFIG_INET
4284        } else if (level == SOL_IP) {
4285                if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4286                        return -EINVAL;
4287
4288                val = *((int *)optval);
4289                /* Only some options are supported */
4290                switch (optname) {
4291                case IP_TOS:
4292                        if (val < -1 || val > 0xff) {
4293                                ret = -EINVAL;
4294                        } else {
4295                                struct inet_sock *inet = inet_sk(sk);
4296
4297                                if (val == -1)
4298                                        val = 0;
4299                                inet->tos = val;
4300                        }
4301                        break;
4302                default:
4303                        ret = -EINVAL;
4304                }
4305#if IS_ENABLED(CONFIG_IPV6)
4306        } else if (level == SOL_IPV6) {
4307                if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4308                        return -EINVAL;
4309
4310                val = *((int *)optval);
4311                /* Only some options are supported */
4312                switch (optname) {
4313                case IPV6_TCLASS:
4314                        if (val < -1 || val > 0xff) {
4315                                ret = -EINVAL;
4316                        } else {
4317                                struct ipv6_pinfo *np = inet6_sk(sk);
4318
4319                                if (val == -1)
4320                                        val = 0;
4321                                np->tclass = val;
4322                        }
4323                        break;
4324                default:
4325                        ret = -EINVAL;
4326                }
4327#endif
4328        } else if (level == SOL_TCP &&
4329                   sk->sk_prot->setsockopt == tcp_setsockopt) {
4330                if (optname == TCP_CONGESTION) {
4331                        char name[TCP_CA_NAME_MAX];
4332                        bool reinit = bpf_sock->op > BPF_SOCK_OPS_NEEDS_ECN;
4333
4334                        strncpy(name, optval, min_t(long, optlen,
4335                                                    TCP_CA_NAME_MAX-1));
4336                        name[TCP_CA_NAME_MAX-1] = 0;
4337                        ret = tcp_set_congestion_control(sk, name, false,
4338                                                         reinit, true);
4339                } else {
4340                        struct tcp_sock *tp = tcp_sk(sk);
4341
4342                        if (optlen != sizeof(int))
4343                                return -EINVAL;
4344
4345                        val = *((int *)optval);
4346                        /* Only some options are supported */
4347                        switch (optname) {
4348                        case TCP_BPF_IW:
4349                                if (val <= 0 || tp->data_segs_out > tp->syn_data)
4350                                        ret = -EINVAL;
4351                                else
4352                                        tp->snd_cwnd = val;
4353                                break;
4354                        case TCP_BPF_SNDCWND_CLAMP:
4355                                if (val <= 0) {
4356                                        ret = -EINVAL;
4357                                } else {
4358                                        tp->snd_cwnd_clamp = val;
4359                                        tp->snd_ssthresh = val;
4360                                }
4361                                break;
4362                        case TCP_SAVE_SYN:
4363                                if (val < 0 || val > 1)
4364                                        ret = -EINVAL;
4365                                else
4366                                        tp->save_syn = val;
4367                                break;
4368                        default:
4369                                ret = -EINVAL;
4370                        }
4371                }
4372#endif
4373        } else {
4374                ret = -EINVAL;
4375        }
4376        return ret;
4377}
4378
4379static const struct bpf_func_proto bpf_setsockopt_proto = {
4380        .func           = bpf_setsockopt,
4381        .gpl_only       = false,
4382        .ret_type       = RET_INTEGER,
4383        .arg1_type      = ARG_PTR_TO_CTX,
4384        .arg2_type      = ARG_ANYTHING,
4385        .arg3_type      = ARG_ANYTHING,
4386        .arg4_type      = ARG_PTR_TO_MEM,
4387        .arg5_type      = ARG_CONST_SIZE,
4388};
4389
4390BPF_CALL_5(bpf_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4391           int, level, int, optname, char *, optval, int, optlen)
4392{
4393        struct sock *sk = bpf_sock->sk;
4394
4395        if (!sk_fullsock(sk))
4396                goto err_clear;
4397#ifdef CONFIG_INET
4398        if (level == SOL_TCP && sk->sk_prot->getsockopt == tcp_getsockopt) {
4399                struct inet_connection_sock *icsk;
4400                struct tcp_sock *tp;
4401
4402                switch (optname) {
4403                case TCP_CONGESTION:
4404                        icsk = inet_csk(sk);
4405
4406                        if (!icsk->icsk_ca_ops || optlen <= 1)
4407                                goto err_clear;
4408                        strncpy(optval, icsk->icsk_ca_ops->name, optlen);
4409                        optval[optlen - 1] = 0;
4410                        break;
4411                case TCP_SAVED_SYN:
4412                        tp = tcp_sk(sk);
4413
4414                        if (optlen <= 0 || !tp->saved_syn ||
4415                            optlen > tp->saved_syn[0])
4416                                goto err_clear;
4417                        memcpy(optval, tp->saved_syn + 1, optlen);
4418                        break;
4419                default:
4420                        goto err_clear;
4421                }
4422        } else if (level == SOL_IP) {
4423                struct inet_sock *inet = inet_sk(sk);
4424
4425                if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4426                        goto err_clear;
4427
4428                /* Only some options are supported */
4429                switch (optname) {
4430                case IP_TOS:
4431                        *((int *)optval) = (int)inet->tos;
4432                        break;
4433                default:
4434                        goto err_clear;
4435                }
4436#if IS_ENABLED(CONFIG_IPV6)
4437        } else if (level == SOL_IPV6) {
4438                struct ipv6_pinfo *np = inet6_sk(sk);
4439
4440                if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4441                        goto err_clear;
4442
4443                /* Only some options are supported */
4444                switch (optname) {
4445                case IPV6_TCLASS:
4446                        *((int *)optval) = (int)np->tclass;
4447                        break;
4448                default:
4449                        goto err_clear;
4450                }
4451#endif
4452        } else {
4453                goto err_clear;
4454        }
4455        return 0;
4456#endif
4457err_clear:
4458        memset(optval, 0, optlen);
4459        return -EINVAL;
4460}
4461
4462static const struct bpf_func_proto bpf_getsockopt_proto = {
4463        .func           = bpf_getsockopt,
4464        .gpl_only       = false,
4465        .ret_type       = RET_INTEGER,
4466        .arg1_type      = ARG_PTR_TO_CTX,
4467        .arg2_type      = ARG_ANYTHING,
4468        .arg3_type      = ARG_ANYTHING,
4469        .arg4_type      = ARG_PTR_TO_UNINIT_MEM,
4470        .arg5_type      = ARG_CONST_SIZE,
4471};
4472
4473BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
4474           int, argval)
4475{
4476        struct sock *sk = bpf_sock->sk;
4477        int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
4478
4479        if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
4480                return -EINVAL;
4481
4482        tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
4483
4484        return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
4485}
4486
4487static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
4488        .func           = bpf_sock_ops_cb_flags_set,
4489        .gpl_only       = false,
4490        .ret_type       = RET_INTEGER,
4491        .arg1_type      = ARG_PTR_TO_CTX,
4492        .arg2_type      = ARG_ANYTHING,
4493};
4494
4495const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly;
4496EXPORT_SYMBOL_GPL(ipv6_bpf_stub);
4497
4498BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
4499           int, addr_len)
4500{
4501#ifdef CONFIG_INET
4502        struct sock *sk = ctx->sk;
4503        int err;
4504
4505        /* Binding to port can be expensive so it's prohibited in the helper.
4506         * Only binding to IP is supported.
4507         */
4508        err = -EINVAL;
4509        if (addr_len < offsetofend(struct sockaddr, sa_family))
4510                return err;
4511        if (addr->sa_family == AF_INET) {
4512                if (addr_len < sizeof(struct sockaddr_in))
4513                        return err;
4514                if (((struct sockaddr_in *)addr)->sin_port != htons(0))
4515                        return err;
4516                return __inet_bind(sk, addr, addr_len, true, false);
4517#if IS_ENABLED(CONFIG_IPV6)
4518        } else if (addr->sa_family == AF_INET6) {
4519                if (addr_len < SIN6_LEN_RFC2133)
4520                        return err;
4521                if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
4522                        return err;
4523                /* ipv6_bpf_stub cannot be NULL, since it's called from
4524                 * bpf_cgroup_inet6_connect hook and ipv6 is already loaded
4525                 */
4526                return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, true, false);
4527#endif /* CONFIG_IPV6 */
4528        }
4529#endif /* CONFIG_INET */
4530
4531        return -EAFNOSUPPORT;
4532}
4533
4534static const struct bpf_func_proto bpf_bind_proto = {
4535        .func           = bpf_bind,
4536        .gpl_only       = false,
4537        .ret_type       = RET_INTEGER,
4538        .arg1_type      = ARG_PTR_TO_CTX,
4539        .arg2_type      = ARG_PTR_TO_MEM,
4540        .arg3_type      = ARG_CONST_SIZE,
4541};
4542
4543#ifdef CONFIG_XFRM
4544BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
4545           struct bpf_xfrm_state *, to, u32, size, u64, flags)
4546{
4547        const struct sec_path *sp = skb_sec_path(skb);
4548        const struct xfrm_state *x;
4549
4550        if (!sp || unlikely(index >= sp->len || flags))
4551                goto err_clear;
4552
4553        x = sp->xvec[index];
4554
4555        if (unlikely(size != sizeof(struct bpf_xfrm_state)))
4556                goto err_clear;
4557
4558        to->reqid = x->props.reqid;
4559        to->spi = x->id.spi;
4560        to->family = x->props.family;
4561        to->ext = 0;
4562
4563        if (to->family == AF_INET6) {
4564                memcpy(to->remote_ipv6, x->props.saddr.a6,
4565                       sizeof(to->remote_ipv6));
4566        } else {
4567                to->remote_ipv4 = x->props.saddr.a4;
4568                memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4569        }
4570
4571        return 0;
4572err_clear:
4573        memset(to, 0, size);
4574        return -EINVAL;
4575}
4576
4577static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
4578        .func           = bpf_skb_get_xfrm_state,
4579        .gpl_only       = false,
4580        .ret_type       = RET_INTEGER,
4581        .arg1_type      = ARG_PTR_TO_CTX,
4582        .arg2_type      = ARG_ANYTHING,
4583        .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
4584        .arg4_type      = ARG_CONST_SIZE,
4585        .arg5_type      = ARG_ANYTHING,
4586};
4587#endif
4588
4589#if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
4590static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params,
4591                                  const struct neighbour *neigh,
4592                                  const struct net_device *dev)
4593{
4594        memcpy(params->dmac, neigh->ha, ETH_ALEN);
4595        memcpy(params->smac, dev->dev_addr, ETH_ALEN);
4596        params->h_vlan_TCI = 0;
4597        params->h_vlan_proto = 0;
4598        params->ifindex = dev->ifindex;
4599
4600        return 0;
4601}
4602#endif
4603
4604#if IS_ENABLED(CONFIG_INET)
4605static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4606                               u32 flags, bool check_mtu)
4607{
4608        struct fib_nh_common *nhc;
4609        struct in_device *in_dev;
4610        struct neighbour *neigh;
4611        struct net_device *dev;
4612        struct fib_result res;
4613        struct flowi4 fl4;
4614        int err;
4615        u32 mtu;
4616
4617        dev = dev_get_by_index_rcu(net, params->ifindex);
4618        if (unlikely(!dev))
4619                return -ENODEV;
4620
4621        /* verify forwarding is enabled on this interface */
4622        in_dev = __in_dev_get_rcu(dev);
4623        if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
4624                return BPF_FIB_LKUP_RET_FWD_DISABLED;
4625
4626        if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4627                fl4.flowi4_iif = 1;
4628                fl4.flowi4_oif = params->ifindex;
4629        } else {
4630                fl4.flowi4_iif = params->ifindex;
4631                fl4.flowi4_oif = 0;
4632        }
4633        fl4.flowi4_tos = params->tos & IPTOS_RT_MASK;
4634        fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
4635        fl4.flowi4_flags = 0;
4636
4637        fl4.flowi4_proto = params->l4_protocol;
4638        fl4.daddr = params->ipv4_dst;
4639        fl4.saddr = params->ipv4_src;
4640        fl4.fl4_sport = params->sport;
4641        fl4.fl4_dport = params->dport;
4642
4643        if (flags & BPF_FIB_LOOKUP_DIRECT) {
4644                u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4645                struct fib_table *tb;
4646
4647                tb = fib_get_table(net, tbid);
4648                if (unlikely(!tb))
4649                        return BPF_FIB_LKUP_RET_NOT_FWDED;
4650
4651                err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
4652        } else {
4653                fl4.flowi4_mark = 0;
4654                fl4.flowi4_secid = 0;
4655                fl4.flowi4_tun_key.tun_id = 0;
4656                fl4.flowi4_uid = sock_net_uid(net, NULL);
4657
4658                err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
4659        }
4660
4661        if (err) {
4662                /* map fib lookup errors to RTN_ type */
4663                if (err == -EINVAL)
4664                        return BPF_FIB_LKUP_RET_BLACKHOLE;
4665                if (err == -EHOSTUNREACH)
4666                        return BPF_FIB_LKUP_RET_UNREACHABLE;
4667                if (err == -EACCES)
4668                        return BPF_FIB_LKUP_RET_PROHIBIT;
4669
4670                return BPF_FIB_LKUP_RET_NOT_FWDED;
4671        }
4672
4673        if (res.type != RTN_UNICAST)
4674                return BPF_FIB_LKUP_RET_NOT_FWDED;
4675
4676        if (fib_info_num_path(res.fi) > 1)
4677                fib_select_path(net, &res, &fl4, NULL);
4678
4679        if (check_mtu) {
4680                mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
4681                if (params->tot_len > mtu)
4682                        return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4683        }
4684
4685        nhc = res.nhc;
4686
4687        /* do not handle lwt encaps right now */
4688        if (nhc->nhc_lwtstate)
4689                return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4690
4691        dev = nhc->nhc_dev;
4692
4693        params->rt_metric = res.fi->fib_priority;
4694
4695        /* xdp and cls_bpf programs are run in RCU-bh so
4696         * rcu_read_lock_bh is not needed here
4697         */
4698        if (likely(nhc->nhc_gw_family != AF_INET6)) {
4699                if (nhc->nhc_gw_family)
4700                        params->ipv4_dst = nhc->nhc_gw.ipv4;
4701
4702                neigh = __ipv4_neigh_lookup_noref(dev,
4703                                                 (__force u32)params->ipv4_dst);
4704        } else {
4705                struct in6_addr *dst = (struct in6_addr *)params->ipv6_dst;
4706
4707                params->family = AF_INET6;
4708                *dst = nhc->nhc_gw.ipv6;
4709                neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
4710        }
4711
4712        if (!neigh)
4713                return BPF_FIB_LKUP_RET_NO_NEIGH;
4714
4715        return bpf_fib_set_fwd_params(params, neigh, dev);
4716}
4717#endif
4718
4719#if IS_ENABLED(CONFIG_IPV6)
4720static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4721                               u32 flags, bool check_mtu)
4722{
4723        struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
4724        struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
4725        struct fib6_result res = {};
4726        struct neighbour *neigh;
4727        struct net_device *dev;
4728        struct inet6_dev *idev;
4729        struct flowi6 fl6;
4730        int strict = 0;
4731        int oif, err;
4732        u32 mtu;
4733
4734        /* link local addresses are never forwarded */
4735        if (rt6_need_strict(dst) || rt6_need_strict(src))
4736                return BPF_FIB_LKUP_RET_NOT_FWDED;
4737
4738        dev = dev_get_by_index_rcu(net, params->ifindex);
4739        if (unlikely(!dev))
4740                return -ENODEV;
4741
4742        idev = __in6_dev_get_safely(dev);
4743        if (unlikely(!idev || !idev->cnf.forwarding))
4744                return BPF_FIB_LKUP_RET_FWD_DISABLED;
4745
4746        if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4747                fl6.flowi6_iif = 1;
4748                oif = fl6.flowi6_oif = params->ifindex;
4749        } else {
4750                oif = fl6.flowi6_iif = params->ifindex;
4751                fl6.flowi6_oif = 0;
4752                strict = RT6_LOOKUP_F_HAS_SADDR;
4753        }
4754        fl6.flowlabel = params->flowinfo;
4755        fl6.flowi6_scope = 0;
4756        fl6.flowi6_flags = 0;
4757        fl6.mp_hash = 0;
4758
4759        fl6.flowi6_proto = params->l4_protocol;
4760        fl6.daddr = *dst;
4761        fl6.saddr = *src;
4762        fl6.fl6_sport = params->sport;
4763        fl6.fl6_dport = params->dport;
4764
4765        if (flags & BPF_FIB_LOOKUP_DIRECT) {
4766                u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4767                struct fib6_table *tb;
4768
4769                tb = ipv6_stub->fib6_get_table(net, tbid);
4770                if (unlikely(!tb))
4771                        return BPF_FIB_LKUP_RET_NOT_FWDED;
4772
4773                err = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, &res,
4774                                                   strict);
4775        } else {
4776                fl6.flowi6_mark = 0;
4777                fl6.flowi6_secid = 0;
4778                fl6.flowi6_tun_key.tun_id = 0;
4779                fl6.flowi6_uid = sock_net_uid(net, NULL);
4780
4781                err = ipv6_stub->fib6_lookup(net, oif, &fl6, &res, strict);
4782        }
4783
4784        if (unlikely(err || IS_ERR_OR_NULL(res.f6i) ||
4785                     res.f6i == net->ipv6.fib6_null_entry))
4786                return BPF_FIB_LKUP_RET_NOT_FWDED;
4787
4788        switch (res.fib6_type) {
4789        /* only unicast is forwarded */
4790        case RTN_UNICAST:
4791                break;
4792        case RTN_BLACKHOLE:
4793                return BPF_FIB_LKUP_RET_BLACKHOLE;
4794        case RTN_UNREACHABLE:
4795                return BPF_FIB_LKUP_RET_UNREACHABLE;
4796        case RTN_PROHIBIT:
4797                return BPF_FIB_LKUP_RET_PROHIBIT;
4798        default:
4799                return BPF_FIB_LKUP_RET_NOT_FWDED;
4800        }
4801
4802        ipv6_stub->fib6_select_path(net, &res, &fl6, fl6.flowi6_oif,
4803                                    fl6.flowi6_oif != 0, NULL, strict);
4804
4805        if (check_mtu) {
4806                mtu = ipv6_stub->ip6_mtu_from_fib6(&res, dst, src);
4807                if (params->tot_len > mtu)
4808                        return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4809        }
4810
4811        if (res.nh->fib_nh_lws)
4812                return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4813
4814        if (res.nh->fib_nh_gw_family)
4815                *dst = res.nh->fib_nh_gw6;
4816
4817        dev = res.nh->fib_nh_dev;
4818        params->rt_metric = res.f6i->fib6_metric;
4819
4820        /* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
4821         * not needed here.
4822         */
4823        neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
4824        if (!neigh)
4825                return BPF_FIB_LKUP_RET_NO_NEIGH;
4826
4827        return bpf_fib_set_fwd_params(params, neigh, dev);
4828}
4829#endif
4830
4831BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
4832           struct bpf_fib_lookup *, params, int, plen, u32, flags)
4833{
4834        if (plen < sizeof(*params))
4835                return -EINVAL;
4836
4837        if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4838                return -EINVAL;
4839
4840        switch (params->family) {
4841#if IS_ENABLED(CONFIG_INET)
4842        case AF_INET:
4843                return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
4844                                           flags, true);
4845#endif
4846#if IS_ENABLED(CONFIG_IPV6)
4847        case AF_INET6:
4848                return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
4849                                           flags, true);
4850#endif
4851        }
4852        return -EAFNOSUPPORT;
4853}
4854
4855static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
4856        .func           = bpf_xdp_fib_lookup,
4857        .gpl_only       = true,
4858        .ret_type       = RET_INTEGER,
4859        .arg1_type      = ARG_PTR_TO_CTX,
4860        .arg2_type      = ARG_PTR_TO_MEM,
4861        .arg3_type      = ARG_CONST_SIZE,
4862        .arg4_type      = ARG_ANYTHING,
4863};
4864
4865BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
4866           struct bpf_fib_lookup *, params, int, plen, u32, flags)
4867{
4868        struct net *net = dev_net(skb->dev);
4869        int rc = -EAFNOSUPPORT;
4870
4871        if (plen < sizeof(*params))
4872                return -EINVAL;
4873
4874        if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4875                return -EINVAL;
4876
4877        switch (params->family) {
4878#if IS_ENABLED(CONFIG_INET)
4879        case AF_INET:
4880                rc = bpf_ipv4_fib_lookup(net, params, flags, false);
4881                break;
4882#endif
4883#if IS_ENABLED(CONFIG_IPV6)
4884        case AF_INET6:
4885                rc = bpf_ipv6_fib_lookup(net, params, flags, false);
4886                break;
4887#endif
4888        }
4889
4890        if (!rc) {
4891                struct net_device *dev;
4892
4893                dev = dev_get_by_index_rcu(net, params->ifindex);
4894                if (!is_skb_forwardable(dev, skb))
4895                        rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
4896        }
4897
4898        return rc;
4899}
4900
4901static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
4902        .func           = bpf_skb_fib_lookup,
4903        .gpl_only       = true,
4904        .ret_type       = RET_INTEGER,
4905        .arg1_type      = ARG_PTR_TO_CTX,
4906        .arg2_type      = ARG_PTR_TO_MEM,
4907        .arg3_type      = ARG_CONST_SIZE,
4908        .arg4_type      = ARG_ANYTHING,
4909};
4910
4911#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4912static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
4913{
4914        int err;
4915        struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;
4916
4917        if (!seg6_validate_srh(srh, len))
4918                return -EINVAL;
4919
4920        switch (type) {
4921        case BPF_LWT_ENCAP_SEG6_INLINE:
4922                if (skb->protocol != htons(ETH_P_IPV6))
4923                        return -EBADMSG;
4924
4925                err = seg6_do_srh_inline(skb, srh);
4926                break;
4927        case BPF_LWT_ENCAP_SEG6:
4928                skb_reset_inner_headers(skb);
4929                skb->encapsulation = 1;
4930                err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
4931                break;
4932        default:
4933                return -EINVAL;
4934        }
4935
4936        bpf_compute_data_pointers(skb);
4937        if (err)
4938                return err;
4939
4940        ipv6_hdr(skb)->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
4941        skb_set_transport_header(skb, sizeof(struct ipv6hdr));
4942
4943        return seg6_lookup_nexthop(skb, NULL, 0);
4944}
4945#endif /* CONFIG_IPV6_SEG6_BPF */
4946
4947#if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
4948static int bpf_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len,
4949                             bool ingress)
4950{
4951        return bpf_lwt_push_ip_encap(skb, hdr, len, ingress);
4952}
4953#endif
4954
4955BPF_CALL_4(bpf_lwt_in_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
4956           u32, len)
4957{
4958        switch (type) {
4959#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4960        case BPF_LWT_ENCAP_SEG6:
4961        case BPF_LWT_ENCAP_SEG6_INLINE:
4962                return bpf_push_seg6_encap(skb, type, hdr, len);
4963#endif
4964#if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
4965        case BPF_LWT_ENCAP_IP:
4966                return bpf_push_ip_encap(skb, hdr, len, true /* ingress */);
4967#endif
4968        default:
4969                return -EINVAL;
4970        }
4971}
4972
4973BPF_CALL_4(bpf_lwt_xmit_push_encap, struct sk_buff *, skb, u32, type,
4974           void *, hdr, u32, len)
4975{
4976        switch (type) {
4977#if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
4978        case BPF_LWT_ENCAP_IP:
4979                return bpf_push_ip_encap(skb, hdr, len, false /* egress */);
4980#endif
4981        default:
4982                return -EINVAL;
4983        }
4984}
4985
4986static const struct bpf_func_proto bpf_lwt_in_push_encap_proto = {
4987        .func           = bpf_lwt_in_push_encap,
4988        .gpl_only       = false,
4989        .ret_type       = RET_INTEGER,
4990        .arg1_type      = ARG_PTR_TO_CTX,
4991        .arg2_type      = ARG_ANYTHING,
4992        .arg3_type      = ARG_PTR_TO_MEM,
4993        .arg4_type      = ARG_CONST_SIZE
4994};
4995
4996static const struct bpf_func_proto bpf_lwt_xmit_push_encap_proto = {
4997        .func           = bpf_lwt_xmit_push_encap,
4998        .gpl_only       = false,
4999        .ret_type       = RET_INTEGER,
5000        .arg1_type      = ARG_PTR_TO_CTX,
5001        .arg2_type      = ARG_ANYTHING,
5002        .arg3_type      = ARG_PTR_TO_MEM,
5003        .arg4_type      = ARG_CONST_SIZE
5004};
5005
5006#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
5007BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
5008           const void *, from, u32, len)
5009{
5010        struct seg6_bpf_srh_state *srh_state =
5011                this_cpu_ptr(&seg6_bpf_srh_states);
5012        struct ipv6_sr_hdr *srh = srh_state->srh;
5013        void *srh_tlvs, *srh_end, *ptr;
5014        int srhoff = 0;
5015
5016        if (srh == NULL)
5017                return -EINVAL;
5018
5019        srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
5020        srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
5021
5022        ptr = skb->data + offset;
5023        if (ptr >= srh_tlvs && ptr + len <= srh_end)
5024                srh_state->valid = false;
5025        else if (ptr < (void *)&srh->flags ||
5026                 ptr + len > (void *)&srh->segments)
5027                return -EFAULT;
5028
5029        if (unlikely(bpf_try_make_writable(skb, offset + len)))
5030                return -EFAULT;
5031        if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
5032                return -EINVAL;
5033        srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5034
5035        memcpy(skb->data + offset, from, len);
5036        return 0;
5037}
5038
5039static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
5040        .func           = bpf_lwt_seg6_store_bytes,
5041        .gpl_only       = false,
5042        .ret_type       = RET_INTEGER,
5043        .arg1_type      = ARG_PTR_TO_CTX,
5044        .arg2_type      = ARG_ANYTHING,
5045        .arg3_type      = ARG_PTR_TO_MEM,
5046        .arg4_type      = ARG_CONST_SIZE
5047};
5048
5049static void bpf_update_srh_state(struct sk_buff *skb)
5050{
5051        struct seg6_bpf_srh_state *srh_state =
5052                this_cpu_ptr(&seg6_bpf_srh_states);
5053        int srhoff = 0;
5054
5055        if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) {
5056                srh_state->srh = NULL;
5057        } else {
5058                srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5059                srh_state->hdrlen = srh_state->srh->hdrlen << 3;
5060                srh_state->valid = true;
5061        }
5062}
5063
5064BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
5065           u32, action, void *, param, u32, param_len)
5066{
5067        struct seg6_bpf_srh_state *srh_state =
5068                this_cpu_ptr(&seg6_bpf_srh_states);
5069        int hdroff = 0;
5070        int err;
5071
5072        switch (action) {
5073        case SEG6_LOCAL_ACTION_END_X:
5074                if (!seg6_bpf_has_valid_srh(skb))
5075                        return -EBADMSG;
5076                if (param_len != sizeof(struct in6_addr))
5077                        return -EINVAL;
5078                return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
5079        case SEG6_LOCAL_ACTION_END_T:
5080                if (!seg6_bpf_has_valid_srh(skb))
5081                        return -EBADMSG;
5082                if (param_len != sizeof(int))
5083                        return -EINVAL;
5084                return seg6_lookup_nexthop(skb, NULL, *(int *)param);
5085        case SEG6_LOCAL_ACTION_END_DT6:
5086                if (!seg6_bpf_has_valid_srh(skb))
5087                        return -EBADMSG;
5088                if (param_len != sizeof(int))
5089                        return -EINVAL;
5090
5091                if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
5092                        return -EBADMSG;
5093                if (!pskb_pull(skb, hdroff))
5094                        return -EBADMSG;
5095
5096                skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
5097                skb_reset_network_header(skb);
5098                skb_reset_transport_header(skb);
5099                skb->encapsulation = 0;
5100
5101                bpf_compute_data_pointers(skb);
5102                bpf_update_srh_state(skb);
5103                return seg6_lookup_nexthop(skb, NULL, *(int *)param);
5104        case SEG6_LOCAL_ACTION_END_B6:
5105                if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
5106                        return -EBADMSG;
5107                err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
5108                                          param, param_len);
5109                if (!err)
5110                        bpf_update_srh_state(skb);
5111
5112                return err;
5113        case SEG6_LOCAL_ACTION_END_B6_ENCAP:
5114                if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
5115                        return -EBADMSG;
5116                err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
5117                                          param, param_len);
5118                if (!err)
5119                        bpf_update_srh_state(skb);
5120
5121                return err;
5122        default:
5123                return -EINVAL;
5124        }
5125}
5126
5127static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
5128        .func           = bpf_lwt_seg6_action,
5129        .gpl_only       = false,
5130        .ret_type       = RET_INTEGER,
5131        .arg1_type      = ARG_PTR_TO_CTX,
5132        .arg2_type      = ARG_ANYTHING,
5133        .arg3_type      = ARG_PTR_TO_MEM,
5134        .arg4_type      = ARG_CONST_SIZE
5135};
5136
5137BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
5138           s32, len)
5139{
5140        struct seg6_bpf_srh_state *srh_state =
5141                this_cpu_ptr(&seg6_bpf_srh_states);
5142        struct ipv6_sr_hdr *srh = srh_state->srh;
5143        void *srh_end, *srh_tlvs, *ptr;
5144        struct ipv6hdr *hdr;
5145        int srhoff = 0;
5146        int ret;
5147
5148        if (unlikely(srh == NULL))
5149                return -EINVAL;
5150
5151        srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
5152                        ((srh->first_segment + 1) << 4));
5153        srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
5154                        srh_state->hdrlen);
5155        ptr = skb->data + offset;
5156
5157        if (unlikely(ptr < srh_tlvs || ptr > srh_end))
5158                return -EFAULT;
5159        if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
5160                return -EFAULT;
5161
5162        if (len > 0) {
5163                ret = skb_cow_head(skb, len);
5164                if (unlikely(ret < 0))
5165                        return ret;
5166
5167                ret = bpf_skb_net_hdr_push(skb, offset, len);
5168        } else {
5169                ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
5170        }
5171
5172        bpf_compute_data_pointers(skb);
5173        if (unlikely(ret < 0))
5174                return ret;
5175
5176        hdr = (struct ipv6hdr *)skb->data;
5177        hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
5178
5179        if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
5180                return -EINVAL;
5181        srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5182        srh_state->hdrlen += len;
5183        srh_state->valid = false;
5184        return 0;
5185}
5186
5187static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
5188        .func           = bpf_lwt_seg6_adjust_srh,
5189        .gpl_only       = false,
5190        .ret_type       = RET_INTEGER,
5191        .arg1_type      = ARG_PTR_TO_CTX,
5192        .arg2_type      = ARG_ANYTHING,
5193        .arg3_type      = ARG_ANYTHING,
5194};
5195#endif /* CONFIG_IPV6_SEG6_BPF */
5196
5197#ifdef CONFIG_INET
5198static struct sock *sk_lookup(struct net *net, struct bpf_sock_tuple *tuple,
5199                              int dif, int sdif, u8 family, u8 proto)
5200{
5201        bool refcounted = false;
5202        struct sock *sk = NULL;
5203
5204        if (family == AF_INET) {
5205                __be32 src4 = tuple->ipv4.saddr;
5206                __be32 dst4 = tuple->ipv4.daddr;
5207
5208                if (proto == IPPROTO_TCP)
5209                        sk = __inet_lookup(net, &tcp_hashinfo, NULL, 0,
5210                                           src4, tuple->ipv4.sport,
5211                                           dst4, tuple->ipv4.dport,
5212                                           dif, sdif, &refcounted);
5213                else
5214                        sk = __udp4_lib_lookup(net, src4, tuple->ipv4.sport,
5215                                               dst4, tuple->ipv4.dport,
5216                                               dif, sdif, &udp_table, NULL);
5217#if IS_ENABLED(CONFIG_IPV6)
5218        } else {
5219                struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr;
5220                struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr;
5221
5222                if (proto == IPPROTO_TCP)
5223                        sk = __inet6_lookup(net, &tcp_hashinfo, NULL, 0,
5224                                            src6, tuple->ipv6.sport,
5225                                            dst6, ntohs(tuple->ipv6.dport),
5226                                            dif, sdif, &refcounted);
5227                else if (likely(ipv6_bpf_stub))
5228                        sk = ipv6_bpf_stub->udp6_lib_lookup(net,
5229                                                            src6, tuple->ipv6.sport,
5230                                                            dst6, tuple->ipv6.dport,
5231                                                            dif, sdif,
5232                                                            &udp_table, NULL);
5233#endif
5234        }
5235
5236        if (unlikely(sk && !refcounted && !sock_flag(sk, SOCK_RCU_FREE))) {
5237                WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
5238                sk = NULL;
5239        }
5240        return sk;
5241}
5242
5243/* bpf_skc_lookup performs the core lookup for different types of sockets,
5244 * taking a reference on the socket if it doesn't have the flag SOCK_RCU_FREE.
5245 * Returns the socket as an 'unsigned long' to simplify the casting in the
5246 * callers to satisfy BPF_CALL declarations.
5247 */
5248static struct sock *
5249__bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5250                 struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
5251                 u64 flags)
5252{
5253        struct sock *sk = NULL;
5254        u8 family = AF_UNSPEC;
5255        struct net *net;
5256        int sdif;
5257
5258        if (len == sizeof(tuple->ipv4))
5259                family = AF_INET;
5260        else if (len == sizeof(tuple->ipv6))
5261                family = AF_INET6;
5262        else
5263                return NULL;
5264
5265        if (unlikely(family == AF_UNSPEC || flags ||
5266                     !((s32)netns_id < 0 || netns_id <= S32_MAX)))
5267                goto out;
5268
5269        if (family == AF_INET)
5270                sdif = inet_sdif(skb);
5271        else
5272                sdif = inet6_sdif(skb);
5273
5274        if ((s32)netns_id < 0) {
5275                net = caller_net;
5276                sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
5277        } else {
5278                net = get_net_ns_by_id(caller_net, netns_id);
5279                if (unlikely(!net))
5280                        goto out;
5281                sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
5282                put_net(net);
5283        }
5284
5285out:
5286        return sk;
5287}
5288
5289static struct sock *
5290__bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5291                struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
5292                u64 flags)
5293{
5294        struct sock *sk = __bpf_skc_lookup(skb, tuple, len, caller_net,
5295                                           ifindex, proto, netns_id, flags);
5296
5297        if (sk) {
5298                sk = sk_to_full_sk(sk);
5299                if (!sk_fullsock(sk)) {
5300                        if (!sock_flag(sk, SOCK_RCU_FREE))
5301                                sock_gen_put(sk);
5302                        return NULL;
5303                }
5304        }
5305
5306        return sk;
5307}
5308
5309static struct sock *
5310bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5311               u8 proto, u64 netns_id, u64 flags)
5312{
5313        struct net *caller_net;
5314        int ifindex;
5315
5316        if (skb->dev) {
5317                caller_net = dev_net(skb->dev);
5318                ifindex = skb->dev->ifindex;
5319        } else {
5320                caller_net = sock_net(skb->sk);
5321                ifindex = 0;
5322        }
5323
5324        return __bpf_skc_lookup(skb, tuple, len, caller_net, ifindex, proto,
5325                                netns_id, flags);
5326}
5327
5328static struct sock *
5329bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5330              u8 proto, u64 netns_id, u64 flags)
5331{
5332        struct sock *sk = bpf_skc_lookup(skb, tuple, len, proto, netns_id,
5333                                         flags);
5334
5335        if (sk) {
5336                sk = sk_to_full_sk(sk);
5337                if (!sk_fullsock(sk)) {
5338                        if (!sock_flag(sk, SOCK_RCU_FREE))
5339                                sock_gen_put(sk);
5340                        return NULL;
5341                }
5342        }
5343
5344        return sk;
5345}
5346
5347BPF_CALL_5(bpf_skc_lookup_tcp, struct sk_buff *, skb,
5348           struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5349{
5350        return (unsigned long)bpf_skc_lookup(skb, tuple, len, IPPROTO_TCP,
5351                                             netns_id, flags);
5352}
5353
5354static const struct bpf_func_proto bpf_skc_lookup_tcp_proto = {
5355        .func           = bpf_skc_lookup_tcp,
5356        .gpl_only       = false,
5357        .pkt_access     = true,
5358        .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5359        .arg1_type      = ARG_PTR_TO_CTX,
5360        .arg2_type      = ARG_PTR_TO_MEM,
5361        .arg3_type      = ARG_CONST_SIZE,
5362        .arg4_type      = ARG_ANYTHING,
5363        .arg5_type      = ARG_ANYTHING,
5364};
5365
5366BPF_CALL_5(bpf_sk_lookup_tcp, struct sk_buff *, skb,
5367           struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5368{
5369        return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_TCP,
5370                                            netns_id, flags);
5371}
5372
5373static const struct bpf_func_proto bpf_sk_lookup_tcp_proto = {
5374        .func           = bpf_sk_lookup_tcp,
5375        .gpl_only       = false,
5376        .pkt_access     = true,
5377        .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5378        .arg1_type      = ARG_PTR_TO_CTX,
5379        .arg2_type      = ARG_PTR_TO_MEM,
5380        .arg3_type      = ARG_CONST_SIZE,
5381        .arg4_type      = ARG_ANYTHING,
5382        .arg5_type      = ARG_ANYTHING,
5383};
5384
5385BPF_CALL_5(bpf_sk_lookup_udp, struct sk_buff *, skb,
5386           struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5387{
5388        return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_UDP,
5389                                            netns_id, flags);
5390}
5391
5392static const struct bpf_func_proto bpf_sk_lookup_udp_proto = {
5393        .func           = bpf_sk_lookup_udp,
5394        .gpl_only       = false,
5395        .pkt_access     = true,
5396        .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5397        .arg1_type      = ARG_PTR_TO_CTX,
5398        .arg2_type      = ARG_PTR_TO_MEM,
5399        .arg3_type      = ARG_CONST_SIZE,
5400        .arg4_type      = ARG_ANYTHING,
5401        .arg5_type      = ARG_ANYTHING,
5402};
5403
5404BPF_CALL_1(bpf_sk_release, struct sock *, sk)
5405{
5406        if (!sock_flag(sk, SOCK_RCU_FREE))
5407                sock_gen_put(sk);
5408        return 0;
5409}
5410
5411static const struct bpf_func_proto bpf_sk_release_proto = {
5412        .func           = bpf_sk_release,
5413        .gpl_only       = false,
5414        .ret_type       = RET_INTEGER,
5415        .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5416};
5417
5418BPF_CALL_5(bpf_xdp_sk_lookup_udp, struct xdp_buff *, ctx,
5419           struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5420{
5421        struct net *caller_net = dev_net(ctx->rxq->dev);
5422        int ifindex = ctx->rxq->dev->ifindex;
5423
5424        return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
5425                                              ifindex, IPPROTO_UDP, netns_id,
5426                                              flags);
5427}
5428
5429static const struct bpf_func_proto bpf_xdp_sk_lookup_udp_proto = {
5430        .func           = bpf_xdp_sk_lookup_udp,
5431        .gpl_only       = false,
5432        .pkt_access     = true,
5433        .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5434        .arg1_type      = ARG_PTR_TO_CTX,
5435        .arg2_type      = ARG_PTR_TO_MEM,
5436        .arg3_type      = ARG_CONST_SIZE,
5437        .arg4_type      = ARG_ANYTHING,
5438        .arg5_type      = ARG_ANYTHING,
5439};
5440
5441BPF_CALL_5(bpf_xdp_skc_lookup_tcp, struct xdp_buff *, ctx,
5442           struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5443{
5444        struct net *caller_net = dev_net(ctx->rxq->dev);
5445        int ifindex = ctx->rxq->dev->ifindex;
5446
5447        return (unsigned long)__bpf_skc_lookup(NULL, tuple, len, caller_net,
5448                                               ifindex, IPPROTO_TCP, netns_id,
5449                                               flags);
5450}
5451
5452static const struct bpf_func_proto bpf_xdp_skc_lookup_tcp_proto = {
5453        .func           = bpf_xdp_skc_lookup_tcp,
5454        .gpl_only       = false,
5455        .pkt_access     = true,
5456        .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5457        .arg1_type      = ARG_PTR_TO_CTX,
5458        .arg2_type      = ARG_PTR_TO_MEM,
5459        .arg3_type      = ARG_CONST_SIZE,
5460        .arg4_type      = ARG_ANYTHING,
5461        .arg5_type      = ARG_ANYTHING,
5462};
5463
5464BPF_CALL_5(bpf_xdp_sk_lookup_tcp, struct xdp_buff *, ctx,
5465           struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5466{
5467        struct net *caller_net = dev_net(ctx->rxq->dev);
5468        int ifindex = ctx->rxq->dev->ifindex;
5469
5470        return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
5471                                              ifindex, IPPROTO_TCP, netns_id,
5472                                              flags);
5473}
5474
5475static const struct bpf_func_proto bpf_xdp_sk_lookup_tcp_proto = {
5476        .func           = bpf_xdp_sk_lookup_tcp,
5477        .gpl_only       = false,
5478        .pkt_access     = true,
5479        .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5480        .arg1_type      = ARG_PTR_TO_CTX,
5481        .arg2_type      = ARG_PTR_TO_MEM,
5482        .arg3_type      = ARG_CONST_SIZE,
5483        .arg4_type      = ARG_ANYTHING,
5484        .arg5_type      = ARG_ANYTHING,
5485};
5486
5487BPF_CALL_5(bpf_sock_addr_skc_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
5488           struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5489{
5490        return (unsigned long)__bpf_skc_lookup(NULL, tuple, len,
5491                                               sock_net(ctx->sk), 0,
5492                                               IPPROTO_TCP, netns_id, flags);
5493}
5494
5495static const struct bpf_func_proto bpf_sock_addr_skc_lookup_tcp_proto = {
5496        .func           = bpf_sock_addr_skc_lookup_tcp,
5497        .gpl_only       = false,
5498        .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5499        .arg1_type      = ARG_PTR_TO_CTX,
5500        .arg2_type      = ARG_PTR_TO_MEM,
5501        .arg3_type      = ARG_CONST_SIZE,
5502        .arg4_type      = ARG_ANYTHING,
5503        .arg5_type      = ARG_ANYTHING,
5504};
5505
5506BPF_CALL_5(bpf_sock_addr_sk_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
5507           struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5508{
5509        return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
5510                                              sock_net(ctx->sk), 0, IPPROTO_TCP,
5511                                              netns_id, flags);
5512}
5513
5514static const struct bpf_func_proto bpf_sock_addr_sk_lookup_tcp_proto = {
5515        .func           = bpf_sock_addr_sk_lookup_tcp,
5516        .gpl_only       = false,
5517        .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5518        .arg1_type      = ARG_PTR_TO_CTX,
5519        .arg2_type      = ARG_PTR_TO_MEM,
5520        .arg3_type      = ARG_CONST_SIZE,
5521        .arg4_type      = ARG_ANYTHING,
5522        .arg5_type      = ARG_ANYTHING,
5523};
5524
5525BPF_CALL_5(bpf_sock_addr_sk_lookup_udp, struct bpf_sock_addr_kern *, ctx,
5526           struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5527{
5528        return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
5529                                              sock_net(ctx->sk), 0, IPPROTO_UDP,
5530                                              netns_id, flags);
5531}
5532
5533static const struct bpf_func_proto bpf_sock_addr_sk_lookup_udp_proto = {
5534        .func           = bpf_sock_addr_sk_lookup_udp,
5535        .gpl_only       = false,
5536        .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5537        .arg1_type      = ARG_PTR_TO_CTX,
5538        .arg2_type      = ARG_PTR_TO_MEM,
5539        .arg3_type      = ARG_CONST_SIZE,
5540        .arg4_type      = ARG_ANYTHING,
5541        .arg5_type      = ARG_ANYTHING,
5542};
5543
5544bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
5545                                  struct bpf_insn_access_aux *info)
5546{
5547        if (off < 0 || off >= offsetofend(struct bpf_tcp_sock,
5548                                          icsk_retransmits))
5549                return false;
5550
5551        if (off % size != 0)
5552                return false;
5553
5554        switch (off) {
5555        case offsetof(struct bpf_tcp_soc