linux/net/core/dev.c
<<
>>
Prefs
   1/*
   2 *      NET3    Protocol independent device support routines.
   3 *
   4 *              This program is free software; you can redistribute it and/or
   5 *              modify it under the terms of the GNU General Public License
   6 *              as published by the Free Software Foundation; either version
   7 *              2 of the License, or (at your option) any later version.
   8 *
   9 *      Derived from the non IP parts of dev.c 1.0.19
  10 *              Authors:        Ross Biro
  11 *                              Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  12 *                              Mark Evans, <evansmp@uhura.aston.ac.uk>
  13 *
  14 *      Additional Authors:
  15 *              Florian la Roche <rzsfl@rz.uni-sb.de>
  16 *              Alan Cox <gw4pts@gw4pts.ampr.org>
  17 *              David Hinds <dahinds@users.sourceforge.net>
  18 *              Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
  19 *              Adam Sulmicki <adam@cfar.umd.edu>
  20 *              Pekka Riikonen <priikone@poesidon.pspt.fi>
  21 *
  22 *      Changes:
  23 *              D.J. Barrow     :       Fixed bug where dev->refcnt gets set
  24 *                                      to 2 if register_netdev gets called
  25 *                                      before net_dev_init & also removed a
  26 *                                      few lines of code in the process.
  27 *              Alan Cox        :       device private ioctl copies fields back.
  28 *              Alan Cox        :       Transmit queue code does relevant
  29 *                                      stunts to keep the queue safe.
  30 *              Alan Cox        :       Fixed double lock.
  31 *              Alan Cox        :       Fixed promisc NULL pointer trap
  32 *              ????????        :       Support the full private ioctl range
  33 *              Alan Cox        :       Moved ioctl permission check into
  34 *                                      drivers
  35 *              Tim Kordas      :       SIOCADDMULTI/SIOCDELMULTI
  36 *              Alan Cox        :       100 backlog just doesn't cut it when
  37 *                                      you start doing multicast video 8)
  38 *              Alan Cox        :       Rewrote net_bh and list manager.
  39 *              Alan Cox        :       Fix ETH_P_ALL echoback lengths.
  40 *              Alan Cox        :       Took out transmit every packet pass
  41 *                                      Saved a few bytes in the ioctl handler
  42 *              Alan Cox        :       Network driver sets packet type before
  43 *                                      calling netif_rx. Saves a function
  44 *                                      call a packet.
  45 *              Alan Cox        :       Hashed net_bh()
  46 *              Richard Kooijman:       Timestamp fixes.
  47 *              Alan Cox        :       Wrong field in SIOCGIFDSTADDR
  48 *              Alan Cox        :       Device lock protection.
  49 *              Alan Cox        :       Fixed nasty side effect of device close
  50 *                                      changes.
  51 *              Rudi Cilibrasi  :       Pass the right thing to
  52 *                                      set_mac_address()
  53 *              Dave Miller     :       32bit quantity for the device lock to
  54 *                                      make it work out on a Sparc.
  55 *              Bjorn Ekwall    :       Added KERNELD hack.
  56 *              Alan Cox        :       Cleaned up the backlog initialise.
  57 *              Craig Metz      :       SIOCGIFCONF fix if space for under
  58 *                                      1 device.
  59 *          Thomas Bogendoerfer :       Return ENODEV for dev_open, if there
  60 *                                      is no device open function.
  61 *              Andi Kleen      :       Fix error reporting for SIOCGIFCONF
  62 *          Michael Chastain    :       Fix signed/unsigned for SIOCGIFCONF
  63 *              Cyrus Durgin    :       Cleaned for KMOD
  64 *              Adam Sulmicki   :       Bug Fix : Network Device Unload
  65 *                                      A network device unload needs to purge
  66 *                                      the backlog queue.
  67 *      Paul Rusty Russell      :       SIOCSIFNAME
  68 *              Pekka Riikonen  :       Netdev boot-time settings code
  69 *              Andrew Morton   :       Make unregister_netdevice wait
  70 *                                      indefinitely on dev->refcnt
  71 *              J Hadi Salim    :       - Backlog queue sampling
  72 *                                      - netif_rx() feedback
  73 */
  74
  75#include <linux/uaccess.h>
  76#include <linux/bitops.h>
  77#include <linux/capability.h>
  78#include <linux/cpu.h>
  79#include <linux/types.h>
  80#include <linux/kernel.h>
  81#include <linux/hash.h>
  82#include <linux/slab.h>
  83#include <linux/sched.h>
  84#include <linux/sched/mm.h>
  85#include <linux/mutex.h>
  86#include <linux/string.h>
  87#include <linux/mm.h>
  88#include <linux/socket.h>
  89#include <linux/sockios.h>
  90#include <linux/errno.h>
  91#include <linux/interrupt.h>
  92#include <linux/if_ether.h>
  93#include <linux/netdevice.h>
  94#include <linux/etherdevice.h>
  95#include <linux/ethtool.h>
  96#include <linux/skbuff.h>
  97#include <linux/bpf.h>
  98#include <linux/bpf_trace.h>
  99#include <net/net_namespace.h>
 100#include <net/sock.h>
 101#include <net/busy_poll.h>
 102#include <linux/rtnetlink.h>
 103#include <linux/stat.h>
 104#include <net/dst.h>
 105#include <net/dst_metadata.h>
 106#include <net/pkt_sched.h>
 107#include <net/pkt_cls.h>
 108#include <net/checksum.h>
 109#include <net/xfrm.h>
 110#include <linux/highmem.h>
 111#include <linux/init.h>
 112#include <linux/module.h>
 113#include <linux/netpoll.h>
 114#include <linux/rcupdate.h>
 115#include <linux/delay.h>
 116#include <net/iw_handler.h>
 117#include <asm/current.h>
 118#include <linux/audit.h>
 119#include <linux/dmaengine.h>
 120#include <linux/err.h>
 121#include <linux/ctype.h>
 122#include <linux/if_arp.h>
 123#include <linux/if_vlan.h>
 124#include <linux/ip.h>
 125#include <net/ip.h>
 126#include <net/mpls.h>
 127#include <linux/ipv6.h>
 128#include <linux/in.h>
 129#include <linux/jhash.h>
 130#include <linux/random.h>
 131#include <trace/events/napi.h>
 132#include <trace/events/net.h>
 133#include <trace/events/skb.h>
 134#include <linux/pci.h>
 135#include <linux/inetdevice.h>
 136#include <linux/cpu_rmap.h>
 137#include <linux/static_key.h>
 138#include <linux/hashtable.h>
 139#include <linux/vmalloc.h>
 140#include <linux/if_macvlan.h>
 141#include <linux/errqueue.h>
 142#include <linux/hrtimer.h>
 143#include <linux/netfilter_ingress.h>
 144#include <linux/crash_dump.h>
 145#include <linux/sctp.h>
 146#include <net/udp_tunnel.h>
 147#include <linux/net_namespace.h>
 148#include <linux/indirect_call_wrapper.h>
 149#include <net/devlink.h>
 150
 151#include "net-sysfs.h"
 152
 153#include <linux/rh_features.h>
 154
 155/* Instead of increasing this, you should create a hash table. */
 156#define MAX_GRO_SKBS 8
 157
 158/* This should be increased if a protocol with a bigger head is added. */
 159#define GRO_MAX_HEAD (MAX_HEADER + 128)
 160
 161static DEFINE_SPINLOCK(ptype_lock);
 162static DEFINE_SPINLOCK(offload_lock);
 163struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
 164struct list_head ptype_all __read_mostly;       /* Taps */
 165static struct list_head offload_base __read_mostly;
 166
 167static int netif_rx_internal(struct sk_buff *skb);
 168static int call_netdevice_notifiers_info(unsigned long val,
 169                                         struct netdev_notifier_info *info);
 170static int call_netdevice_notifiers_extack(unsigned long val,
 171                                           struct net_device *dev,
 172                                           struct netlink_ext_ack *extack);
 173static struct napi_struct *napi_by_id(unsigned int napi_id);
 174
 175/*
 176 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
 177 * semaphore.
 178 *
 179 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
 180 *
 181 * Writers must hold the rtnl semaphore while they loop through the
 182 * dev_base_head list, and hold dev_base_lock for writing when they do the
 183 * actual updates.  This allows pure readers to access the list even
 184 * while a writer is preparing to update it.
 185 *
 186 * To put it another way, dev_base_lock is held for writing only to
 187 * protect against pure readers; the rtnl semaphore provides the
 188 * protection against other writers.
 189 *
 190 * See, for example usages, register_netdevice() and
 191 * unregister_netdevice(), which must be called with the rtnl
 192 * semaphore held.
 193 */
 194DEFINE_RWLOCK(dev_base_lock);
 195EXPORT_SYMBOL(dev_base_lock);
 196
 197static DEFINE_MUTEX(ifalias_mutex);
 198
 199/* protects napi_hash addition/deletion and napi_gen_id */
 200static DEFINE_SPINLOCK(napi_hash_lock);
 201
 202static unsigned int napi_gen_id = NR_CPUS;
 203static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
 204
 205static seqcount_t devnet_rename_seq;
 206
 207static inline void dev_base_seq_inc(struct net *net)
 208{
 209        while (++net->dev_base_seq == 0)
 210                ;
 211}
 212
 213static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
 214{
 215        unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
 216
 217        return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
 218}
 219
 220static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
 221{
 222        return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
 223}
 224
 225static inline void rps_lock(struct softnet_data *sd)
 226{
 227#ifdef CONFIG_RPS
 228        spin_lock(&sd->input_pkt_queue.lock);
 229#endif
 230}
 231
 232static inline void rps_unlock(struct softnet_data *sd)
 233{
 234#ifdef CONFIG_RPS
 235        spin_unlock(&sd->input_pkt_queue.lock);
 236#endif
 237}
 238
 239/* Device list insertion */
 240static void list_netdevice(struct net_device *dev)
 241{
 242        struct net *net = dev_net(dev);
 243
 244        ASSERT_RTNL();
 245
 246        write_lock_bh(&dev_base_lock);
 247        list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
 248        hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
 249        hlist_add_head_rcu(&dev->index_hlist,
 250                           dev_index_hash(net, dev->ifindex));
 251        write_unlock_bh(&dev_base_lock);
 252
 253        dev_base_seq_inc(net);
 254}
 255
 256/* Device list removal
 257 * caller must respect a RCU grace period before freeing/reusing dev
 258 */
 259static void unlist_netdevice(struct net_device *dev)
 260{
 261        ASSERT_RTNL();
 262
 263        /* Unlink dev from the device chain */
 264        write_lock_bh(&dev_base_lock);
 265        list_del_rcu(&dev->dev_list);
 266        hlist_del_rcu(&dev->name_hlist);
 267        hlist_del_rcu(&dev->index_hlist);
 268        write_unlock_bh(&dev_base_lock);
 269
 270        dev_base_seq_inc(dev_net(dev));
 271}
 272
 273/*
 274 *      Our notifier list
 275 */
 276
 277static RAW_NOTIFIER_HEAD(netdev_chain);
 278
 279/*
 280 *      Device drivers call our routines to queue packets here. We empty the
 281 *      queue in the local softnet handler.
 282 */
 283
 284DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
 285EXPORT_PER_CPU_SYMBOL(softnet_data);
 286
 287#ifdef CONFIG_LOCKDEP
 288/*
 289 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
 290 * according to dev->type
 291 */
 292static const unsigned short netdev_lock_type[] = {
 293         ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
 294         ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
 295         ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
 296         ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
 297         ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
 298         ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
 299         ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
 300         ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
 301         ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
 302         ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
 303         ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
 304         ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
 305         ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
 306         ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
 307         ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
 308
 309static const char *const netdev_lock_name[] = {
 310        "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
 311        "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
 312        "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
 313        "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
 314        "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
 315        "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
 316        "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
 317        "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
 318        "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
 319        "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
 320        "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
 321        "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
 322        "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
 323        "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
 324        "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
 325
 326static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
 327static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
 328
 329static inline unsigned short netdev_lock_pos(unsigned short dev_type)
 330{
 331        int i;
 332
 333        for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
 334                if (netdev_lock_type[i] == dev_type)
 335                        return i;
 336        /* the last key is used by default */
 337        return ARRAY_SIZE(netdev_lock_type) - 1;
 338}
 339
 340static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
 341                                                 unsigned short dev_type)
 342{
 343        int i;
 344
 345        i = netdev_lock_pos(dev_type);
 346        lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
 347                                   netdev_lock_name[i]);
 348}
 349
 350static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
 351{
 352        int i;
 353
 354        i = netdev_lock_pos(dev->type);
 355        lockdep_set_class_and_name(&dev->addr_list_lock,
 356                                   &netdev_addr_lock_key[i],
 357                                   netdev_lock_name[i]);
 358}
 359#else
 360static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
 361                                                 unsigned short dev_type)
 362{
 363}
 364static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
 365{
 366}
 367#endif
 368
 369/*******************************************************************************
 370 *
 371 *              Protocol management and registration routines
 372 *
 373 *******************************************************************************/
 374
 375
 376/*
 377 *      Add a protocol ID to the list. Now that the input handler is
 378 *      smarter we can dispense with all the messy stuff that used to be
 379 *      here.
 380 *
 381 *      BEWARE!!! Protocol handlers, mangling input packets,
 382 *      MUST BE last in hash buckets and checking protocol handlers
 383 *      MUST start from promiscuous ptype_all chain in net_bh.
 384 *      It is true now, do not change it.
 385 *      Explanation follows: if protocol handler, mangling packet, will
 386 *      be the first on list, it is not able to sense, that packet
 387 *      is cloned and should be copied-on-write, so that it will
 388 *      change it and subsequent readers will get broken packet.
 389 *                                                      --ANK (980803)
 390 */
 391
 392static inline struct list_head *ptype_head(const struct packet_type *pt)
 393{
 394        if (pt->type == htons(ETH_P_ALL))
 395                return pt->dev ? &pt->dev->ptype_all : &ptype_all;
 396        else
 397                return pt->dev ? &pt->dev->ptype_specific :
 398                                 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
 399}
 400
 401/**
 402 *      dev_add_pack - add packet handler
 403 *      @pt: packet type declaration
 404 *
 405 *      Add a protocol handler to the networking stack. The passed &packet_type
 406 *      is linked into kernel lists and may not be freed until it has been
 407 *      removed from the kernel lists.
 408 *
 409 *      This call does not sleep therefore it can not
 410 *      guarantee all CPU's that are in middle of receiving packets
 411 *      will see the new packet type (until the next received packet).
 412 */
 413
 414void dev_add_pack(struct packet_type *pt)
 415{
 416        struct list_head *head = ptype_head(pt);
 417
 418        spin_lock(&ptype_lock);
 419        list_add_rcu(&pt->list, head);
 420        spin_unlock(&ptype_lock);
 421}
 422EXPORT_SYMBOL(dev_add_pack);
 423
 424/**
 425 *      __dev_remove_pack        - remove packet handler
 426 *      @pt: packet type declaration
 427 *
 428 *      Remove a protocol handler that was previously added to the kernel
 429 *      protocol handlers by dev_add_pack(). The passed &packet_type is removed
 430 *      from the kernel lists and can be freed or reused once this function
 431 *      returns.
 432 *
 433 *      The packet type might still be in use by receivers
 434 *      and must not be freed until after all the CPU's have gone
 435 *      through a quiescent state.
 436 */
 437void __dev_remove_pack(struct packet_type *pt)
 438{
 439        struct list_head *head = ptype_head(pt);
 440        struct packet_type *pt1;
 441
 442        spin_lock(&ptype_lock);
 443
 444        list_for_each_entry(pt1, head, list) {
 445                if (pt == pt1) {
 446                        list_del_rcu(&pt->list);
 447                        goto out;
 448                }
 449        }
 450
 451        pr_warn("dev_remove_pack: %p not found\n", pt);
 452out:
 453        spin_unlock(&ptype_lock);
 454}
 455EXPORT_SYMBOL(__dev_remove_pack);
 456
 457/**
 458 *      dev_remove_pack  - remove packet handler
 459 *      @pt: packet type declaration
 460 *
 461 *      Remove a protocol handler that was previously added to the kernel
 462 *      protocol handlers by dev_add_pack(). The passed &packet_type is removed
 463 *      from the kernel lists and can be freed or reused once this function
 464 *      returns.
 465 *
 466 *      This call sleeps to guarantee that no CPU is looking at the packet
 467 *      type after return.
 468 */
 469void dev_remove_pack(struct packet_type *pt)
 470{
 471        __dev_remove_pack(pt);
 472
 473        synchronize_net();
 474}
 475EXPORT_SYMBOL(dev_remove_pack);
 476
 477
 478/**
 479 *      dev_add_offload - register offload handlers
 480 *      @po: protocol offload declaration
 481 *
 482 *      Add protocol offload handlers to the networking stack. The passed
 483 *      &proto_offload is linked into kernel lists and may not be freed until
 484 *      it has been removed from the kernel lists.
 485 *
 486 *      This call does not sleep therefore it can not
 487 *      guarantee all CPU's that are in middle of receiving packets
 488 *      will see the new offload handlers (until the next received packet).
 489 */
 490void dev_add_offload(struct packet_offload *po)
 491{
 492        struct packet_offload *elem;
 493
 494        spin_lock(&offload_lock);
 495        list_for_each_entry(elem, &offload_base, list) {
 496                if (po->priority < elem->priority)
 497                        break;
 498        }
 499        list_add_rcu(&po->list, elem->list.prev);
 500        spin_unlock(&offload_lock);
 501}
 502EXPORT_SYMBOL(dev_add_offload);
 503
 504/**
 505 *      __dev_remove_offload     - remove offload handler
 506 *      @po: packet offload declaration
 507 *
 508 *      Remove a protocol offload handler that was previously added to the
 509 *      kernel offload handlers by dev_add_offload(). The passed &offload_type
 510 *      is removed from the kernel lists and can be freed or reused once this
 511 *      function returns.
 512 *
 513 *      The packet type might still be in use by receivers
 514 *      and must not be freed until after all the CPU's have gone
 515 *      through a quiescent state.
 516 */
 517static void __dev_remove_offload(struct packet_offload *po)
 518{
 519        struct list_head *head = &offload_base;
 520        struct packet_offload *po1;
 521
 522        spin_lock(&offload_lock);
 523
 524        list_for_each_entry(po1, head, list) {
 525                if (po == po1) {
 526                        list_del_rcu(&po->list);
 527                        goto out;
 528                }
 529        }
 530
 531        pr_warn("dev_remove_offload: %p not found\n", po);
 532out:
 533        spin_unlock(&offload_lock);
 534}
 535
 536/**
 537 *      dev_remove_offload       - remove packet offload handler
 538 *      @po: packet offload declaration
 539 *
 540 *      Remove a packet offload handler that was previously added to the kernel
 541 *      offload handlers by dev_add_offload(). The passed &offload_type is
 542 *      removed from the kernel lists and can be freed or reused once this
 543 *      function returns.
 544 *
 545 *      This call sleeps to guarantee that no CPU is looking at the packet
 546 *      type after return.
 547 */
 548void dev_remove_offload(struct packet_offload *po)
 549{
 550        __dev_remove_offload(po);
 551
 552        synchronize_net();
 553}
 554EXPORT_SYMBOL(dev_remove_offload);
 555
 556/******************************************************************************
 557 *
 558 *                    Device Boot-time Settings Routines
 559 *
 560 ******************************************************************************/
 561
 562/* Boot time configuration table */
 563static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
 564
 565/**
 566 *      netdev_boot_setup_add   - add new setup entry
 567 *      @name: name of the device
 568 *      @map: configured settings for the device
 569 *
 570 *      Adds new setup entry to the dev_boot_setup list.  The function
 571 *      returns 0 on error and 1 on success.  This is a generic routine to
 572 *      all netdevices.
 573 */
 574static int netdev_boot_setup_add(char *name, struct ifmap *map)
 575{
 576        struct netdev_boot_setup *s;
 577        int i;
 578
 579        s = dev_boot_setup;
 580        for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
 581                if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
 582                        memset(s[i].name, 0, sizeof(s[i].name));
 583                        strlcpy(s[i].name, name, IFNAMSIZ);
 584                        memcpy(&s[i].map, map, sizeof(s[i].map));
 585                        break;
 586                }
 587        }
 588
 589        return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
 590}
 591
 592/**
 593 * netdev_boot_setup_check      - check boot time settings
 594 * @dev: the netdevice
 595 *
 596 * Check boot time settings for the device.
 597 * The found settings are set for the device to be used
 598 * later in the device probing.
 599 * Returns 0 if no settings found, 1 if they are.
 600 */
 601int netdev_boot_setup_check(struct net_device *dev)
 602{
 603        struct netdev_boot_setup *s = dev_boot_setup;
 604        int i;
 605
 606        for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
 607                if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
 608                    !strcmp(dev->name, s[i].name)) {
 609                        dev->irq = s[i].map.irq;
 610                        dev->base_addr = s[i].map.base_addr;
 611                        dev->mem_start = s[i].map.mem_start;
 612                        dev->mem_end = s[i].map.mem_end;
 613                        return 1;
 614                }
 615        }
 616        return 0;
 617}
 618EXPORT_SYMBOL(netdev_boot_setup_check);
 619
 620
 621/**
 622 * netdev_boot_base     - get address from boot time settings
 623 * @prefix: prefix for network device
 624 * @unit: id for network device
 625 *
 626 * Check boot time settings for the base address of device.
 627 * The found settings are set for the device to be used
 628 * later in the device probing.
 629 * Returns 0 if no settings found.
 630 */
 631unsigned long netdev_boot_base(const char *prefix, int unit)
 632{
 633        const struct netdev_boot_setup *s = dev_boot_setup;
 634        char name[IFNAMSIZ];
 635        int i;
 636
 637        sprintf(name, "%s%d", prefix, unit);
 638
 639        /*
 640         * If device already registered then return base of 1
 641         * to indicate not to probe for this interface
 642         */
 643        if (__dev_get_by_name(&init_net, name))
 644                return 1;
 645
 646        for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
 647                if (!strcmp(name, s[i].name))
 648                        return s[i].map.base_addr;
 649        return 0;
 650}
 651
 652/*
 653 * Saves at boot time configured settings for any netdevice.
 654 */
 655int __init netdev_boot_setup(char *str)
 656{
 657        int ints[5];
 658        struct ifmap map;
 659
 660        str = get_options(str, ARRAY_SIZE(ints), ints);
 661        if (!str || !*str)
 662                return 0;
 663
 664        /* Save settings */
 665        memset(&map, 0, sizeof(map));
 666        if (ints[0] > 0)
 667                map.irq = ints[1];
 668        if (ints[0] > 1)
 669                map.base_addr = ints[2];
 670        if (ints[0] > 2)
 671                map.mem_start = ints[3];
 672        if (ints[0] > 3)
 673                map.mem_end = ints[4];
 674
 675        /* Add new entry to the list */
 676        return netdev_boot_setup_add(str, &map);
 677}
 678
 679__setup("netdev=", netdev_boot_setup);
 680
 681/*******************************************************************************
 682 *
 683 *                          Device Interface Subroutines
 684 *
 685 *******************************************************************************/
 686
 687/**
 688 *      dev_get_iflink  - get 'iflink' value of a interface
 689 *      @dev: targeted interface
 690 *
 691 *      Indicates the ifindex the interface is linked to.
 692 *      Physical interfaces have the same 'ifindex' and 'iflink' values.
 693 */
 694
 695int dev_get_iflink(const struct net_device *dev)
 696{
 697        if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
 698                return dev->netdev_ops->ndo_get_iflink(dev);
 699
 700        return dev->ifindex;
 701}
 702EXPORT_SYMBOL(dev_get_iflink);
 703
 704/**
 705 *      dev_fill_metadata_dst - Retrieve tunnel egress information.
 706 *      @dev: targeted interface
 707 *      @skb: The packet.
 708 *
 709 *      For better visibility of tunnel traffic OVS needs to retrieve
 710 *      egress tunnel information for a packet. Following API allows
 711 *      user to get this info.
 712 */
 713int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
 714{
 715        struct ip_tunnel_info *info;
 716
 717        if (!dev->netdev_ops  || !dev->netdev_ops->ndo_fill_metadata_dst)
 718                return -EINVAL;
 719
 720        info = skb_tunnel_info_unclone(skb);
 721        if (!info)
 722                return -ENOMEM;
 723        if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
 724                return -EINVAL;
 725
 726        return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
 727}
 728EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
 729
 730/**
 731 *      __dev_get_by_name       - find a device by its name
 732 *      @net: the applicable net namespace
 733 *      @name: name to find
 734 *
 735 *      Find an interface by name. Must be called under RTNL semaphore
 736 *      or @dev_base_lock. If the name is found a pointer to the device
 737 *      is returned. If the name is not found then %NULL is returned. The
 738 *      reference counters are not incremented so the caller must be
 739 *      careful with locks.
 740 */
 741
 742struct net_device *__dev_get_by_name(struct net *net, const char *name)
 743{
 744        struct net_device *dev;
 745        struct hlist_head *head = dev_name_hash(net, name);
 746
 747        hlist_for_each_entry(dev, head, name_hlist)
 748                if (!strncmp(dev->name, name, IFNAMSIZ))
 749                        return dev;
 750
 751        return NULL;
 752}
 753EXPORT_SYMBOL(__dev_get_by_name);
 754
 755/**
 756 * dev_get_by_name_rcu  - find a device by its name
 757 * @net: the applicable net namespace
 758 * @name: name to find
 759 *
 760 * Find an interface by name.
 761 * If the name is found a pointer to the device is returned.
 762 * If the name is not found then %NULL is returned.
 763 * The reference counters are not incremented so the caller must be
 764 * careful with locks. The caller must hold RCU lock.
 765 */
 766
 767struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
 768{
 769        struct net_device *dev;
 770        struct hlist_head *head = dev_name_hash(net, name);
 771
 772        hlist_for_each_entry_rcu(dev, head, name_hlist)
 773                if (!strncmp(dev->name, name, IFNAMSIZ))
 774                        return dev;
 775
 776        return NULL;
 777}
 778EXPORT_SYMBOL(dev_get_by_name_rcu);
 779
 780/**
 781 *      dev_get_by_name         - find a device by its name
 782 *      @net: the applicable net namespace
 783 *      @name: name to find
 784 *
 785 *      Find an interface by name. This can be called from any
 786 *      context and does its own locking. The returned handle has
 787 *      the usage count incremented and the caller must use dev_put() to
 788 *      release it when it is no longer needed. %NULL is returned if no
 789 *      matching device is found.
 790 */
 791
 792struct net_device *dev_get_by_name(struct net *net, const char *name)
 793{
 794        struct net_device *dev;
 795
 796        rcu_read_lock();
 797        dev = dev_get_by_name_rcu(net, name);
 798        if (dev)
 799                dev_hold(dev);
 800        rcu_read_unlock();
 801        return dev;
 802}
 803EXPORT_SYMBOL(dev_get_by_name);
 804
 805/**
 806 *      __dev_get_by_index - find a device by its ifindex
 807 *      @net: the applicable net namespace
 808 *      @ifindex: index of device
 809 *
 810 *      Search for an interface by index. Returns %NULL if the device
 811 *      is not found or a pointer to the device. The device has not
 812 *      had its reference counter increased so the caller must be careful
 813 *      about locking. The caller must hold either the RTNL semaphore
 814 *      or @dev_base_lock.
 815 */
 816
 817struct net_device *__dev_get_by_index(struct net *net, int ifindex)
 818{
 819        struct net_device *dev;
 820        struct hlist_head *head = dev_index_hash(net, ifindex);
 821
 822        hlist_for_each_entry(dev, head, index_hlist)
 823                if (dev->ifindex == ifindex)
 824                        return dev;
 825
 826        return NULL;
 827}
 828EXPORT_SYMBOL(__dev_get_by_index);
 829
 830/**
 831 *      dev_get_by_index_rcu - find a device by its ifindex
 832 *      @net: the applicable net namespace
 833 *      @ifindex: index of device
 834 *
 835 *      Search for an interface by index. Returns %NULL if the device
 836 *      is not found or a pointer to the device. The device has not
 837 *      had its reference counter increased so the caller must be careful
 838 *      about locking. The caller must hold RCU lock.
 839 */
 840
 841struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
 842{
 843        struct net_device *dev;
 844        struct hlist_head *head = dev_index_hash(net, ifindex);
 845
 846        hlist_for_each_entry_rcu(dev, head, index_hlist)
 847                if (dev->ifindex == ifindex)
 848                        return dev;
 849
 850        return NULL;
 851}
 852EXPORT_SYMBOL(dev_get_by_index_rcu);
 853
 854
 855/**
 856 *      dev_get_by_index - find a device by its ifindex
 857 *      @net: the applicable net namespace
 858 *      @ifindex: index of device
 859 *
 860 *      Search for an interface by index. Returns NULL if the device
 861 *      is not found or a pointer to the device. The device returned has
 862 *      had a reference added and the pointer is safe until the user calls
 863 *      dev_put to indicate they have finished with it.
 864 */
 865
 866struct net_device *dev_get_by_index(struct net *net, int ifindex)
 867{
 868        struct net_device *dev;
 869
 870        rcu_read_lock();
 871        dev = dev_get_by_index_rcu(net, ifindex);
 872        if (dev)
 873                dev_hold(dev);
 874        rcu_read_unlock();
 875        return dev;
 876}
 877EXPORT_SYMBOL(dev_get_by_index);
 878
 879/**
 880 *      dev_get_by_napi_id - find a device by napi_id
 881 *      @napi_id: ID of the NAPI struct
 882 *
 883 *      Search for an interface by NAPI ID. Returns %NULL if the device
 884 *      is not found or a pointer to the device. The device has not had
 885 *      its reference counter increased so the caller must be careful
 886 *      about locking. The caller must hold RCU lock.
 887 */
 888
 889struct net_device *dev_get_by_napi_id(unsigned int napi_id)
 890{
 891        struct napi_struct *napi;
 892
 893        WARN_ON_ONCE(!rcu_read_lock_held());
 894
 895        if (napi_id < MIN_NAPI_ID)
 896                return NULL;
 897
 898        napi = napi_by_id(napi_id);
 899
 900        return napi ? napi->dev : NULL;
 901}
 902EXPORT_SYMBOL(dev_get_by_napi_id);
 903
 904/**
 905 *      netdev_get_name - get a netdevice name, knowing its ifindex.
 906 *      @net: network namespace
 907 *      @name: a pointer to the buffer where the name will be stored.
 908 *      @ifindex: the ifindex of the interface to get the name from.
 909 *
 910 *      The use of raw_seqcount_begin() and cond_resched() before
 911 *      retrying is required as we want to give the writers a chance
 912 *      to complete when CONFIG_PREEMPT is not set.
 913 */
 914int netdev_get_name(struct net *net, char *name, int ifindex)
 915{
 916        struct net_device *dev;
 917        unsigned int seq;
 918
 919retry:
 920        seq = raw_seqcount_begin(&devnet_rename_seq);
 921        rcu_read_lock();
 922        dev = dev_get_by_index_rcu(net, ifindex);
 923        if (!dev) {
 924                rcu_read_unlock();
 925                return -ENODEV;
 926        }
 927
 928        strcpy(name, dev->name);
 929        rcu_read_unlock();
 930        if (read_seqcount_retry(&devnet_rename_seq, seq)) {
 931                cond_resched();
 932                goto retry;
 933        }
 934
 935        return 0;
 936}
 937
 938/**
 939 *      dev_getbyhwaddr_rcu - find a device by its hardware address
 940 *      @net: the applicable net namespace
 941 *      @type: media type of device
 942 *      @ha: hardware address
 943 *
 944 *      Search for an interface by MAC address. Returns NULL if the device
 945 *      is not found or a pointer to the device.
 946 *      The caller must hold RCU or RTNL.
 947 *      The returned device has not had its ref count increased
 948 *      and the caller must therefore be careful about locking
 949 *
 950 */
 951
 952struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
 953                                       const char *ha)
 954{
 955        struct net_device *dev;
 956
 957        for_each_netdev_rcu(net, dev)
 958                if (dev->type == type &&
 959                    !memcmp(dev->dev_addr, ha, dev->addr_len))
 960                        return dev;
 961
 962        return NULL;
 963}
 964EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
 965
 966struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
 967{
 968        struct net_device *dev;
 969
 970        ASSERT_RTNL();
 971        for_each_netdev(net, dev)
 972                if (dev->type == type)
 973                        return dev;
 974
 975        return NULL;
 976}
 977EXPORT_SYMBOL(__dev_getfirstbyhwtype);
 978
 979struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
 980{
 981        struct net_device *dev, *ret = NULL;
 982
 983        rcu_read_lock();
 984        for_each_netdev_rcu(net, dev)
 985                if (dev->type == type) {
 986                        dev_hold(dev);
 987                        ret = dev;
 988                        break;
 989                }
 990        rcu_read_unlock();
 991        return ret;
 992}
 993EXPORT_SYMBOL(dev_getfirstbyhwtype);
 994
 995/**
 996 *      __dev_get_by_flags - find any device with given flags
 997 *      @net: the applicable net namespace
 998 *      @if_flags: IFF_* values
 999 *      @mask: bitmask of bits in if_flags to check
1000 *
1001 *      Search for any interface with the given flags. Returns NULL if a device
1002 *      is not found or a pointer to the device. Must be called inside
1003 *      rtnl_lock(), and result refcount is unchanged.
1004 */
1005
1006struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1007                                      unsigned short mask)
1008{
1009        struct net_device *dev, *ret;
1010
1011        ASSERT_RTNL();
1012
1013        ret = NULL;
1014        for_each_netdev(net, dev) {
1015                if (((dev->flags ^ if_flags) & mask) == 0) {
1016                        ret = dev;
1017                        break;
1018                }
1019        }
1020        return ret;
1021}
1022EXPORT_SYMBOL(__dev_get_by_flags);
1023
1024/**
1025 *      dev_valid_name - check if name is okay for network device
1026 *      @name: name string
1027 *
1028 *      Network device names need to be valid file names to
1029 *      to allow sysfs to work.  We also disallow any kind of
1030 *      whitespace.
1031 */
1032bool dev_valid_name(const char *name)
1033{
1034        if (*name == '\0')
1035                return false;
1036        if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1037                return false;
1038        if (!strcmp(name, ".") || !strcmp(name, ".."))
1039                return false;
1040
1041        while (*name) {
1042                if (*name == '/' || *name == ':' || isspace(*name))
1043                        return false;
1044                name++;
1045        }
1046        return true;
1047}
1048EXPORT_SYMBOL(dev_valid_name);
1049
1050/**
1051 *      __dev_alloc_name - allocate a name for a device
1052 *      @net: network namespace to allocate the device name in
1053 *      @name: name format string
1054 *      @buf:  scratch buffer and result name string
1055 *
1056 *      Passed a format string - eg "lt%d" it will try and find a suitable
1057 *      id. It scans list of devices to build up a free map, then chooses
1058 *      the first empty slot. The caller must hold the dev_base or rtnl lock
1059 *      while allocating the name and adding the device in order to avoid
1060 *      duplicates.
1061 *      Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1062 *      Returns the number of the unit assigned or a negative errno code.
1063 */
1064
1065static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1066{
1067        int i = 0;
1068        const char *p;
1069        const int max_netdevices = 8*PAGE_SIZE;
1070        unsigned long *inuse;
1071        struct net_device *d;
1072
1073        if (!dev_valid_name(name))
1074                return -EINVAL;
1075
1076        p = strchr(name, '%');
1077        if (p) {
1078                /*
1079                 * Verify the string as this thing may have come from
1080                 * the user.  There must be either one "%d" and no other "%"
1081                 * characters.
1082                 */
1083                if (p[1] != 'd' || strchr(p + 2, '%'))
1084                        return -EINVAL;
1085
1086                /* Use one page as a bit array of possible slots */
1087                inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1088                if (!inuse)
1089                        return -ENOMEM;
1090
1091                for_each_netdev(net, d) {
1092                        if (!sscanf(d->name, name, &i))
1093                                continue;
1094                        if (i < 0 || i >= max_netdevices)
1095                                continue;
1096
1097                        /*  avoid cases where sscanf is not exact inverse of printf */
1098                        snprintf(buf, IFNAMSIZ, name, i);
1099                        if (!strncmp(buf, d->name, IFNAMSIZ))
1100                                set_bit(i, inuse);
1101                }
1102
1103                i = find_first_zero_bit(inuse, max_netdevices);
1104                free_page((unsigned long) inuse);
1105        }
1106
1107        snprintf(buf, IFNAMSIZ, name, i);
1108        if (!__dev_get_by_name(net, buf))
1109                return i;
1110
1111        /* It is possible to run out of possible slots
1112         * when the name is long and there isn't enough space left
1113         * for the digits, or if all bits are used.
1114         */
1115        return -ENFILE;
1116}
1117
1118static int dev_alloc_name_ns(struct net *net,
1119                             struct net_device *dev,
1120                             const char *name)
1121{
1122        char buf[IFNAMSIZ];
1123        int ret;
1124
1125        BUG_ON(!net);
1126        ret = __dev_alloc_name(net, name, buf);
1127        if (ret >= 0)
1128                strlcpy(dev->name, buf, IFNAMSIZ);
1129        return ret;
1130}
1131
1132/**
1133 *      dev_alloc_name - allocate a name for a device
1134 *      @dev: device
1135 *      @name: name format string
1136 *
1137 *      Passed a format string - eg "lt%d" it will try and find a suitable
1138 *      id. It scans list of devices to build up a free map, then chooses
1139 *      the first empty slot. The caller must hold the dev_base or rtnl lock
1140 *      while allocating the name and adding the device in order to avoid
1141 *      duplicates.
1142 *      Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1143 *      Returns the number of the unit assigned or a negative errno code.
1144 */
1145
1146int dev_alloc_name(struct net_device *dev, const char *name)
1147{
1148        return dev_alloc_name_ns(dev_net(dev), dev, name);
1149}
1150EXPORT_SYMBOL(dev_alloc_name);
1151
1152int dev_get_valid_name(struct net *net, struct net_device *dev,
1153                       const char *name)
1154{
1155        BUG_ON(!net);
1156
1157        if (!dev_valid_name(name))
1158                return -EINVAL;
1159
1160        if (strchr(name, '%'))
1161                return dev_alloc_name_ns(net, dev, name);
1162        else if (__dev_get_by_name(net, name))
1163                return -EEXIST;
1164        else if (dev->name != name)
1165                strlcpy(dev->name, name, IFNAMSIZ);
1166
1167        return 0;
1168}
1169EXPORT_SYMBOL(dev_get_valid_name);
1170
1171/**
1172 *      dev_change_name - change name of a device
1173 *      @dev: device
1174 *      @newname: name (or format string) must be at least IFNAMSIZ
1175 *
1176 *      Change name of a device, can pass format strings "eth%d".
1177 *      for wildcarding.
1178 */
1179int dev_change_name(struct net_device *dev, const char *newname)
1180{
1181        unsigned char old_assign_type;
1182        char oldname[IFNAMSIZ];
1183        int err = 0;
1184        int ret;
1185        struct net *net;
1186
1187        ASSERT_RTNL();
1188        BUG_ON(!dev_net(dev));
1189
1190        net = dev_net(dev);
1191        if (dev->flags & IFF_UP)
1192                return -EBUSY;
1193
1194        write_seqcount_begin(&devnet_rename_seq);
1195
1196        if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1197                write_seqcount_end(&devnet_rename_seq);
1198                return 0;
1199        }
1200
1201        memcpy(oldname, dev->name, IFNAMSIZ);
1202
1203        err = dev_get_valid_name(net, dev, newname);
1204        if (err < 0) {
1205                write_seqcount_end(&devnet_rename_seq);
1206                return err;
1207        }
1208
1209        if (oldname[0] && !strchr(oldname, '%'))
1210                netdev_info(dev, "renamed from %s\n", oldname);
1211
1212        old_assign_type = dev->name_assign_type;
1213        dev->name_assign_type = NET_NAME_RENAMED;
1214
1215rollback:
1216        ret = device_rename(&dev->dev, dev->name);
1217        if (ret) {
1218                memcpy(dev->name, oldname, IFNAMSIZ);
1219                dev->name_assign_type = old_assign_type;
1220                write_seqcount_end(&devnet_rename_seq);
1221                return ret;
1222        }
1223
1224        write_seqcount_end(&devnet_rename_seq);
1225
1226        netdev_adjacent_rename_links(dev, oldname);
1227
1228        write_lock_bh(&dev_base_lock);
1229        hlist_del_rcu(&dev->name_hlist);
1230        write_unlock_bh(&dev_base_lock);
1231
1232        synchronize_rcu();
1233
1234        write_lock_bh(&dev_base_lock);
1235        hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
1236        write_unlock_bh(&dev_base_lock);
1237
1238        ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1239        ret = notifier_to_errno(ret);
1240
1241        if (ret) {
1242                /* err >= 0 after dev_alloc_name() or stores the first errno */
1243                if (err >= 0) {
1244                        err = ret;
1245                        write_seqcount_begin(&devnet_rename_seq);
1246                        memcpy(dev->name, oldname, IFNAMSIZ);
1247                        memcpy(oldname, newname, IFNAMSIZ);
1248                        dev->name_assign_type = old_assign_type;
1249                        old_assign_type = NET_NAME_RENAMED;
1250                        goto rollback;
1251                } else {
1252                        pr_err("%s: name change rollback failed: %d\n",
1253                               dev->name, ret);
1254                }
1255        }
1256
1257        return err;
1258}
1259
1260/**
1261 *      dev_set_alias - change ifalias of a device
1262 *      @dev: device
1263 *      @alias: name up to IFALIASZ
1264 *      @len: limit of bytes to copy from info
1265 *
1266 *      Set ifalias for a device,
1267 */
1268int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1269{
1270        struct dev_ifalias *new_alias = NULL;
1271
1272        if (len >= IFALIASZ)
1273                return -EINVAL;
1274
1275        if (len) {
1276                new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1277                if (!new_alias)
1278                        return -ENOMEM;
1279
1280                memcpy(new_alias->ifalias, alias, len);
1281                new_alias->ifalias[len] = 0;
1282        }
1283
1284        mutex_lock(&ifalias_mutex);
1285        rcu_swap_protected(dev->ifalias, new_alias,
1286                           mutex_is_locked(&ifalias_mutex));
1287        mutex_unlock(&ifalias_mutex);
1288
1289        if (new_alias)
1290                kfree_rcu(new_alias, rcuhead);
1291
1292        return len;
1293}
1294EXPORT_SYMBOL(dev_set_alias);
1295
1296/**
1297 *      dev_get_alias - get ifalias of a device
1298 *      @dev: device
1299 *      @name: buffer to store name of ifalias
1300 *      @len: size of buffer
1301 *
1302 *      get ifalias for a device.  Caller must make sure dev cannot go
1303 *      away,  e.g. rcu read lock or own a reference count to device.
1304 */
1305int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1306{
1307        const struct dev_ifalias *alias;
1308        int ret = 0;
1309
1310        rcu_read_lock();
1311        alias = rcu_dereference(dev->ifalias);
1312        if (alias)
1313                ret = snprintf(name, len, "%s", alias->ifalias);
1314        rcu_read_unlock();
1315
1316        return ret;
1317}
1318
1319/**
1320 *      netdev_features_change - device changes features
1321 *      @dev: device to cause notification
1322 *
1323 *      Called to indicate a device has changed features.
1324 */
1325void netdev_features_change(struct net_device *dev)
1326{
1327        call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1328}
1329EXPORT_SYMBOL(netdev_features_change);
1330
1331/**
1332 *      netdev_state_change - device changes state
1333 *      @dev: device to cause notification
1334 *
1335 *      Called to indicate a device has changed state. This function calls
1336 *      the notifier chains for netdev_chain and sends a NEWLINK message
1337 *      to the routing socket.
1338 */
1339void netdev_state_change(struct net_device *dev)
1340{
1341        if (dev->flags & IFF_UP) {
1342                struct netdev_notifier_change_info change_info = {
1343                        .info.dev = dev,
1344                };
1345
1346                call_netdevice_notifiers_info(NETDEV_CHANGE,
1347                                              &change_info.info);
1348                rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
1349        }
1350}
1351EXPORT_SYMBOL(netdev_state_change);
1352
1353/**
1354 * netdev_notify_peers - notify network peers about existence of @dev
1355 * @dev: network device
1356 *
1357 * Generate traffic such that interested network peers are aware of
1358 * @dev, such as by generating a gratuitous ARP. This may be used when
1359 * a device wants to inform the rest of the network about some sort of
1360 * reconfiguration such as a failover event or virtual machine
1361 * migration.
1362 */
1363void netdev_notify_peers(struct net_device *dev)
1364{
1365        rtnl_lock();
1366        call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1367        call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1368        rtnl_unlock();
1369}
1370EXPORT_SYMBOL(netdev_notify_peers);
1371
1372static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1373{
1374        const struct net_device_ops *ops = dev->netdev_ops;
1375        int ret;
1376
1377        ASSERT_RTNL();
1378
1379        if (!netif_device_present(dev))
1380                return -ENODEV;
1381
1382        /* Block netpoll from trying to do any rx path servicing.
1383         * If we don't do this there is a chance ndo_poll_controller
1384         * or ndo_poll may be running while we open the device
1385         */
1386        netpoll_poll_disable(dev);
1387
1388        ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1389        ret = notifier_to_errno(ret);
1390        if (ret)
1391                return ret;
1392
1393        set_bit(__LINK_STATE_START, &dev->state);
1394
1395        if (ops->ndo_validate_addr)
1396                ret = ops->ndo_validate_addr(dev);
1397
1398        if (!ret && ops->ndo_open)
1399                ret = ops->ndo_open(dev);
1400
1401        netpoll_poll_enable(dev);
1402
1403        if (ret)
1404                clear_bit(__LINK_STATE_START, &dev->state);
1405        else {
1406                dev->flags |= IFF_UP;
1407                dev_set_rx_mode(dev);
1408                dev_activate(dev);
1409                add_device_randomness(dev->dev_addr, dev->addr_len);
1410        }
1411
1412        return ret;
1413}
1414
1415/**
1416 *      dev_open        - prepare an interface for use.
1417 *      @dev: device to open
1418 *      @extack: netlink extended ack
1419 *
1420 *      Takes a device from down to up state. The device's private open
1421 *      function is invoked and then the multicast lists are loaded. Finally
1422 *      the device is moved into the up state and a %NETDEV_UP message is
1423 *      sent to the netdev notifier chain.
1424 *
1425 *      Calling this function on an active interface is a nop. On a failure
1426 *      a negative errno code is returned.
1427 */
1428int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1429{
1430        int ret;
1431
1432        if (dev->flags & IFF_UP)
1433                return 0;
1434
1435        ret = __dev_open(dev, extack);
1436        if (ret < 0)
1437                return ret;
1438
1439        rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1440        call_netdevice_notifiers(NETDEV_UP, dev);
1441
1442        return ret;
1443}
1444EXPORT_SYMBOL(dev_open);
1445
1446static void __dev_close_many(struct list_head *head)
1447{
1448        struct net_device *dev;
1449
1450        ASSERT_RTNL();
1451        might_sleep();
1452
1453        list_for_each_entry(dev, head, close_list) {
1454                /* Temporarily disable netpoll until the interface is down */
1455                netpoll_poll_disable(dev);
1456
1457                call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1458
1459                clear_bit(__LINK_STATE_START, &dev->state);
1460
1461                /* Synchronize to scheduled poll. We cannot touch poll list, it
1462                 * can be even on different cpu. So just clear netif_running().
1463                 *
1464                 * dev->stop() will invoke napi_disable() on all of it's
1465                 * napi_struct instances on this device.
1466                 */
1467                smp_mb__after_atomic(); /* Commit netif_running(). */
1468        }
1469
1470        dev_deactivate_many(head);
1471
1472        list_for_each_entry(dev, head, close_list) {
1473                const struct net_device_ops *ops = dev->netdev_ops;
1474
1475                /*
1476                 *      Call the device specific close. This cannot fail.
1477                 *      Only if device is UP
1478                 *
1479                 *      We allow it to be called even after a DETACH hot-plug
1480                 *      event.
1481                 */
1482                if (ops->ndo_stop)
1483                        ops->ndo_stop(dev);
1484
1485                dev->flags &= ~IFF_UP;
1486                netpoll_poll_enable(dev);
1487        }
1488}
1489
1490static void __dev_close(struct net_device *dev)
1491{
1492        LIST_HEAD(single);
1493
1494        list_add(&dev->close_list, &single);
1495        __dev_close_many(&single);
1496        list_del(&single);
1497}
1498
1499void dev_close_many(struct list_head *head, bool unlink)
1500{
1501        struct net_device *dev, *tmp;
1502
1503        /* Remove the devices that don't need to be closed */
1504        list_for_each_entry_safe(dev, tmp, head, close_list)
1505                if (!(dev->flags & IFF_UP))
1506                        list_del_init(&dev->close_list);
1507
1508        __dev_close_many(head);
1509
1510        list_for_each_entry_safe(dev, tmp, head, close_list) {
1511                rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1512                call_netdevice_notifiers(NETDEV_DOWN, dev);
1513                if (unlink)
1514                        list_del_init(&dev->close_list);
1515        }
1516}
1517EXPORT_SYMBOL(dev_close_many);
1518
1519/**
1520 *      dev_close - shutdown an interface.
1521 *      @dev: device to shutdown
1522 *
1523 *      This function moves an active device into down state. A
1524 *      %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1525 *      is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1526 *      chain.
1527 */
1528void dev_close(struct net_device *dev)
1529{
1530        if (dev->flags & IFF_UP) {
1531                LIST_HEAD(single);
1532
1533                list_add(&dev->close_list, &single);
1534                dev_close_many(&single, true);
1535                list_del(&single);
1536        }
1537}
1538EXPORT_SYMBOL(dev_close);
1539
1540
1541/**
1542 *      dev_disable_lro - disable Large Receive Offload on a device
1543 *      @dev: device
1544 *
1545 *      Disable Large Receive Offload (LRO) on a net device.  Must be
1546 *      called under RTNL.  This is needed if received packets may be
1547 *      forwarded to another interface.
1548 */
1549void dev_disable_lro(struct net_device *dev)
1550{
1551        struct net_device *lower_dev;
1552        struct list_head *iter;
1553
1554        dev->wanted_features &= ~NETIF_F_LRO;
1555        netdev_update_features(dev);
1556
1557        if (unlikely(dev->features & NETIF_F_LRO))
1558                netdev_WARN(dev, "failed to disable LRO!\n");
1559
1560        netdev_for_each_lower_dev(dev, lower_dev, iter)
1561                dev_disable_lro(lower_dev);
1562}
1563EXPORT_SYMBOL(dev_disable_lro);
1564
1565/**
1566 *      dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1567 *      @dev: device
1568 *
1569 *      Disable HW Generic Receive Offload (GRO_HW) on a net device.  Must be
1570 *      called under RTNL.  This is needed if Generic XDP is installed on
1571 *      the device.
1572 */
1573static void dev_disable_gro_hw(struct net_device *dev)
1574{
1575        dev->wanted_features &= ~NETIF_F_GRO_HW;
1576        netdev_update_features(dev);
1577
1578        if (unlikely(dev->features & NETIF_F_GRO_HW))
1579                netdev_WARN(dev, "failed to disable GRO_HW!\n");
1580}
1581
1582const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1583{
1584#define N(val)                                          \
1585        case NETDEV_##val:                              \
1586                return "NETDEV_" __stringify(val);
1587        switch (cmd) {
1588        N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1589        N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1590        N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1591        N(POST_INIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN) N(CHANGEUPPER)
1592        N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA) N(BONDING_INFO)
1593        N(PRECHANGEUPPER) N(CHANGELOWERSTATE) N(UDP_TUNNEL_PUSH_INFO)
1594        N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1595        N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1596        N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1597        N(PRE_CHANGEADDR)
1598        }
1599#undef N
1600        return "UNKNOWN_NETDEV_EVENT";
1601}
1602EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1603
1604static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1605                                   struct net_device *dev)
1606{
1607        struct netdev_notifier_info info = {
1608                .dev = dev,
1609        };
1610
1611        return nb->notifier_call(nb, val, &info);
1612}
1613
1614static int dev_boot_phase = 1;
1615
1616/**
1617 * register_netdevice_notifier - register a network notifier block
1618 * @nb: notifier
1619 *
1620 * Register a notifier to be called when network device events occur.
1621 * The notifier passed is linked into the kernel structures and must
1622 * not be reused until it has been unregistered. A negative errno code
1623 * is returned on a failure.
1624 *
1625 * When registered all registration and up events are replayed
1626 * to the new notifier to allow device to have a race free
1627 * view of the network device list.
1628 */
1629
1630int register_netdevice_notifier(struct notifier_block *nb)
1631{
1632        struct net_device *dev;
1633        struct net_device *last;
1634        struct net *net;
1635        int err;
1636
1637        /* Close race with setup_net() and cleanup_net() */
1638        down_write(&pernet_ops_rwsem);
1639        rtnl_lock();
1640        err = raw_notifier_chain_register(&netdev_chain, nb);
1641        if (err)
1642                goto unlock;
1643        if (dev_boot_phase)
1644                goto unlock;
1645        for_each_net(net) {
1646                for_each_netdev(net, dev) {
1647                        err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1648                        err = notifier_to_errno(err);
1649                        if (err)
1650                                goto rollback;
1651
1652                        if (!(dev->flags & IFF_UP))
1653                                continue;
1654
1655                        call_netdevice_notifier(nb, NETDEV_UP, dev);
1656                }
1657        }
1658
1659unlock:
1660        rtnl_unlock();
1661        up_write(&pernet_ops_rwsem);
1662        return err;
1663
1664rollback:
1665        last = dev;
1666        for_each_net(net) {
1667                for_each_netdev(net, dev) {
1668                        if (dev == last)
1669                                goto outroll;
1670
1671                        if (dev->flags & IFF_UP) {
1672                                call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1673                                                        dev);
1674                                call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1675                        }
1676                        call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1677                }
1678        }
1679
1680outroll:
1681        raw_notifier_chain_unregister(&netdev_chain, nb);
1682        goto unlock;
1683}
1684EXPORT_SYMBOL(register_netdevice_notifier);
1685
1686/**
1687 * unregister_netdevice_notifier - unregister a network notifier block
1688 * @nb: notifier
1689 *
1690 * Unregister a notifier previously registered by
1691 * register_netdevice_notifier(). The notifier is unlinked into the
1692 * kernel structures and may then be reused. A negative errno code
1693 * is returned on a failure.
1694 *
1695 * After unregistering unregister and down device events are synthesized
1696 * for all devices on the device list to the removed notifier to remove
1697 * the need for special case cleanup code.
1698 */
1699
1700int unregister_netdevice_notifier(struct notifier_block *nb)
1701{
1702        struct net_device *dev;
1703        struct net *net;
1704        int err;
1705
1706        /* Close race with setup_net() and cleanup_net() */
1707        down_write(&pernet_ops_rwsem);
1708        rtnl_lock();
1709        err = raw_notifier_chain_unregister(&netdev_chain, nb);
1710        if (err)
1711                goto unlock;
1712
1713        for_each_net(net) {
1714                for_each_netdev(net, dev) {
1715                        if (dev->flags & IFF_UP) {
1716                                call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1717                                                        dev);
1718                                call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1719                        }
1720                        call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1721                }
1722        }
1723unlock:
1724        rtnl_unlock();
1725        up_write(&pernet_ops_rwsem);
1726        return err;
1727}
1728EXPORT_SYMBOL(unregister_netdevice_notifier);
1729
1730/**
1731 *      call_netdevice_notifiers_info - call all network notifier blocks
1732 *      @val: value passed unmodified to notifier function
1733 *      @info: notifier information data
1734 *
1735 *      Call all network notifier blocks.  Parameters and return value
1736 *      are as for raw_notifier_call_chain().
1737 */
1738
1739static int call_netdevice_notifiers_info(unsigned long val,
1740                                         struct netdev_notifier_info *info)
1741{
1742        ASSERT_RTNL();
1743        return raw_notifier_call_chain(&netdev_chain, val, info);
1744}
1745
1746static int call_netdevice_notifiers_extack(unsigned long val,
1747                                           struct net_device *dev,
1748                                           struct netlink_ext_ack *extack)
1749{
1750        struct netdev_notifier_info info = {
1751                .dev = dev,
1752                .extack = extack,
1753        };
1754
1755        return call_netdevice_notifiers_info(val, &info);
1756}
1757
1758/**
1759 *      call_netdevice_notifiers - call all network notifier blocks
1760 *      @val: value passed unmodified to notifier function
1761 *      @dev: net_device pointer passed unmodified to notifier function
1762 *
1763 *      Call all network notifier blocks.  Parameters and return value
1764 *      are as for raw_notifier_call_chain().
1765 */
1766
1767int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
1768{
1769        return call_netdevice_notifiers_extack(val, dev, NULL);
1770}
1771EXPORT_SYMBOL(call_netdevice_notifiers);
1772
1773/**
1774 *      call_netdevice_notifiers_mtu - call all network notifier blocks
1775 *      @val: value passed unmodified to notifier function
1776 *      @dev: net_device pointer passed unmodified to notifier function
1777 *      @arg: additional u32 argument passed to the notifier function
1778 *
1779 *      Call all network notifier blocks.  Parameters and return value
1780 *      are as for raw_notifier_call_chain().
1781 */
1782static int call_netdevice_notifiers_mtu(unsigned long val,
1783                                        struct net_device *dev, u32 arg)
1784{
1785        struct netdev_notifier_info_ext info = {
1786                .info.dev = dev,
1787                .ext.mtu = arg,
1788        };
1789
1790        BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
1791
1792        return call_netdevice_notifiers_info(val, &info.info);
1793}
1794
1795#ifdef CONFIG_NET_INGRESS
1796static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
1797
1798void net_inc_ingress_queue(void)
1799{
1800        static_branch_inc(&ingress_needed_key);
1801}
1802EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
1803
1804void net_dec_ingress_queue(void)
1805{
1806        static_branch_dec(&ingress_needed_key);
1807}
1808EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
1809#endif
1810
1811#ifdef CONFIG_NET_EGRESS
1812static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
1813
1814void net_inc_egress_queue(void)
1815{
1816        static_branch_inc(&egress_needed_key);
1817}
1818EXPORT_SYMBOL_GPL(net_inc_egress_queue);
1819
1820void net_dec_egress_queue(void)
1821{
1822        static_branch_dec(&egress_needed_key);
1823}
1824EXPORT_SYMBOL_GPL(net_dec_egress_queue);
1825#endif
1826
1827static DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
1828#ifdef HAVE_JUMP_LABEL
1829static atomic_t netstamp_needed_deferred;
1830static atomic_t netstamp_wanted;
1831static void netstamp_clear(struct work_struct *work)
1832{
1833        int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
1834        int wanted;
1835
1836        wanted = atomic_add_return(deferred, &netstamp_wanted);
1837        if (wanted > 0)
1838                static_branch_enable(&netstamp_needed_key);
1839        else
1840                static_branch_disable(&netstamp_needed_key);
1841}
1842static DECLARE_WORK(netstamp_work, netstamp_clear);
1843#endif
1844
1845void net_enable_timestamp(void)
1846{
1847#ifdef HAVE_JUMP_LABEL
1848        int wanted;
1849
1850        while (1) {
1851                wanted = atomic_read(&netstamp_wanted);
1852                if (wanted <= 0)
1853                        break;
1854                if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
1855                        return;
1856        }
1857        atomic_inc(&netstamp_needed_deferred);
1858        schedule_work(&netstamp_work);
1859#else
1860        static_branch_inc(&netstamp_needed_key);
1861#endif
1862}
1863EXPORT_SYMBOL(net_enable_timestamp);
1864
1865void net_disable_timestamp(void)
1866{
1867#ifdef HAVE_JUMP_LABEL
1868        int wanted;
1869
1870        while (1) {
1871                wanted = atomic_read(&netstamp_wanted);
1872                if (wanted <= 1)
1873                        break;
1874                if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
1875                        return;
1876        }
1877        atomic_dec(&netstamp_needed_deferred);
1878        schedule_work(&netstamp_work);
1879#else
1880        static_branch_dec(&netstamp_needed_key);
1881#endif
1882}
1883EXPORT_SYMBOL(net_disable_timestamp);
1884
1885static inline void net_timestamp_set(struct sk_buff *skb)
1886{
1887        skb->tstamp = 0;
1888        if (static_branch_unlikely(&netstamp_needed_key))
1889                __net_timestamp(skb);
1890}
1891
1892#define net_timestamp_check(COND, SKB)                          \
1893        if (static_branch_unlikely(&netstamp_needed_key)) {     \
1894                if ((COND) && !(SKB)->tstamp)                   \
1895                        __net_timestamp(SKB);                   \
1896        }                                                       \
1897
1898bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
1899{
1900        unsigned int len;
1901
1902        if (!(dev->flags & IFF_UP))
1903                return false;
1904
1905        len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
1906        if (skb->len <= len)
1907                return true;
1908
1909        /* if TSO is enabled, we don't care about the length as the packet
1910         * could be forwarded without being segmented before
1911         */
1912        if (skb_is_gso(skb))
1913                return true;
1914
1915        return false;
1916}
1917EXPORT_SYMBOL_GPL(is_skb_forwardable);
1918
1919int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
1920{
1921        int ret = ____dev_forward_skb(dev, skb);
1922
1923        if (likely(!ret)) {
1924                skb->protocol = eth_type_trans(skb, dev);
1925                skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
1926        }
1927
1928        return ret;
1929}
1930EXPORT_SYMBOL_GPL(__dev_forward_skb);
1931
1932/**
1933 * dev_forward_skb - loopback an skb to another netif
1934 *
1935 * @dev: destination network device
1936 * @skb: buffer to forward
1937 *
1938 * return values:
1939 *      NET_RX_SUCCESS  (no congestion)
1940 *      NET_RX_DROP     (packet was dropped, but freed)
1941 *
1942 * dev_forward_skb can be used for injecting an skb from the
1943 * start_xmit function of one device into the receive queue
1944 * of another device.
1945 *
1946 * The receiving device may be in another namespace, so
1947 * we have to clear all information in the skb that could
1948 * impact namespace isolation.
1949 */
1950int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
1951{
1952        return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
1953}
1954EXPORT_SYMBOL_GPL(dev_forward_skb);
1955
1956static inline int deliver_skb(struct sk_buff *skb,
1957                              struct packet_type *pt_prev,
1958                              struct net_device *orig_dev)
1959{
1960        if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
1961                return -ENOMEM;
1962        refcount_inc(&skb->users);
1963        return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
1964}
1965
1966static inline void deliver_ptype_list_skb(struct sk_buff *skb,
1967                                          struct packet_type **pt,
1968                                          struct net_device *orig_dev,
1969                                          __be16 type,
1970                                          struct list_head *ptype_list)
1971{
1972        struct packet_type *ptype, *pt_prev = *pt;
1973
1974        list_for_each_entry_rcu(ptype, ptype_list, list) {
1975                if (ptype->type != type)
1976                        continue;
1977                if (pt_prev)
1978                        deliver_skb(skb, pt_prev, orig_dev);
1979                pt_prev = ptype;
1980        }
1981        *pt = pt_prev;
1982}
1983
1984static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
1985{
1986        if (!ptype->af_packet_priv || !skb->sk)
1987                return false;
1988
1989        if (ptype->id_match)
1990                return ptype->id_match(ptype, skb->sk);
1991        else if ((struct sock *)ptype->af_packet_priv == skb->sk)
1992                return true;
1993
1994        return false;
1995}
1996
1997/*
1998 *      Support routine. Sends outgoing frames to any network
1999 *      taps currently in use.
2000 */
2001
2002void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2003{
2004        struct packet_type *ptype;
2005        struct sk_buff *skb2 = NULL;
2006        struct packet_type *pt_prev = NULL;
2007        struct list_head *ptype_list = &ptype_all;
2008
2009        rcu_read_lock();
2010again:
2011        list_for_each_entry_rcu(ptype, ptype_list, list) {
2012                /* Never send packets back to the socket
2013                 * they originated from - MvS (miquels@drinkel.ow.org)
2014                 */
2015                if (skb_loop_sk(ptype, skb))
2016                        continue;
2017
2018                if (pt_prev) {
2019                        deliver_skb(skb2, pt_prev, skb->dev);
2020                        pt_prev = ptype;
2021                        continue;
2022                }
2023
2024                /* need to clone skb, done only once */
2025                skb2 = skb_clone(skb, GFP_ATOMIC);
2026                if (!skb2)
2027                        goto out_unlock;
2028
2029                net_timestamp_set(skb2);
2030
2031                /* skb->nh should be correctly
2032                 * set by sender, so that the second statement is
2033                 * just protection against buggy protocols.
2034                 */
2035                skb_reset_mac_header(skb2);
2036
2037                if (skb_network_header(skb2) < skb2->data ||
2038                    skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2039                        net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2040                                             ntohs(skb2->protocol),
2041                                             dev->name);
2042                        skb_reset_network_header(skb2);
2043                }
2044
2045                skb2->transport_header = skb2->network_header;
2046                skb2->pkt_type = PACKET_OUTGOING;
2047                pt_prev = ptype;
2048        }
2049
2050        if (ptype_list == &ptype_all) {
2051                ptype_list = &dev->ptype_all;
2052                goto again;
2053        }
2054out_unlock:
2055        if (pt_prev) {
2056                if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2057                        pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2058                else
2059                        kfree_skb(skb2);
2060        }
2061        rcu_read_unlock();
2062}
2063EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2064
2065/**
2066 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2067 * @dev: Network device
2068 * @txq: number of queues available
2069 *
2070 * If real_num_tx_queues is changed the tc mappings may no longer be
2071 * valid. To resolve this verify the tc mapping remains valid and if
2072 * not NULL the mapping. With no priorities mapping to this
2073 * offset/count pair it will no longer be used. In the worst case TC0
2074 * is invalid nothing can be done so disable priority mappings. If is
2075 * expected that drivers will fix this mapping if they can before
2076 * calling netif_set_real_num_tx_queues.
2077 */
2078static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2079{
2080        int i;
2081        struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2082
2083        /* If TC0 is invalidated disable TC mapping */
2084        if (tc->offset + tc->count > txq) {
2085                pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2086                dev->num_tc = 0;
2087                return;
2088        }
2089
2090        /* Invalidated prio to tc mappings set to TC0 */
2091        for (i = 1; i < TC_BITMASK + 1; i++) {
2092                int q = netdev_get_prio_tc_map(dev, i);
2093
2094                tc = &dev->tc_to_txq[q];
2095                if (tc->offset + tc->count > txq) {
2096                        pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
2097                                i, q);
2098                        netdev_set_prio_tc_map(dev, i, 0);
2099                }
2100        }
2101}
2102
2103int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2104{
2105        if (dev->num_tc) {
2106                struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2107                int i;
2108
2109                /* walk through the TCs and see if it falls into any of them */
2110                for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2111                        if ((txq - tc->offset) < tc->count)
2112                                return i;
2113                }
2114
2115                /* didn't find it, just return -1 to indicate no match */
2116                return -1;
2117        }
2118
2119        return 0;
2120}
2121EXPORT_SYMBOL(netdev_txq_to_tc);
2122
2123#ifdef CONFIG_XPS
2124struct static_key xps_needed __read_mostly;
2125EXPORT_SYMBOL(xps_needed);
2126struct static_key xps_rxqs_needed __read_mostly;
2127EXPORT_SYMBOL(xps_rxqs_needed);
2128static DEFINE_MUTEX(xps_map_mutex);
2129#define xmap_dereference(P)             \
2130        rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2131
2132static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2133                             int tci, u16 index)
2134{
2135        struct xps_map *map = NULL;
2136        int pos;
2137
2138        if (dev_maps)
2139                map = xmap_dereference(dev_maps->attr_map[tci]);
2140        if (!map)
2141                return false;
2142
2143        for (pos = map->len; pos--;) {
2144                if (map->queues[pos] != index)
2145                        continue;
2146
2147                if (map->len > 1) {
2148                        map->queues[pos] = map->queues[--map->len];
2149                        break;
2150                }
2151
2152                RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2153                kfree_rcu(map, rcu);
2154                return false;
2155        }
2156
2157        return true;
2158}
2159
2160static bool remove_xps_queue_cpu(struct net_device *dev,
2161                                 struct xps_dev_maps *dev_maps,
2162                                 int cpu, u16 offset, u16 count)
2163{
2164        int num_tc = dev->num_tc ? : 1;
2165        bool active = false;
2166        int tci;
2167
2168        for (tci = cpu * num_tc; num_tc--; tci++) {
2169                int i, j;
2170
2171                for (i = count, j = offset; i--; j++) {
2172                        if (!remove_xps_queue(dev_maps, tci, j))
2173                                break;
2174                }
2175
2176                active |= i < 0;
2177        }
2178
2179        return active;
2180}
2181
2182static void reset_xps_maps(struct net_device *dev,
2183                           struct xps_dev_maps *dev_maps,
2184                           bool is_rxqs_map)
2185{
2186        if (is_rxqs_map) {
2187                static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2188                RCU_INIT_POINTER(dev->xps_rxqs_map, NULL);
2189        } else {
2190                RCU_INIT_POINTER(dev->xps_cpus_map, NULL);
2191        }
2192        static_key_slow_dec_cpuslocked(&xps_needed);
2193        kfree_rcu(dev_maps, rcu);
2194}
2195
2196static void clean_xps_maps(struct net_device *dev, const unsigned long *mask,
2197                           struct xps_dev_maps *dev_maps, unsigned int nr_ids,
2198                           u16 offset, u16 count, bool is_rxqs_map)
2199{
2200        bool active = false;
2201        int i, j;
2202
2203        for (j = -1; j = netif_attrmask_next(j, mask, nr_ids),
2204             j < nr_ids;)
2205                active |= remove_xps_queue_cpu(dev, dev_maps, j, offset,
2206                                               count);
2207        if (!active)
2208                reset_xps_maps(dev, dev_maps, is_rxqs_map);
2209
2210        if (!is_rxqs_map) {
2211                for (i = offset + (count - 1); count--; i--) {
2212                        netdev_queue_numa_node_write(
2213                                netdev_get_tx_queue(dev, i),
2214                                NUMA_NO_NODE);
2215                }
2216        }
2217}
2218
2219static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2220                                   u16 count)
2221{
2222        const unsigned long *possible_mask = NULL;
2223        struct xps_dev_maps *dev_maps;
2224        unsigned int nr_ids;
2225
2226        if (!static_key_false(&xps_needed))
2227                return;
2228
2229        cpus_read_lock();
2230        mutex_lock(&xps_map_mutex);
2231
2232        if (static_key_false(&xps_rxqs_needed)) {
2233                dev_maps = xmap_dereference(dev->xps_rxqs_map);
2234                if (dev_maps) {
2235                        nr_ids = dev->num_rx_queues;
2236                        clean_xps_maps(dev, possible_mask, dev_maps, nr_ids,
2237                                       offset, count, true);
2238                }
2239        }
2240
2241        dev_maps = xmap_dereference(dev->xps_cpus_map);
2242        if (!dev_maps)
2243                goto out_no_maps;
2244
2245        if (num_possible_cpus() > 1)
2246                possible_mask = cpumask_bits(cpu_possible_mask);
2247        nr_ids = nr_cpu_ids;
2248        clean_xps_maps(dev, possible_mask, dev_maps, nr_ids, offset, count,
2249                       false);
2250
2251out_no_maps:
2252        mutex_unlock(&xps_map_mutex);
2253        cpus_read_unlock();
2254}
2255
2256static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2257{
2258        netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2259}
2260
2261static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2262                                      u16 index, bool is_rxqs_map)
2263{
2264        struct xps_map *new_map;
2265        int alloc_len = XPS_MIN_MAP_ALLOC;
2266        int i, pos;
2267
2268        for (pos = 0; map && pos < map->len; pos++) {
2269                if (map->queues[pos] != index)
2270                        continue;
2271                return map;
2272        }
2273
2274        /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2275        if (map) {
2276                if (pos < map->alloc_len)
2277                        return map;
2278
2279                alloc_len = map->alloc_len * 2;
2280        }
2281
2282        /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2283         *  map
2284         */
2285        if (is_rxqs_map)
2286                new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2287        else
2288                new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2289                                       cpu_to_node(attr_index));
2290        if (!new_map)
2291                return NULL;
2292
2293        for (i = 0; i < pos; i++)
2294                new_map->queues[i] = map->queues[i];
2295        new_map->alloc_len = alloc_len;
2296        new_map->len = pos;
2297
2298        return new_map;
2299}
2300
2301/* Must be called under cpus_read_lock */
2302int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2303                          u16 index, bool is_rxqs_map)
2304{
2305        const unsigned long *online_mask = NULL, *possible_mask = NULL;
2306        struct xps_dev_maps *dev_maps, *new_dev_maps = NULL;
2307        int i, j, tci, numa_node_id = -2;
2308        int maps_sz, num_tc = 1, tc = 0;
2309        struct xps_map *map, *new_map;
2310        bool active = false;
2311        unsigned int nr_ids;
2312
2313        if (dev->num_tc) {
2314                /* Do not allow XPS on subordinate device directly */
2315                num_tc = dev->num_tc;
2316                if (num_tc < 0)
2317                        return -EINVAL;
2318
2319                /* If queue belongs to subordinate dev use its map */
2320                dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2321
2322                tc = netdev_txq_to_tc(dev, index);
2323                if (tc < 0)
2324                        return -EINVAL;
2325        }
2326
2327        mutex_lock(&xps_map_mutex);
2328        if (is_rxqs_map) {
2329                maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2330                dev_maps = xmap_dereference(dev->xps_rxqs_map);
2331                nr_ids = dev->num_rx_queues;
2332        } else {
2333                maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2334                if (num_possible_cpus() > 1) {
2335                        online_mask = cpumask_bits(cpu_online_mask);
2336                        possible_mask = cpumask_bits(cpu_possible_mask);
2337                }
2338                dev_maps = xmap_dereference(dev->xps_cpus_map);
2339                nr_ids = nr_cpu_ids;
2340        }
2341
2342        if (maps_sz < L1_CACHE_BYTES)
2343                maps_sz = L1_CACHE_BYTES;
2344
2345        /* allocate memory for queue storage */
2346        for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2347             j < nr_ids;) {
2348                if (!new_dev_maps)
2349                        new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2350                if (!new_dev_maps) {
2351                        mutex_unlock(&xps_map_mutex);
2352                        return -ENOMEM;
2353                }
2354
2355                tci = j * num_tc + tc;
2356                map = dev_maps ? xmap_dereference(dev_maps->attr_map[tci]) :
2357                                 NULL;
2358
2359                map = expand_xps_map(map, j, index, is_rxqs_map);
2360                if (!map)
2361                        goto error;
2362
2363                RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2364        }
2365
2366        if (!new_dev_maps)
2367                goto out_no_new_maps;
2368
2369        if (!dev_maps) {
2370                /* Increment static keys at most once per type */
2371                static_key_slow_inc_cpuslocked(&xps_needed);
2372                if (is_rxqs_map)
2373                        static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2374        }
2375
2376        for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2377             j < nr_ids;) {
2378                /* copy maps belonging to foreign traffic classes */
2379                for (i = tc, tci = j * num_tc; dev_maps && i--; tci++) {
2380                        /* fill in the new device map from the old device map */
2381                        map = xmap_dereference(dev_maps->attr_map[tci]);
2382                        RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2383                }
2384
2385                /* We need to explicitly update tci as prevous loop
2386                 * could break out early if dev_maps is NULL.
2387                 */
2388                tci = j * num_tc + tc;
2389
2390                if (netif_attr_test_mask(j, mask, nr_ids) &&
2391                    netif_attr_test_online(j, online_mask, nr_ids)) {
2392                        /* add tx-queue to CPU/rx-queue maps */
2393                        int pos = 0;
2394
2395                        map = xmap_dereference(new_dev_maps->attr_map[tci]);
2396                        while ((pos < map->len) && (map->queues[pos] != index))
2397                                pos++;
2398
2399                        if (pos == map->len)
2400                                map->queues[map->len++] = index;
2401#ifdef CONFIG_NUMA
2402                        if (!is_rxqs_map) {
2403                                if (numa_node_id == -2)
2404                                        numa_node_id = cpu_to_node(j);
2405                                else if (numa_node_id != cpu_to_node(j))
2406                                        numa_node_id = -1;
2407                        }
2408#endif
2409                } else if (dev_maps) {
2410                        /* fill in the new device map from the old device map */
2411                        map = xmap_dereference(dev_maps->attr_map[tci]);
2412                        RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2413                }
2414
2415                /* copy maps belonging to foreign traffic classes */
2416                for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
2417                        /* fill in the new device map from the old device map */
2418                        map = xmap_dereference(dev_maps->attr_map[tci]);
2419                        RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2420                }
2421        }
2422
2423        if (is_rxqs_map)
2424                rcu_assign_pointer(dev->xps_rxqs_map, new_dev_maps);
2425        else
2426                rcu_assign_pointer(dev->xps_cpus_map, new_dev_maps);
2427
2428        /* Cleanup old maps */
2429        if (!dev_maps)
2430                goto out_no_old_maps;
2431
2432        for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2433             j < nr_ids;) {
2434                for (i = num_tc, tci = j * num_tc; i--; tci++) {
2435                        new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2436                        map = xmap_dereference(dev_maps->attr_map[tci]);
2437                        if (map && map != new_map)
2438                                kfree_rcu(map, rcu);
2439                }
2440        }
2441
2442        kfree_rcu(dev_maps, rcu);
2443
2444out_no_old_maps:
2445        dev_maps = new_dev_maps;
2446        active = true;
2447
2448out_no_new_maps:
2449        if (!is_rxqs_map) {
2450                /* update Tx queue numa node */
2451                netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2452                                             (numa_node_id >= 0) ?
2453                                             numa_node_id : NUMA_NO_NODE);
2454        }
2455
2456        if (!dev_maps)
2457                goto out_no_maps;
2458
2459        /* removes tx-queue from unused CPUs/rx-queues */
2460        for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2461             j < nr_ids;) {
2462                for (i = tc, tci = j * num_tc; i--; tci++)
2463                        active |= remove_xps_queue(dev_maps, tci, index);
2464                if (!netif_attr_test_mask(j, mask, nr_ids) ||
2465                    !netif_attr_test_online(j, online_mask, nr_ids))
2466                        active |= remove_xps_queue(dev_maps, tci, index);
2467                for (i = num_tc - tc, tci++; --i; tci++)
2468                        active |= remove_xps_queue(dev_maps, tci, index);
2469        }
2470
2471        /* free map if not active */
2472        if (!active)
2473                reset_xps_maps(dev, dev_maps, is_rxqs_map);
2474
2475out_no_maps:
2476        mutex_unlock(&xps_map_mutex);
2477
2478        return 0;
2479error:
2480        /* remove any maps that we added */
2481        for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2482             j < nr_ids;) {
2483                for (i = num_tc, tci = j * num_tc; i--; tci++) {
2484                        new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2485                        map = dev_maps ?
2486                              xmap_dereference(dev_maps->attr_map[tci]) :
2487                              NULL;
2488                        if (new_map && new_map != map)
2489                                kfree(new_map);
2490                }
2491        }
2492
2493        mutex_unlock(&xps_map_mutex);
2494
2495        kfree(new_dev_maps);
2496        return -ENOMEM;
2497}
2498EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2499
2500int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2501                        u16 index)
2502{
2503        int ret;
2504
2505        cpus_read_lock();
2506        ret =  __netif_set_xps_queue(dev, cpumask_bits(mask), index, false);
2507        cpus_read_unlock();
2508
2509        return ret;
2510}
2511EXPORT_SYMBOL(netif_set_xps_queue);
2512
2513#endif
2514static void netdev_unbind_all_sb_channels(struct net_device *dev)
2515{
2516        struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2517
2518        /* Unbind any subordinate channels */
2519        while (txq-- != &dev->_tx[0]) {
2520                if (txq->sb_dev)
2521                        netdev_unbind_sb_channel(dev, txq->sb_dev);
2522        }
2523}
2524
2525void netdev_reset_tc(struct net_device *dev)
2526{
2527#ifdef CONFIG_XPS
2528        netif_reset_xps_queues_gt(dev, 0);
2529#endif
2530        netdev_unbind_all_sb_channels(dev);
2531
2532        /* Reset TC configuration of device */
2533        dev->num_tc = 0;
2534        memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2535        memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2536}
2537EXPORT_SYMBOL(netdev_reset_tc);
2538
2539int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2540{
2541        if (tc >= dev->num_tc)
2542                return -EINVAL;
2543
2544#ifdef CONFIG_XPS
2545        netif_reset_xps_queues(dev, offset, count);
2546#endif
2547        dev->tc_to_txq[tc].count = count;
2548        dev->tc_to_txq[tc].offset = offset;
2549        return 0;
2550}
2551EXPORT_SYMBOL(netdev_set_tc_queue);
2552
2553int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2554{
2555        if (num_tc > TC_MAX_QUEUE)
2556                return -EINVAL;
2557
2558#ifdef CONFIG_XPS
2559        netif_reset_xps_queues_gt(dev, 0);
2560#endif
2561        netdev_unbind_all_sb_channels(dev);
2562
2563        dev->num_tc = num_tc;
2564        return 0;
2565}
2566EXPORT_SYMBOL(netdev_set_num_tc);
2567
2568void netdev_unbind_sb_channel(struct net_device *dev,
2569                              struct net_device *sb_dev)
2570{
2571        struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2572
2573#ifdef CONFIG_XPS
2574        netif_reset_xps_queues_gt(sb_dev, 0);
2575#endif
2576        memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2577        memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2578
2579        while (txq-- != &dev->_tx[0]) {
2580                if (txq->sb_dev == sb_dev)
2581                        txq->sb_dev = NULL;
2582        }
2583}
2584EXPORT_SYMBOL(netdev_unbind_sb_channel);
2585
2586int netdev_bind_sb_channel_queue(struct net_device *dev,
2587                                 struct net_device *sb_dev,
2588                                 u8 tc, u16 count, u16 offset)
2589{
2590        /* Make certain the sb_dev and dev are already configured */
2591        if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2592                return -EINVAL;
2593
2594        /* We cannot hand out queues we don't have */
2595        if ((offset + count) > dev->real_num_tx_queues)
2596                return -EINVAL;
2597
2598        /* Record the mapping */
2599        sb_dev->tc_to_txq[tc].count = count;
2600        sb_dev->tc_to_txq[tc].offset = offset;
2601
2602        /* Provide a way for Tx queue to find the tc_to_txq map or
2603         * XPS map for itself.
2604         */
2605        while (count--)
2606                netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2607
2608        return 0;
2609}
2610EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2611
2612int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2613{
2614        /* Do not use a multiqueue device to represent a subordinate channel */
2615        if (netif_is_multiqueue(dev))
2616                return -ENODEV;
2617
2618        /* We allow channels 1 - 32767 to be used for subordinate channels.
2619         * Channel 0 is meant to be "native" mode and used only to represent
2620         * the main root device. We allow writing 0 to reset the device back
2621         * to normal mode after being used as a subordinate channel.
2622         */
2623        if (channel > S16_MAX)
2624                return -EINVAL;
2625
2626        dev->num_tc = -channel;
2627
2628        return 0;
2629}
2630EXPORT_SYMBOL(netdev_set_sb_channel);
2631
2632/*
2633 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2634 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2635 */
2636int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2637{
2638        bool disabling;
2639        int rc;
2640
2641        disabling = txq < dev->real_num_tx_queues;
2642
2643        if (txq < 1 || txq > dev->num_tx_queues)
2644                return -EINVAL;
2645
2646        if (dev->reg_state == NETREG_REGISTERED ||
2647            dev->reg_state == NETREG_UNREGISTERING) {
2648                ASSERT_RTNL();
2649
2650                rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2651                                                  txq);
2652                if (rc)
2653                        return rc;
2654
2655                if (dev->num_tc)
2656                        netif_setup_tc(dev, txq);
2657
2658                dev->real_num_tx_queues = txq;
2659
2660                if (disabling) {
2661                        synchronize_net();
2662                        qdisc_reset_all_tx_gt(dev, txq);
2663#ifdef CONFIG_XPS
2664                        netif_reset_xps_queues_gt(dev, txq);
2665#endif
2666                }
2667        } else {
2668                dev->real_num_tx_queues = txq;
2669        }
2670
2671        return 0;
2672}
2673EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2674
2675#ifdef CONFIG_SYSFS
2676/**
2677 *      netif_set_real_num_rx_queues - set actual number of RX queues used
2678 *      @dev: Network device
2679 *      @rxq: Actual number of RX queues
2680 *
2681 *      This must be called either with the rtnl_lock held or before
2682 *      registration of the net device.  Returns 0 on success, or a
2683 *      negative error code.  If called before registration, it always
2684 *      succeeds.
2685 */
2686int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2687{
2688        int rc;
2689
2690        if (rxq < 1 || rxq > dev->num_rx_queues)
2691                return -EINVAL;
2692
2693        if (dev->reg_state == NETREG_REGISTERED) {
2694                ASSERT_RTNL();
2695
2696                rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2697                                                  rxq);
2698                if (rc)
2699                        return rc;
2700        }
2701
2702        dev->real_num_rx_queues = rxq;
2703        return 0;
2704}
2705EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2706#endif
2707
2708/**
2709 * netif_get_num_default_rss_queues - default number of RSS queues
2710 *
2711 * This routine should set an upper limit on the number of RSS queues
2712 * used by default by multiqueue devices.
2713 */
2714int netif_get_num_default_rss_queues(void)
2715{
2716        return is_kdump_kernel() ?
2717                1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
2718}
2719EXPORT_SYMBOL(netif_get_num_default_rss_queues);
2720
2721static void __netif_reschedule(struct Qdisc *q)
2722{
2723        struct softnet_data *sd;
2724        unsigned long flags;
2725
2726        local_irq_save(flags);
2727        sd = this_cpu_ptr(&softnet_data);
2728        q->next_sched = NULL;
2729        *sd->output_queue_tailp = q;
2730        sd->output_queue_tailp = &q->next_sched;
2731        raise_softirq_irqoff(NET_TX_SOFTIRQ);
2732        local_irq_restore(flags);
2733}
2734
2735void __netif_schedule(struct Qdisc *q)
2736{
2737        if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
2738                __netif_reschedule(q);
2739}
2740EXPORT_SYMBOL(__netif_schedule);
2741
2742struct dev_kfree_skb_cb {
2743        enum skb_free_reason reason;
2744};
2745
2746static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
2747{
2748        return (struct dev_kfree_skb_cb *)skb->cb;
2749}
2750
2751void netif_schedule_queue(struct netdev_queue *txq)
2752{
2753        rcu_read_lock();
2754        if (!(txq->state & QUEUE_STATE_ANY_XOFF)) {
2755                struct Qdisc *q = rcu_dereference(txq->qdisc);
2756
2757                __netif_schedule(q);
2758        }
2759        rcu_read_unlock();
2760}
2761EXPORT_SYMBOL(netif_schedule_queue);
2762
2763void netif_tx_wake_queue(struct netdev_queue *dev_queue)
2764{
2765        if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
2766                struct Qdisc *q;
2767
2768                rcu_read_lock();
2769                q = rcu_dereference(dev_queue->qdisc);
2770                __netif_schedule(q);
2771                rcu_read_unlock();
2772        }
2773}
2774EXPORT_SYMBOL(netif_tx_wake_queue);
2775
2776void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
2777{
2778        unsigned long flags;
2779
2780        if (unlikely(!skb))
2781                return;
2782
2783        if (likely(refcount_read(&skb->users) == 1)) {
2784                smp_rmb();
2785                refcount_set(&skb->users, 0);
2786        } else if (likely(!refcount_dec_and_test(&skb->users))) {
2787                return;
2788        }
2789        get_kfree_skb_cb(skb)->reason = reason;
2790        local_irq_save(flags);
2791        skb->next = __this_cpu_read(softnet_data.completion_queue);
2792        __this_cpu_write(softnet_data.completion_queue, skb);
2793        raise_softirq_irqoff(NET_TX_SOFTIRQ);
2794        local_irq_restore(flags);
2795}
2796EXPORT_SYMBOL(__dev_kfree_skb_irq);
2797
2798void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
2799{
2800        if (in_irq() || irqs_disabled())
2801                __dev_kfree_skb_irq(skb, reason);
2802        else
2803                dev_kfree_skb(skb);
2804}
2805EXPORT_SYMBOL(__dev_kfree_skb_any);
2806
2807
2808/**
2809 * netif_device_detach - mark device as removed
2810 * @dev: network device
2811 *
2812 * Mark device as removed from system and therefore no longer available.
2813 */
2814void netif_device_detach(struct net_device *dev)
2815{
2816        if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
2817            netif_running(dev)) {
2818                netif_tx_stop_all_queues(dev);
2819        }
2820}
2821EXPORT_SYMBOL(netif_device_detach);
2822
2823/**
2824 * netif_device_attach - mark device as attached
2825 * @dev: network device
2826 *
2827 * Mark device as attached from system and restart if needed.
2828 */
2829void netif_device_attach(struct net_device *dev)
2830{
2831        if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
2832            netif_running(dev)) {
2833                netif_tx_wake_all_queues(dev);
2834                __netdev_watchdog_up(dev);
2835        }
2836}
2837EXPORT_SYMBOL(netif_device_attach);
2838
2839/*
2840 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
2841 * to be used as a distribution range.
2842 */
2843static u16 skb_tx_hash(const struct net_device *dev,
2844                       const struct net_device *sb_dev,
2845                       struct sk_buff *skb)
2846{
2847        u32 hash;
2848        u16 qoffset = 0;
2849        u16 qcount = dev->real_num_tx_queues;
2850
2851        if (dev->num_tc) {
2852                u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
2853
2854                qoffset = sb_dev->tc_to_txq[tc].offset;
2855                qcount = sb_dev->tc_to_txq[tc].count;
2856        }
2857
2858        if (skb_rx_queue_recorded(skb)) {
2859                hash = skb_get_rx_queue(skb);
2860                while (unlikely(hash >= qcount))
2861                        hash -= qcount;
2862                return hash + qoffset;
2863        }
2864
2865        return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
2866}
2867
2868static void skb_warn_bad_offload(const struct sk_buff *skb)
2869{
2870        static const netdev_features_t null_features;
2871        struct net_device *dev = skb->dev;
2872        const char *name = "";
2873
2874        if (!net_ratelimit())
2875                return;
2876
2877        if (dev) {
2878                if (dev->dev.parent)
2879                        name = dev_driver_string(dev->dev.parent);
2880                else
2881                        name = netdev_name(dev);
2882        }
2883        WARN(1, "%s: caps=(%pNF, %pNF) len=%d data_len=%d gso_size=%d "
2884             "gso_type=%d ip_summed=%d\n",
2885             name, dev ? &dev->features : &null_features,
2886             skb->sk ? &skb->sk->sk_route_caps : &null_features,
2887             skb->len, skb->data_len, skb_shinfo(skb)->gso_size,
2888             skb_shinfo(skb)->gso_type, skb->ip_summed);
2889}
2890
2891/*
2892 * Invalidate hardware checksum when packet is to be mangled, and
2893 * complete checksum manually on outgoing path.
2894 */
2895int skb_checksum_help(struct sk_buff *skb)
2896{
2897        __wsum csum;
2898        int ret = 0, offset;
2899
2900        if (skb->ip_summed == CHECKSUM_COMPLETE)
2901                goto out_set_summed;
2902
2903        if (unlikely(skb_shinfo(skb)->gso_size)) {
2904                skb_warn_bad_offload(skb);
2905                return -EINVAL;
2906        }
2907
2908        /* Before computing a checksum, we should make sure no frag could
2909         * be modified by an external entity : checksum could be wrong.
2910         */
2911        if (skb_has_shared_frag(skb)) {
2912                ret = __skb_linearize(skb);
2913                if (ret)
2914                        goto out;
2915        }
2916
2917        offset = skb_checksum_start_offset(skb);
2918        BUG_ON(offset >= skb_headlen(skb));
2919        csum = skb_checksum(skb, offset, skb->len - offset, 0);
2920
2921        offset += skb->csum_offset;
2922        BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
2923
2924        if (skb_cloned(skb) &&
2925            !skb_clone_writable(skb, offset + sizeof(__sum16))) {
2926                ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
2927                if (ret)
2928                        goto out;
2929        }
2930
2931        *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
2932out_set_summed:
2933        skb->ip_summed = CHECKSUM_NONE;
2934out:
2935        return ret;
2936}
2937EXPORT_SYMBOL(skb_checksum_help);
2938
2939int skb_crc32c_csum_help(struct sk_buff *skb)
2940{
2941        __le32 crc32c_csum;
2942        int ret = 0, offset, start;
2943
2944        if (skb->ip_summed != CHECKSUM_PARTIAL)
2945                goto out;
2946
2947        if (unlikely(skb_is_gso(skb)))
2948                goto out;
2949
2950        /* Before computing a checksum, we should make sure no frag could
2951         * be modified by an external entity : checksum could be wrong.
2952         */
2953        if (unlikely(skb_has_shared_frag(skb))) {
2954                ret = __skb_linearize(skb);
2955                if (ret)
2956                        goto out;
2957        }
2958        start = skb_checksum_start_offset(skb);
2959        offset = start + offsetof(struct sctphdr, checksum);
2960        if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
2961                ret = -EINVAL;
2962                goto out;
2963        }
2964        if (skb_cloned(skb) &&
2965            !skb_clone_writable(skb, offset + sizeof(__le32))) {
2966                ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
2967                if (ret)
2968                        goto out;
2969        }
2970        crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
2971                                                  skb->len - start, ~(__u32)0,
2972                                                  crc32c_csum_stub));
2973        *(__le32 *)(skb->data + offset) = crc32c_csum;
2974        skb->ip_summed = CHECKSUM_NONE;
2975        skb->csum_not_inet = 0;
2976out:
2977        return ret;
2978}
2979
2980__be16 skb_network_protocol(struct sk_buff *skb, int *depth)
2981{
2982        __be16 type = skb->protocol;
2983
2984        /* Tunnel gso handlers can set protocol to ethernet. */
2985        if (type == htons(ETH_P_TEB)) {
2986                struct ethhdr *eth;
2987
2988                if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
2989                        return 0;
2990
2991                eth = (struct ethhdr *)skb->data;
2992                type = eth->h_proto;
2993        }
2994
2995        return __vlan_get_protocol(skb, type, depth);
2996}
2997
2998/**
2999 *      skb_mac_gso_segment - mac layer segmentation handler.
3000 *      @skb: buffer to segment
3001 *      @features: features for the output path (see dev->features)
3002 */
3003struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
3004                                    netdev_features_t features)
3005{
3006        struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
3007        struct packet_offload *ptype;
3008        int vlan_depth = skb->mac_len;
3009        __be16 type = skb_network_protocol(skb, &vlan_depth);
3010
3011        if (unlikely(!type))
3012                return ERR_PTR(-EINVAL);
3013
3014        __skb_pull(skb, vlan_depth);
3015
3016        rcu_read_lock();
3017        list_for_each_entry_rcu(ptype, &offload_base, list) {
3018                if (ptype->type == type && ptype->callbacks.gso_segment) {
3019                        segs = ptype->callbacks.gso_segment(skb, features);
3020                        break;
3021                }
3022        }
3023        rcu_read_unlock();
3024
3025        __skb_push(skb, skb->data - skb_mac_header(skb));
3026
3027        return segs;
3028}
3029EXPORT_SYMBOL(skb_mac_gso_segment);
3030
3031
3032/* openvswitch calls this on rx path, so we need a different check.
3033 */
3034static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
3035{
3036        if (tx_path)
3037                return skb->ip_summed != CHECKSUM_PARTIAL &&
3038                       skb->ip_summed != CHECKSUM_UNNECESSARY;
3039
3040        return skb->ip_summed == CHECKSUM_NONE;
3041}
3042
3043/**
3044 *      __skb_gso_segment - Perform segmentation on skb.
3045 *      @skb: buffer to segment
3046 *      @features: features for the output path (see dev->features)
3047 *      @tx_path: whether it is called in TX path
3048 *
3049 *      This function segments the given skb and returns a list of segments.
3050 *
3051 *      It may return NULL if the skb requires no segmentation.  This is
3052 *      only possible when GSO is used for verifying header integrity.
3053 *
3054 *      Segmentation preserves SKB_SGO_CB_OFFSET bytes of previous skb cb.
3055 */
3056struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
3057                                  netdev_features_t features, bool tx_path)
3058{
3059        struct sk_buff *segs;
3060
3061        if (unlikely(skb_needs_check(skb, tx_path))) {
3062                int err;
3063
3064                /* We're going to init ->check field in TCP or UDP header */
3065                err = skb_cow_head(skb, 0);
3066                if (err < 0)
3067                        return ERR_PTR(err);
3068        }
3069
3070        /* Only report GSO partial support if it will enable us to
3071         * support segmentation on this frame without needing additional
3072         * work.
3073         */
3074        if (features & NETIF_F_GSO_PARTIAL) {
3075                netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
3076                struct net_device *dev = skb->dev;
3077
3078                partial_features |= dev->features & dev->gso_partial_features;
3079                if (!skb_gso_ok(skb, features | partial_features))
3080                        features &= ~NETIF_F_GSO_PARTIAL;
3081        }
3082
3083        BUILD_BUG_ON(SKB_SGO_CB_OFFSET +
3084                     sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
3085
3086        SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
3087        SKB_GSO_CB(skb)->encap_level = 0;
3088
3089        skb_reset_mac_header(skb);
3090        skb_reset_mac_len(skb);
3091
3092        segs = skb_mac_gso_segment(skb, features);
3093
3094        if (unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
3095                skb_warn_bad_offload(skb);
3096
3097        return segs;
3098}
3099EXPORT_SYMBOL(__skb_gso_segment);
3100
3101/* Take action when hardware reception checksum errors are detected. */
3102#ifdef CONFIG_BUG
3103void netdev_rx_csum_fault(struct net_device *dev)
3104{
3105        if (net_ratelimit()) {
3106                pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
3107                dump_stack();
3108        }
3109}
3110EXPORT_SYMBOL(netdev_rx_csum_fault);
3111#endif
3112
3113/* XXX: check that highmem exists at all on the given machine. */
3114static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3115{
3116#ifdef CONFIG_HIGHMEM
3117        int i;
3118
3119        if (!(dev->features & NETIF_F_HIGHDMA)) {
3120                for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3121                        skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3122
3123                        if (PageHighMem(skb_frag_page(frag)))
3124                                return 1;
3125                }
3126        }
3127#endif
3128        return 0;
3129}
3130
3131/* If MPLS offload request, verify we are testing hardware MPLS features
3132 * instead of standard features for the netdev.
3133 */
3134#if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3135static netdev_features_t net_mpls_features(struct sk_buff *skb,
3136                                           netdev_features_t features,
3137                                           __be16 type)
3138{
3139        if (eth_p_mpls(type))
3140                features &= skb->dev->mpls_features;
3141
3142        return features;
3143}
3144#else
3145static netdev_features_t net_mpls_features(struct sk_buff *skb,
3146                                           netdev_features_t features,
3147                                           __be16 type)
3148{
3149        return features;
3150}
3151#endif
3152
3153static netdev_features_t harmonize_features(struct sk_buff *skb,
3154        netdev_features_t features)
3155{
3156        int tmp;
3157        __be16 type;
3158
3159        type = skb_network_protocol(skb, &tmp);
3160        features = net_mpls_features(skb, features, type);
3161
3162        if (skb->ip_summed != CHECKSUM_NONE &&
3163            !can_checksum_protocol(features, type)) {
3164                features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3165        }
3166        if (illegal_highdma(skb->dev, skb))
3167                features &= ~NETIF_F_SG;
3168
3169        return features;
3170}
3171
3172netdev_features_t passthru_features_check(struct sk_buff *skb,
3173                                          struct net_device *dev,
3174                                          netdev_features_t features)
3175{
3176        return features;
3177}
3178EXPORT_SYMBOL(passthru_features_check);
3179
3180static netdev_features_t dflt_features_check(struct sk_buff *skb,
3181                                             struct net_device *dev,
3182                                             netdev_features_t features)
3183{
3184        return vlan_features_check(skb, features);
3185}
3186
3187static netdev_features_t gso_features_check(const struct sk_buff *skb,
3188                                            struct net_device *dev,
3189                                            netdev_features_t features)
3190{
3191        u16 gso_segs = skb_shinfo(skb)->gso_segs;
3192
3193        if (gso_segs > dev->gso_max_segs)
3194                return features & ~NETIF_F_GSO_MASK;
3195
3196        /* Support for GSO partial features requires software
3197         * intervention before we can actually process the packets
3198         * so we need to strip support for any partial features now
3199         * and we can pull them back in after we have partially
3200         * segmented the frame.
3201         */
3202        if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3203                features &= ~dev->gso_partial_features;
3204
3205        /* Make sure to clear the IPv4 ID mangling feature if the
3206         * IPv4 header has the potential to be fragmented.
3207         */
3208        if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3209                struct iphdr *iph = skb->encapsulation ?
3210                                    inner_ip_hdr(skb) : ip_hdr(skb);
3211
3212                if (!(iph->frag_off & htons(IP_DF)))
3213                        features &= ~NETIF_F_TSO_MANGLEID;
3214        }
3215
3216        return features;
3217}
3218
3219netdev_features_t netif_skb_features(struct sk_buff *skb)
3220{
3221        struct net_device *dev = skb->dev;
3222        netdev_features_t features = dev->features;
3223
3224        if (skb_is_gso(skb))
3225                features = gso_features_check(skb, dev, features);
3226
3227        /* If encapsulation offload request, verify we are testing
3228         * hardware encapsulation features instead of standard
3229         * features for the netdev
3230         */
3231        if (skb->encapsulation)
3232                features &= dev->hw_enc_features;
3233
3234        if (skb_vlan_tagged(skb))
3235                features = netdev_intersect_features(features,
3236                                                     dev->vlan_features |
3237                                                     NETIF_F_HW_VLAN_CTAG_TX |
3238                                                     NETIF_F_HW_VLAN_STAG_TX);
3239
3240        if (dev->netdev_ops->ndo_features_check)
3241                features &= dev->netdev_ops->ndo_features_check(skb, dev,
3242                                                                features);
3243        else
3244                features &= dflt_features_check(skb, dev, features);
3245
3246        return harmonize_features(skb, features);
3247}
3248EXPORT_SYMBOL(netif_skb_features);
3249
3250static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3251                    struct netdev_queue *txq, bool more)
3252{
3253        unsigned int len;
3254        int rc;
3255
3256        if (!list_empty(&ptype_all) || !list_empty(&dev->ptype_all))
3257                dev_queue_xmit_nit(skb, dev);
3258
3259        len = skb->len;
3260        trace_net_dev_start_xmit(skb, dev);
3261        rc = netdev_start_xmit(skb, dev, txq, more);
3262        trace_net_dev_xmit(skb, rc, dev, len);
3263
3264        return rc;
3265}
3266
3267struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3268                                    struct netdev_queue *txq, int *ret)
3269{
3270        struct sk_buff *skb = first;
3271        int rc = NETDEV_TX_OK;
3272
3273        while (skb) {
3274                struct sk_buff *next = skb->next;
3275
3276                skb->next = NULL;
3277                rc = xmit_one(skb, dev, txq, next != NULL);
3278                if (unlikely(!dev_xmit_complete(rc))) {
3279                        skb->next = next;
3280                        goto out;
3281                }
3282
3283                skb = next;
3284                if (netif_tx_queue_stopped(txq) && skb) {
3285                        rc = NETDEV_TX_BUSY;
3286                        break;
3287                }
3288        }
3289
3290out:
3291        *ret = rc;
3292        return skb;
3293}
3294
3295static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3296                                          netdev_features_t features)
3297{
3298        if (skb_vlan_tag_present(skb) &&
3299            !vlan_hw_offload_capable(features, skb->vlan_proto))
3300                skb = __vlan_hwaccel_push_inside(skb);
3301        return skb;
3302}
3303
3304int skb_csum_hwoffload_help(struct sk_buff *skb,
3305                            const netdev_features_t features)
3306{
3307        if (unlikely(skb->csum_not_inet))
3308                return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3309                        skb_crc32c_csum_help(skb);
3310
3311        return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
3312}
3313EXPORT_SYMBOL(skb_csum_hwoffload_help);
3314
3315static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3316{
3317        netdev_features_t features;
3318
3319        features = netif_skb_features(skb);
3320        skb = validate_xmit_vlan(skb, features);
3321        if (unlikely(!skb))
3322                goto out_null;
3323
3324        skb = sk_validate_xmit_skb(skb, dev);
3325        if (unlikely(!skb))
3326                goto out_null;
3327
3328        if (netif_needs_gso(skb, features)) {
3329                struct sk_buff *segs;
3330
3331                segs = skb_gso_segment(skb, features);
3332                if (IS_ERR(segs)) {
3333                        goto out_kfree_skb;
3334                } else if (segs) {
3335                        consume_skb(skb);
3336                        skb = segs;
3337                }
3338        } else {
3339                if (skb_needs_linearize(skb, features) &&
3340                    __skb_linearize(skb))
3341                        goto out_kfree_skb;
3342
3343                /* If packet is not checksummed and device does not
3344                 * support checksumming for this protocol, complete
3345                 * checksumming here.
3346                 */
3347                if (skb->ip_summed == CHECKSUM_PARTIAL) {
3348                        if (skb->encapsulation)
3349                                skb_set_inner_transport_header(skb,
3350                                                               skb_checksum_start_offset(skb));
3351                        else
3352                                skb_set_transport_header(skb,
3353                                                         skb_checksum_start_offset(skb));
3354                        if (skb_csum_hwoffload_help(skb, features))
3355                                goto out_kfree_skb;
3356                }
3357        }
3358
3359        skb = validate_xmit_xfrm(skb, features, again);
3360
3361        return skb;
3362
3363out_kfree_skb:
3364        kfree_skb(skb);
3365out_null:
3366        atomic_long_inc(&dev->tx_dropped);
3367        return NULL;
3368}
3369
3370struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3371{
3372        struct sk_buff *next, *head = NULL, *tail;
3373
3374        for (; skb != NULL; skb = next) {
3375                next = skb->next;
3376                skb->next = NULL;
3377
3378                /* in case skb wont be segmented, point to itself */
3379                skb->prev = skb;
3380
3381                skb = validate_xmit_skb(skb, dev, again);
3382                if (!skb)
3383                        continue;
3384
3385                if (!head)
3386                        head = skb;
3387                else
3388                        tail->next = skb;
3389                /* If skb was segmented, skb->prev points to
3390                 * the last segment. If not, it still contains skb.
3391                 */
3392                tail = skb->prev;
3393        }
3394        return head;
3395}
3396EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3397
3398static void qdisc_pkt_len_init(struct sk_buff *skb)
3399{
3400        const struct skb_shared_info *shinfo = skb_shinfo(skb);
3401
3402        qdisc_skb_cb(skb)->pkt_len = skb->len;
3403
3404        /* To get more precise estimation of bytes sent on wire,
3405         * we add to pkt_len the headers size of all segments
3406         */
3407        if (shinfo->gso_size)  {
3408                unsigned int hdr_len;
3409                u16 gso_segs = shinfo->gso_segs;
3410
3411                /* mac layer + network layer */
3412                hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3413
3414                /* + transport layer */
3415                if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3416                        const struct tcphdr *th;
3417                        struct tcphdr _tcphdr;
3418
3419                        th = skb_header_pointer(skb, skb_transport_offset(skb),
3420                                                sizeof(_tcphdr), &_tcphdr);
3421                        if (likely(th))
3422                                hdr_len += __tcp_hdrlen(th);
3423                } else {
3424                        struct udphdr _udphdr;
3425
3426                        if (skb_header_pointer(skb, skb_transport_offset(skb),
3427                                               sizeof(_udphdr), &_udphdr))
3428                                hdr_len += sizeof(struct udphdr);
3429                }
3430
3431                if (shinfo->gso_type & SKB_GSO_DODGY)
3432                        gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3433                                                shinfo->gso_size);
3434
3435                qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3436        }
3437}
3438
3439static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3440                                 struct net_device *dev,
3441                                 struct netdev_queue *txq)
3442{
3443        spinlock_t *root_lock = qdisc_lock(q);
3444        struct sk_buff *to_free = NULL;
3445        bool contended;
3446        int rc;
3447
3448        qdisc_calculate_pkt_len(skb, q);
3449
3450        if (q->flags & TCQ_F_NOLOCK) {
3451                if ((q->flags & TCQ_F_CAN_BYPASS) && READ_ONCE(q->empty) &&
3452                    qdisc_run_begin(q)) {
3453                        if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
3454                                              &q->state))) {
3455                                __qdisc_drop(skb, &to_free);
3456                                rc = NET_XMIT_DROP;
3457                                goto end_run;
3458                        }
3459                        qdisc_bstats_cpu_update(q, skb);
3460
3461                        rc = NET_XMIT_SUCCESS;
3462                        if (sch_direct_xmit(skb, q, dev, txq, NULL, true))
3463                                __qdisc_run(q);
3464
3465end_run:
3466                        qdisc_run_end(q);
3467                } else {
3468                        rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3469                        qdisc_run(q);
3470                }
3471
3472                if (unlikely(to_free))
3473                        kfree_skb_list(to_free);
3474                return rc;
3475        }
3476
3477        /*
3478         * Heuristic to force contended enqueues to serialize on a
3479         * separate lock before trying to get qdisc main lock.
3480         * This permits qdisc->running owner to get the lock more
3481         * often and dequeue packets faster.
3482         */
3483        contended = qdisc_is_running(q);
3484        if (unlikely(contended))
3485                spin_lock(&q->busylock);
3486
3487        spin_lock(root_lock);
3488        if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3489                __qdisc_drop(skb, &to_free);
3490                rc = NET_XMIT_DROP;
3491        } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3492                   qdisc_run_begin(q)) {
3493                /*
3494                 * This is a work-conserving queue; there are no old skbs
3495                 * waiting to be sent out; and the qdisc is not running -
3496                 * xmit the skb directly.
3497                 */
3498
3499                qdisc_bstats_update(q, skb);
3500
3501                if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3502                        if (unlikely(contended)) {
3503                                spin_unlock(&q->busylock);
3504                                contended = false;
3505                        }
3506                        __qdisc_run(q);
3507                }
3508
3509                qdisc_run_end(q);
3510                rc = NET_XMIT_SUCCESS;
3511        } else {
3512                rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3513                if (qdisc_run_begin(q)) {
3514                        if (unlikely(contended)) {
3515                                spin_unlock(&q->busylock);
3516                                contended = false;
3517                        }
3518                        __qdisc_run(q);
3519                        qdisc_run_end(q);
3520                }
3521        }
3522        spin_unlock(root_lock);
3523        if (unlikely(to_free))
3524                kfree_skb_list(to_free);
3525        if (unlikely(contended))
3526                spin_unlock(&q->busylock);
3527        return rc;
3528}
3529
3530#if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3531static void skb_update_prio(struct sk_buff *skb)
3532{
3533        const struct netprio_map *map;
3534        const struct sock *sk;
3535        unsigned int prioidx;
3536
3537        if (skb->priority)
3538                return;
3539        map = rcu_dereference_bh(skb->dev->priomap);
3540        if (!map)
3541                return;
3542        sk = skb_to_full_sk(skb);
3543        if (!sk)
3544                return;
3545
3546        prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3547
3548        if (prioidx < map->priomap_len)
3549                skb->priority = map->priomap[prioidx];
3550}
3551#else
3552#define skb_update_prio(skb)
3553#endif
3554
3555/**
3556 *      dev_loopback_xmit - loop back @skb
3557 *      @net: network namespace this loopback is happening in
3558 *      @sk:  sk needed to be a netfilter okfn
3559 *      @skb: buffer to transmit
3560 */
3561int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3562{
3563        skb_reset_mac_header(skb);
3564        __skb_pull(skb, skb_network_offset(skb));
3565        skb->pkt_type = PACKET_LOOPBACK;
3566        skb->ip_summed = CHECKSUM_UNNECESSARY;
3567        WARN_ON(!skb_dst(skb));
3568        skb_dst_force(skb);
3569        netif_rx_ni(skb);
3570        return 0;
3571}
3572EXPORT_SYMBOL(dev_loopback_xmit);
3573
3574#ifdef CONFIG_NET_EGRESS
3575static struct sk_buff *
3576sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3577{
3578        struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3579        struct tcf_result cl_res;
3580
3581        if (!miniq)
3582                return skb;
3583
3584        /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3585        mini_qdisc_bstats_cpu_update(miniq, skb);
3586
3587        switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
3588        case TC_ACT_OK:
3589        case TC_ACT_RECLASSIFY:
3590                skb->tc_index = TC_H_MIN(cl_res.classid);
3591                break;
3592        case TC_ACT_SHOT:
3593                mini_qdisc_qstats_cpu_drop(miniq);
3594                *ret = NET_XMIT_DROP;
3595                kfree_skb(skb);
3596                return NULL;
3597        case TC_ACT_STOLEN:
3598        case TC_ACT_QUEUED:
3599        case TC_ACT_TRAP:
3600                *ret = NET_XMIT_SUCCESS;
3601                consume_skb(skb);
3602                return NULL;
3603        case TC_ACT_REDIRECT:
3604                /* No need to push/pop skb's mac_header here on egress! */
3605                skb_do_redirect(skb);
3606                *ret = NET_XMIT_SUCCESS;
3607                return NULL;
3608        default:
3609                break;
3610        }
3611
3612        return skb;
3613}
3614#endif /* CONFIG_NET_EGRESS */
3615
3616#ifdef CONFIG_XPS
3617static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3618                               struct xps_dev_maps *dev_maps, unsigned int tci)
3619{
3620        struct xps_map *map;
3621        int queue_index = -1;
3622
3623        if (dev->num_tc) {
3624                tci *= dev->num_tc;
3625                tci += netdev_get_prio_tc_map(dev, skb->priority);
3626        }
3627
3628        map = rcu_dereference(dev_maps->attr_map[tci]);
3629        if (map) {
3630                if (map->len == 1)
3631                        queue_index = map->queues[0];
3632                else
3633                        queue_index = map->queues[reciprocal_scale(
3634                                                skb_get_hash(skb), map->len)];
3635                if (unlikely(queue_index >= dev->real_num_tx_queues))
3636                        queue_index = -1;
3637        }
3638        return queue_index;
3639}
3640#endif
3641
3642static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3643                         struct sk_buff *skb)
3644{
3645#ifdef CONFIG_XPS
3646        struct xps_dev_maps *dev_maps;
3647        struct sock *sk = skb->sk;
3648        int queue_index = -1;
3649
3650        if (!static_key_false(&xps_needed))
3651                return -1;
3652
3653        rcu_read_lock();
3654        if (!static_key_false(&xps_rxqs_needed))
3655                goto get_cpus_map;
3656
3657        dev_maps = rcu_dereference(sb_dev->xps_rxqs_map);
3658        if (dev_maps) {
3659                int tci = sk_rx_queue_get(sk);
3660
3661                if (tci >= 0 && tci < dev->num_rx_queues)
3662                        queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3663                                                          tci);
3664        }
3665
3666get_cpus_map:
3667        if (queue_index < 0) {
3668                dev_maps = rcu_dereference(sb_dev->xps_cpus_map);
3669                if (dev_maps) {
3670                        unsigned int tci = skb->sender_cpu - 1;
3671
3672                        queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3673                                                          tci);
3674                }
3675        }
3676        rcu_read_unlock();
3677
3678        return queue_index;
3679#else
3680        return -1;
3681#endif
3682}
3683
3684u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3685                     struct net_device *sb_dev,
3686                     select_queue_fallback_t fallback)
3687{
3688        return 0;
3689}
3690EXPORT_SYMBOL(dev_pick_tx_zero);
3691
3692u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
3693                       struct net_device *sb_dev,
3694                       select_queue_fallback_t fallback)
3695{
3696        return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
3697}
3698EXPORT_SYMBOL(dev_pick_tx_cpu_id);
3699
3700static u16 __netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
3701                            struct net_device *sb_dev)
3702{
3703        struct sock *sk = skb->sk;
3704        int queue_index = sk_tx_queue_get(sk);
3705
3706        sb_dev = sb_dev ? : dev;
3707
3708        if (queue_index < 0 || skb->ooo_okay ||
3709            queue_index >= dev->real_num_tx_queues) {
3710                int new_index = get_xps_queue(dev, sb_dev, skb);
3711
3712                if (new_index < 0)
3713                        new_index = skb_tx_hash(dev, sb_dev, skb);
3714
3715                if (queue_index != new_index && sk &&
3716                    sk_fullsock(sk) &&
3717                    rcu_access_pointer(sk->sk_dst_cache))
3718                        sk_tx_queue_set(sk, new_index);
3719
3720                queue_index = new_index;
3721        }
3722
3723        return queue_index;
3724}
3725
3726struct netdev_queue *netdev_pick_tx(struct net_device *dev,
3727                                    struct sk_buff *skb,
3728                                    struct net_device *sb_dev)
3729{
3730        int queue_index = 0;
3731
3732#ifdef CONFIG_XPS
3733        u32 sender_cpu = skb->sender_cpu - 1;
3734
3735        if (sender_cpu >= (u32)NR_CPUS)
3736                skb->sender_cpu = raw_smp_processor_id() + 1;
3737#endif
3738
3739        if (dev->real_num_tx_queues != 1) {
3740                const struct net_device_ops *ops = dev->netdev_ops;
3741
3742                if (ops->ndo_select_queue)
3743                        queue_index = ops->ndo_select_queue(dev, skb, sb_dev,
3744                                                            __netdev_pick_tx);
3745                else
3746                        queue_index = __netdev_pick_tx(dev, skb, sb_dev);
3747
3748                queue_index = netdev_cap_txqueue(dev, queue_index);
3749        }
3750
3751        skb_set_queue_mapping(skb, queue_index);
3752        return netdev_get_tx_queue(dev, queue_index);
3753}
3754
3755/**
3756 *      __dev_queue_xmit - transmit a buffer
3757 *      @skb: buffer to transmit
3758 *      @sb_dev: suboordinate device used for L2 forwarding offload
3759 *
3760 *      Queue a buffer for transmission to a network device. The caller must
3761 *      have set the device and priority and built the buffer before calling
3762 *      this function. The function can be called from an interrupt.
3763 *
3764 *      A negative errno code is returned on a failure. A success does not
3765 *      guarantee the frame will be transmitted as it may be dropped due
3766 *      to congestion or traffic shaping.
3767 *
3768 * -----------------------------------------------------------------------------------
3769 *      I notice this method can also return errors from the queue disciplines,
3770 *      including NET_XMIT_DROP, which is a positive value.  So, errors can also
3771 *      be positive.
3772 *
3773 *      Regardless of the return value, the skb is consumed, so it is currently
3774 *      difficult to retry a send to this method.  (You can bump the ref count
3775 *      before sending to hold a reference for retry if you are careful.)
3776 *
3777 *      When calling this method, interrupts MUST be enabled.  This is because
3778 *      the BH enable code must have IRQs enabled so that it will not deadlock.
3779 *          --BLG
3780 */
3781static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
3782{
3783        struct net_device *dev = skb->dev;
3784        struct netdev_queue *txq;
3785        struct Qdisc *q;
3786        int rc = -ENOMEM;
3787        bool again = false;
3788
3789        skb_reset_mac_header(skb);
3790
3791        if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
3792                __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
3793
3794        /* Disable soft irqs for various locks below. Also
3795         * stops preemption for RCU.
3796         */
3797        rcu_read_lock_bh();
3798
3799        skb_update_prio(skb);
3800
3801        qdisc_pkt_len_init(skb);
3802#ifdef CONFIG_NET_CLS_ACT
3803        skb->tc_at_ingress = 0;
3804# ifdef CONFIG_NET_EGRESS
3805        if (static_branch_unlikely(&egress_needed_key)) {
3806                skb = sch_handle_egress(skb, &rc, dev);
3807                if (!skb)
3808                        goto out;
3809        }
3810# endif
3811#endif
3812        /* If device/qdisc don't need skb->dst, release it right now while
3813         * its hot in this cpu cache.
3814         */
3815        if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
3816                skb_dst_drop(skb);
3817        else
3818                skb_dst_force(skb);
3819
3820        txq = netdev_pick_tx(dev, skb, sb_dev);
3821        q = rcu_dereference_bh(txq->qdisc);
3822
3823        trace_net_dev_queue(skb);
3824        if (q->enqueue) {
3825                rc = __dev_xmit_skb(skb, q, dev, txq);
3826                goto out;
3827        }
3828
3829        /* The device has no queue. Common case for software devices:
3830         * loopback, all the sorts of tunnels...
3831
3832         * Really, it is unlikely that netif_tx_lock protection is necessary
3833         * here.  (f.e. loopback and IP tunnels are clean ignoring statistics
3834         * counters.)
3835         * However, it is possible, that they rely on protection
3836         * made by us here.
3837
3838         * Check this and shot the lock. It is not prone from deadlocks.
3839         *Either shot noqueue qdisc, it is even simpler 8)
3840         */
3841        if (dev->flags & IFF_UP) {
3842                int cpu = smp_processor_id(); /* ok because BHs are off */
3843
3844                if (txq->xmit_lock_owner != cpu) {
3845                        if (dev_xmit_recursion())
3846                                goto recursion_alert;
3847
3848                        skb = validate_xmit_skb(skb, dev, &again);
3849                        if (!skb)
3850                                goto out;
3851
3852                        HARD_TX_LOCK(dev, txq, cpu);
3853
3854                        if (!netif_xmit_stopped(txq)) {
3855                                dev_xmit_recursion_inc();
3856                                skb = dev_hard_start_xmit(skb, dev, txq, &rc);
3857                                dev_xmit_recursion_dec();
3858                                if (dev_xmit_complete(rc)) {
3859                                        HARD_TX_UNLOCK(dev, txq);
3860                                        goto out;
3861                                }
3862                        }
3863                        HARD_TX_UNLOCK(dev, txq);
3864                        net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
3865                                             dev->name);
3866                } else {
3867                        /* Recursion is detected! It is possible,
3868                         * unfortunately
3869                         */
3870recursion_alert:
3871                        net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
3872                                             dev->name);
3873                }
3874        }
3875
3876        rc = -ENETDOWN;
3877        rcu_read_unlock_bh();
3878
3879        atomic_long_inc(&dev->tx_dropped);
3880        kfree_skb_list(skb);
3881        return rc;
3882out:
3883        rcu_read_unlock_bh();
3884        return rc;
3885}
3886
3887int dev_queue_xmit(struct sk_buff *skb)
3888{
3889        return __dev_queue_xmit(skb, NULL);
3890}
3891EXPORT_SYMBOL(dev_queue_xmit);
3892
3893int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
3894{
3895        return __dev_queue_xmit(skb, sb_dev);
3896}
3897EXPORT_SYMBOL(dev_queue_xmit_accel);
3898
3899int dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
3900{
3901        struct net_device *dev = skb->dev;
3902        struct sk_buff *orig_skb = skb;
3903        struct netdev_queue *txq;
3904        int ret = NETDEV_TX_BUSY;
3905        bool again = false;
3906
3907        if (unlikely(!netif_running(dev) ||
3908                     !netif_carrier_ok(dev)))
3909                goto drop;
3910
3911        skb = validate_xmit_skb_list(skb, dev, &again);
3912        if (skb != orig_skb)
3913                goto drop;
3914
3915        skb_set_queue_mapping(skb, queue_id);
3916        txq = skb_get_tx_queue(dev, skb);
3917
3918        local_bh_disable();
3919
3920        HARD_TX_LOCK(dev, txq, smp_processor_id());
3921        if (!netif_xmit_frozen_or_drv_stopped(txq))
3922                ret = netdev_start_xmit(skb, dev, txq, false);
3923        HARD_TX_UNLOCK(dev, txq);
3924
3925        local_bh_enable();
3926
3927        if (!dev_xmit_complete(ret))
3928                kfree_skb(skb);
3929
3930        return ret;
3931drop:
3932        atomic_long_inc(&dev->tx_dropped);
3933        kfree_skb_list(skb);
3934        return NET_XMIT_DROP;
3935}
3936EXPORT_SYMBOL(dev_direct_xmit);
3937
3938/*************************************************************************
3939 *                      Receiver routines
3940 *************************************************************************/
3941
3942int netdev_max_backlog __read_mostly = 1000;
3943EXPORT_SYMBOL(netdev_max_backlog);
3944
3945int netdev_tstamp_prequeue __read_mostly = 1;
3946int netdev_budget __read_mostly = 300;
3947unsigned int __read_mostly netdev_budget_usecs = 2000;
3948int weight_p __read_mostly = 64;           /* old backlog weight */
3949int dev_weight_rx_bias __read_mostly = 1;  /* bias for backlog weight */
3950int dev_weight_tx_bias __read_mostly = 1;  /* bias for output_queue quota */
3951int dev_rx_weight __read_mostly = 64;
3952int dev_tx_weight __read_mostly = 64;
3953
3954/* Called with irq disabled */
3955static inline void ____napi_schedule(struct softnet_data *sd,
3956                                     struct napi_struct *napi)
3957{
3958        list_add_tail(&napi->poll_list, &sd->poll_list);
3959        __raise_softirq_irqoff(NET_RX_SOFTIRQ);
3960}
3961
3962#ifdef CONFIG_RPS
3963
3964/* One global table that all flow-based protocols share. */
3965struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
3966EXPORT_SYMBOL(rps_sock_flow_table);
3967u32 rps_cpu_mask __read_mostly;
3968EXPORT_SYMBOL(rps_cpu_mask);
3969
3970struct static_key_false rps_needed __read_mostly;
3971EXPORT_SYMBOL(rps_needed);
3972struct static_key_false rfs_needed __read_mostly;
3973EXPORT_SYMBOL(rfs_needed);
3974
3975static struct rps_dev_flow *
3976set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
3977            struct rps_dev_flow *rflow, u16 next_cpu)
3978{
3979        if (next_cpu < nr_cpu_ids) {
3980#ifdef CONFIG_RFS_ACCEL
3981                struct netdev_rx_queue *rxqueue;
3982                struct rps_dev_flow_table *flow_table;
3983                struct rps_dev_flow *old_rflow;
3984                u32 flow_id;
3985                u16 rxq_index;
3986                int rc;
3987
3988                /* Should we steer this flow to a different hardware queue? */
3989                if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
3990                    !(dev->features & NETIF_F_NTUPLE))
3991                        goto out;
3992                rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
3993                if (rxq_index == skb_get_rx_queue(skb))
3994                        goto out;
3995
3996                rxqueue = dev->_rx + rxq_index;
3997                flow_table = rcu_dereference(rxqueue->rps_flow_table);
3998                if (!flow_table)
3999                        goto out;
4000                flow_id = skb_get_hash(skb) & flow_table->mask;
4001                rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4002                                                        rxq_index, flow_id);
4003                if (rc < 0)
4004                        goto out;
4005                old_rflow = rflow;
4006                rflow = &flow_table->flows[flow_id];
4007                rflow->filter = rc;
4008                if (old_rflow->filter == rflow->filter)
4009                        old_rflow->filter = RPS_NO_FILTER;
4010        out:
4011#endif
4012                rflow->last_qtail =
4013                        per_cpu(softnet_data, next_cpu).input_queue_head;
4014        }
4015
4016        rflow->cpu = next_cpu;
4017        return rflow;
4018}
4019
4020/*
4021 * get_rps_cpu is called from netif_receive_skb and returns the target
4022 * CPU from the RPS map of the receiving queue for a given skb.
4023 * rcu_read_lock must be held on entry.
4024 */
4025static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4026                       struct rps_dev_flow **rflowp)
4027{
4028        const struct rps_sock_flow_table *sock_flow_table;
4029        struct netdev_rx_queue *rxqueue = dev->_rx;
4030        struct rps_dev_flow_table *flow_table;
4031        struct rps_map *map;
4032        int cpu = -1;
4033        u32 tcpu;
4034        u32 hash;
4035
4036        if (skb_rx_queue_recorded(skb)) {
4037                u16 index = skb_get_rx_queue(skb);
4038
4039                if (unlikely(index >= dev->real_num_rx_queues)) {
4040                        WARN_ONCE(dev->real_num_rx_queues > 1,
4041                                  "%s received packet on queue %u, but number "
4042                                  "of RX queues is %u\n",
4043                                  dev->name, index, dev->real_num_rx_queues);
4044                        goto done;
4045                }
4046                rxqueue += index;
4047        }
4048
4049        /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4050
4051        flow_table = rcu_dereference(rxqueue->rps_flow_table);
4052        map = rcu_dereference(rxqueue->rps_map);
4053        if (!flow_table && !map)
4054                goto done;
4055
4056        skb_reset_network_header(skb);
4057        hash = skb_get_hash(skb);
4058        if (!hash)
4059                goto done;
4060
4061        sock_flow_table = rcu_dereference(rps_sock_flow_table);
4062        if (flow_table && sock_flow_table) {
4063                struct rps_dev_flow *rflow;
4064                u32 next_cpu;
4065                u32 ident;
4066
4067                /* First check into global flow table if there is a match */
4068                ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4069                if ((ident ^ hash) & ~rps_cpu_mask)
4070                        goto try_rps;
4071
4072                next_cpu = ident & rps_cpu_mask;
4073
4074                /* OK, now we know there is a match,
4075                 * we can look at the local (per receive queue) flow table
4076                 */
4077                rflow = &flow_table->flows[hash & flow_table->mask];
4078                tcpu = rflow->cpu;
4079
4080                /*
4081                 * If the desired CPU (where last recvmsg was done) is
4082                 * different from current CPU (one in the rx-queue flow
4083                 * table entry), switch if one of the following holds:
4084                 *   - Current CPU is unset (>= nr_cpu_ids).
4085                 *   - Current CPU is offline.
4086                 *   - The current CPU's queue tail has advanced beyond the
4087                 *     last packet that was enqueued using this table entry.
4088                 *     This guarantees that all previous packets for the flow
4089                 *     have been dequeued, thus preserving in order delivery.
4090                 */
4091                if (unlikely(tcpu != next_cpu) &&
4092                    (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4093                     ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4094                      rflow->last_qtail)) >= 0)) {
4095                        tcpu = next_cpu;
4096                        rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4097                }
4098
4099                if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4100                        *rflowp = rflow;
4101                        cpu = tcpu;
4102                        goto done;
4103                }
4104        }
4105
4106try_rps:
4107
4108        if (map) {
4109                tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4110                if (cpu_online(tcpu)) {
4111                        cpu = tcpu;
4112                        goto done;
4113                }
4114        }
4115
4116done:
4117        return cpu;
4118}
4119
4120#ifdef CONFIG_RFS_ACCEL
4121
4122/**
4123 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4124 * @dev: Device on which the filter was set
4125 * @rxq_index: RX queue index
4126 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4127 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4128 *
4129 * Drivers that implement ndo_rx_flow_steer() should periodically call
4130 * this function for each installed filter and remove the filters for
4131 * which it returns %true.
4132 */
4133bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4134                         u32 flow_id, u16 filter_id)
4135{
4136        struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4137        struct rps_dev_flow_table *flow_table;
4138        struct rps_dev_flow *rflow;
4139        bool expire = true;
4140        unsigned int cpu;
4141
4142        rcu_read_lock();
4143        flow_table = rcu_dereference(rxqueue->rps_flow_table);
4144        if (flow_table && flow_id <= flow_table->mask) {
4145                rflow = &flow_table->flows[flow_id];
4146                cpu = READ_ONCE(rflow->cpu);
4147                if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4148                    ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4149                           rflow->last_qtail) <
4150                     (int)(10 * flow_table->mask)))
4151                        expire = false;
4152        }
4153        rcu_read_unlock();
4154        return expire;
4155}
4156EXPORT_SYMBOL(rps_may_expire_flow);
4157
4158#endif /* CONFIG_RFS_ACCEL */
4159
4160/* Called from hardirq (IPI) context */
4161static void rps_trigger_softirq(void *data)
4162{
4163        struct softnet_data *sd = data;
4164
4165        ____napi_schedule(sd, &sd->backlog);
4166        sd->received_rps++;
4167}
4168
4169#endif /* CONFIG_RPS */
4170
4171/*
4172 * Check if this softnet_data structure is another cpu one
4173 * If yes, queue it to our IPI list and return 1
4174 * If no, return 0
4175 */
4176static int rps_ipi_queued(struct softnet_data *sd)
4177{
4178#ifdef CONFIG_RPS
4179        struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4180
4181        if (sd != mysd) {
4182                sd->rps_ipi_next = mysd->rps_ipi_list;
4183                mysd->rps_ipi_list = sd;
4184
4185                __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4186                return 1;
4187        }
4188#endif /* CONFIG_RPS */
4189        return 0;
4190}
4191
4192#ifdef CONFIG_NET_FLOW_LIMIT
4193int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4194#endif
4195
4196static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4197{
4198#ifdef CONFIG_NET_FLOW_LIMIT
4199        struct sd_flow_limit *fl;
4200        struct softnet_data *sd;
4201        unsigned int old_flow, new_flow;
4202
4203        if (qlen < (netdev_max_backlog >> 1))
4204                return false;
4205
4206        sd = this_cpu_ptr(&softnet_data);
4207
4208        rcu_read_lock();
4209        fl = rcu_dereference(sd->flow_limit);
4210        if (fl) {
4211                new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4212                old_flow = fl->history[fl->history_head];
4213                fl->history[fl->history_head] = new_flow;
4214
4215                fl->history_head++;
4216                fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4217
4218                if (likely(fl->buckets[old_flow]))
4219                        fl->buckets[old_flow]--;
4220
4221                if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4222                        fl->count++;
4223                        rcu_read_unlock();
4224                        return true;
4225                }
4226        }
4227        rcu_read_unlock();
4228#endif
4229        return false;
4230}
4231
4232/*
4233 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4234 * queue (may be a remote CPU queue).
4235 */
4236static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4237                              unsigned int *qtail)
4238{
4239        struct softnet_data *sd;
4240        unsigned long flags;
4241        unsigned int qlen;
4242
4243        sd = &per_cpu(softnet_data, cpu);
4244
4245        local_irq_save(flags);
4246
4247        rps_lock(sd);
4248        if (!netif_running(skb->dev))
4249                goto drop;
4250        qlen = skb_queue_len(&sd->input_pkt_queue);
4251        if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
4252                if (qlen) {
4253enqueue:
4254                        __skb_queue_tail(&sd->input_pkt_queue, skb);
4255                        input_queue_tail_incr_save(sd, qtail);
4256                        rps_unlock(sd);
4257                        local_irq_restore(flags);
4258                        return NET_RX_SUCCESS;
4259                }
4260
4261                /* Schedule NAPI for backlog device
4262                 * We can use non atomic operation since we own the queue lock
4263                 */
4264                if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
4265                        if (!rps_ipi_queued(sd))
4266                                ____napi_schedule(sd, &sd->backlog);
4267                }
4268                goto enqueue;
4269        }
4270
4271drop:
4272        sd->dropped++;
4273        rps_unlock(sd);
4274
4275        local_irq_restore(flags);
4276
4277        atomic_long_inc(&skb->dev->rx_dropped);
4278        kfree_skb(skb);
4279        return NET_RX_DROP;
4280}
4281
4282static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4283{
4284        struct net_device *dev = skb->dev;
4285        struct netdev_rx_queue *rxqueue;
4286
4287        rxqueue = dev->_rx;
4288
4289        if (skb_rx_queue_recorded(skb)) {
4290                u16 index = skb_get_rx_queue(skb);
4291
4292                if (unlikely(index >= dev->real_num_rx_queues)) {
4293                        WARN_ONCE(dev->real_num_rx_queues > 1,
4294                                  "%s received packet on queue %u, but number "
4295                                  "of RX queues is %u\n",
4296                                  dev->name, index, dev->real_num_rx_queues);
4297
4298                        return rxqueue; /* Return first rxqueue */
4299                }
4300                rxqueue += index;
4301        }
4302        return rxqueue;
4303}
4304
4305static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4306                                     struct xdp_buff *xdp,
4307                                     struct bpf_prog *xdp_prog)
4308{
4309        struct netdev_rx_queue *rxqueue;
4310        void *orig_data, *orig_data_end;
4311        u32 metalen, act = XDP_DROP;
4312        __be16 orig_eth_type;
4313        struct ethhdr *eth;
4314        bool orig_bcast;
4315        int hlen, off;
4316        u32 mac_len;
4317
4318        /* Reinjected packets coming from act_mirred or similar should
4319         * not get XDP generic processing.
4320         */
4321        if (skb_is_tc_redirected(skb))
4322                return XDP_PASS;
4323
4324        /* XDP packets must be linear and must have sufficient headroom
4325         * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4326         * native XDP provides, thus we need to do it here as well.
4327         */
4328        if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4329            skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4330                int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4331                int troom = skb->tail + skb->data_len - skb->end;
4332
4333                /* In case we have to go down the path and also linearize,
4334                 * then lets do the pskb_expand_head() work just once here.
4335                 */
4336                if (pskb_expand_head(skb,
4337                                     hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4338                                     troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4339                        goto do_drop;
4340                if (skb_linearize(skb))
4341                        goto do_drop;
4342        }
4343
4344        /* The XDP program wants to see the packet starting at the MAC
4345         * header.
4346         */
4347        mac_len = skb->data - skb_mac_header(skb);
4348        hlen = skb_headlen(skb) + mac_len;
4349        xdp->data = skb->data - mac_len;
4350        xdp->data_meta = xdp->data;
4351        xdp->data_end = xdp->data + hlen;
4352        xdp->data_hard_start = skb->data - skb_headroom(skb);
4353        orig_data_end = xdp->data_end;
4354        orig_data = xdp->data;
4355        eth = (struct ethhdr *)xdp->data;
4356        orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4357        orig_eth_type = eth->h_proto;
4358
4359        rxqueue = netif_get_rxqueue(skb);
4360        xdp->rxq = &rxqueue->xdp_rxq;
4361
4362        act = bpf_prog_run_xdp(xdp_prog, xdp);
4363
4364        /* check if bpf_xdp_adjust_head was used */
4365        off = xdp->data - orig_data;
4366        if (off) {
4367                if (off > 0)
4368                        __skb_pull(skb, off);
4369                else if (off < 0)
4370                        __skb_push(skb, -off);
4371
4372                skb->mac_header += off;
4373                skb_reset_network_header(skb);
4374        }
4375
4376        /* check if bpf_xdp_adjust_tail was used. it can only "shrink"
4377         * pckt.
4378         */
4379        off = orig_data_end - xdp->data_end;
4380        if (off != 0) {
4381                skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4382                skb->len -= off;
4383
4384        }
4385
4386        /* check if XDP changed eth hdr such SKB needs update */
4387        eth = (struct ethhdr *)xdp->data;
4388        if ((orig_eth_type != eth->h_proto) ||
4389            (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4390                __skb_push(skb, ETH_HLEN);
4391                skb->protocol = eth_type_trans(skb, skb->dev);
4392        }
4393
4394        switch (act) {
4395        case XDP_REDIRECT:
4396        case XDP_TX:
4397                __skb_push(skb, mac_len);
4398                break;
4399        case XDP_PASS:
4400                metalen = xdp->data - xdp->data_meta;
4401                if (metalen)
4402                        skb_metadata_set(skb, metalen);
4403                break;
4404        default:
4405                bpf_warn_invalid_xdp_action(act);
4406                /* fall through */
4407        case XDP_ABORTED:
4408                trace_xdp_exception(skb->dev, xdp_prog, act);
4409                /* fall through */
4410        case XDP_DROP:
4411        do_drop:
4412                kfree_skb(skb);
4413                break;
4414        }
4415
4416        return act;
4417}
4418
4419/* When doing generic XDP we have to bypass the qdisc layer and the
4420 * network taps in order to match in-driver-XDP behavior.
4421 */
4422void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4423{
4424        struct net_device *dev = skb->dev;
4425        struct netdev_queue *txq;
4426        bool free_skb = true;
4427        int cpu, rc;
4428
4429        txq = netdev_pick_tx(dev, skb, NULL);
4430        cpu = smp_processor_id();
4431        HARD_TX_LOCK(dev, txq, cpu);
4432        if (!netif_xmit_stopped(txq)) {
4433                rc = netdev_start_xmit(skb, dev, txq, 0);
4434                if (dev_xmit_complete(rc))
4435                        free_skb = false;
4436        }
4437        HARD_TX_UNLOCK(dev, txq);
4438        if (free_skb) {
4439                trace_xdp_exception(dev, xdp_prog, XDP_TX);
4440                kfree_skb(skb);
4441        }
4442}
4443EXPORT_SYMBOL_GPL(generic_xdp_tx);
4444
4445static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4446
4447int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4448{
4449        if (xdp_prog) {
4450                struct xdp_buff xdp;
4451                u32 act;
4452                int err;
4453
4454                act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4455                if (act != XDP_PASS) {
4456                        switch (act) {
4457                        case XDP_REDIRECT:
4458                                err = xdp_do_generic_redirect(skb->dev, skb,
4459                                                              &xdp, xdp_prog);
4460                                if (err)
4461                                        goto out_redir;
4462                                break;
4463                        case XDP_TX:
4464                                generic_xdp_tx(skb, xdp_prog);
4465                                break;
4466                        }
4467                        return XDP_DROP;
4468                }
4469        }
4470        return XDP_PASS;
4471out_redir:
4472        kfree_skb(skb);
4473        return XDP_DROP;
4474}
4475EXPORT_SYMBOL_GPL(do_xdp_generic);
4476
4477static int netif_rx_internal(struct sk_buff *skb)
4478{
4479        int ret;
4480
4481        net_timestamp_check(netdev_tstamp_prequeue, skb);
4482
4483        trace_netif_rx(skb);
4484
4485#ifdef CONFIG_RPS
4486        if (static_branch_unlikely(&rps_needed)) {
4487                struct rps_dev_flow voidflow, *rflow = &voidflow;
4488                int cpu;
4489
4490                preempt_disable();
4491                rcu_read_lock();
4492
4493                cpu = get_rps_cpu(skb->dev, skb, &rflow);
4494                if (cpu < 0)
4495                        cpu = smp_processor_id();
4496
4497                ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4498
4499                rcu_read_unlock();
4500                preempt_enable();
4501        } else
4502#endif
4503        {
4504                unsigned int qtail;
4505
4506                ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
4507                put_cpu();
4508        }
4509        return ret;
4510}
4511
4512/**
4513 *      netif_rx        -       post buffer to the network code
4514 *      @skb: buffer to post
4515 *
4516 *      This function receives a packet from a device driver and queues it for
4517 *      the upper (protocol) levels to process.  It always succeeds. The buffer
4518 *      may be dropped during processing for congestion control or by the
4519 *      protocol layers.
4520 *
4521 *      return values:
4522 *      NET_RX_SUCCESS  (no congestion)
4523 *      NET_RX_DROP     (packet was dropped)
4524 *
4525 */
4526
4527int netif_rx(struct sk_buff *skb)
4528{
4529        trace_netif_rx_entry(skb);
4530
4531        return netif_rx_internal(skb);
4532}
4533EXPORT_SYMBOL(netif_rx);
4534
4535int netif_rx_ni(struct sk_buff *skb)
4536{
4537        int err;
4538
4539        trace_netif_rx_ni_entry(skb);
4540
4541        preempt_disable();
4542        err = netif_rx_internal(skb);
4543        if (local_softirq_pending())
4544                do_softirq();
4545        preempt_enable();
4546
4547        return err;
4548}
4549EXPORT_SYMBOL(netif_rx_ni);
4550
4551static __latent_entropy void net_tx_action(struct softirq_action *h)
4552{
4553        struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4554
4555        if (sd->completion_queue) {
4556                struct sk_buff *clist;
4557
4558                local_irq_disable();
4559                clist = sd->completion_queue;
4560                sd->completion_queue = NULL;
4561                local_irq_enable();
4562
4563                while (clist) {
4564                        struct sk_buff *skb = clist;
4565
4566                        clist = clist->next;
4567
4568                        WARN_ON(refcount_read(&skb->users));
4569                        if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4570                                trace_consume_skb(skb);
4571                        else
4572                                trace_kfree_skb(skb, net_tx_action);
4573
4574                        if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4575                                __kfree_skb(skb);
4576                        else
4577                                __kfree_skb_defer(skb);
4578                }
4579
4580                __kfree_skb_flush();
4581        }
4582
4583        if (sd->output_queue) {
4584                struct Qdisc *head;
4585
4586                local_irq_disable();
4587                head = sd->output_queue;
4588                sd->output_queue = NULL;
4589                sd->output_queue_tailp = &sd->output_queue;
4590                local_irq_enable();
4591
4592                while (head) {
4593                        struct Qdisc *q = head;
4594                        spinlock_t *root_lock = NULL;
4595
4596                        head = head->next_sched;
4597
4598                        if (!(q->flags & TCQ_F_NOLOCK)) {
4599                                root_lock = qdisc_lock(q);
4600                                spin_lock(root_lock);
4601                        }
4602                        /* We need to make sure head->next_sched is read
4603                         * before clearing __QDISC_STATE_SCHED
4604                         */
4605                        smp_mb__before_atomic();
4606                        clear_bit(__QDISC_STATE_SCHED, &q->state);
4607                        qdisc_run(q);
4608                        if (root_lock)
4609                                spin_unlock(root_lock);
4610                }
4611        }
4612
4613        xfrm_dev_backlog(sd);
4614}
4615
4616#if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
4617/* This hook is defined here for ATM LANE */
4618int (*br_fdb_test_addr_hook)(struct net_device *dev,
4619                             unsigned char *addr) __read_mostly;
4620EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
4621#endif
4622
4623static inline struct sk_buff *
4624sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4625                   struct net_device *orig_dev)
4626{
4627#ifdef CONFIG_NET_CLS_ACT
4628        struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
4629        struct tcf_result cl_res;
4630
4631        /* If there's at least one ingress present somewhere (so
4632         * we get here via enabled static key), remaining devices
4633         * that are not configured with an ingress qdisc will bail
4634         * out here.
4635         */
4636        if (!miniq)
4637                return skb;
4638
4639        if (*pt_prev) {
4640                *ret = deliver_skb(skb, *pt_prev, orig_dev);
4641                *pt_prev = NULL;
4642        }
4643
4644        qdisc_skb_cb(skb)->pkt_len = skb->len;
4645        skb->tc_at_ingress = 1;
4646        mini_qdisc_bstats_cpu_update(miniq, skb);
4647
4648        switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
4649        case TC_ACT_OK:
4650        case TC_ACT_RECLASSIFY:
4651                skb->tc_index = TC_H_MIN(cl_res.classid);
4652                break;
4653        case TC_ACT_SHOT:
4654                mini_qdisc_qstats_cpu_drop(miniq);
4655                kfree_skb(skb);
4656                return NULL;
4657        case TC_ACT_STOLEN:
4658        case TC_ACT_QUEUED:
4659        case TC_ACT_TRAP:
4660                consume_skb(skb);
4661                return NULL;
4662        case TC_ACT_REDIRECT:
4663                /* skb_mac_header check was done by cls/act_bpf, so
4664                 * we can safely push the L2 header back before
4665                 * redirecting to another netdev
4666                 */
4667                __skb_push(skb, skb->mac_len);
4668                skb_do_redirect(skb);
4669                return NULL;
4670        case TC_ACT_CONSUMED:
4671                return NULL;
4672        default:
4673                break;
4674        }
4675#endif /* CONFIG_NET_CLS_ACT */
4676        return skb;
4677}
4678
4679/**
4680 *      netdev_is_rx_handler_busy - check if receive handler is registered
4681 *      @dev: device to check
4682 *
4683 *      Check if a receive handler is already registered for a given device.
4684 *      Return true if there one.
4685 *
4686 *      The caller must hold the rtnl_mutex.
4687 */
4688bool netdev_is_rx_handler_busy(struct net_device *dev)
4689{
4690        ASSERT_RTNL();
4691        return dev && rtnl_dereference(dev->rx_handler);
4692}
4693EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
4694
4695/**
4696 *      netdev_rx_handler_register - register receive handler
4697 *      @dev: device to register a handler for
4698 *      @rx_handler: receive handler to register
4699 *      @rx_handler_data: data pointer that is used by rx handler
4700 *
4701 *      Register a receive handler for a device. This handler will then be
4702 *      called from __netif_receive_skb. A negative errno code is returned
4703 *      on a failure.
4704 *
4705 *      The caller must hold the rtnl_mutex.
4706 *
4707 *      For a general description of rx_handler, see enum rx_handler_result.
4708 */
4709int netdev_rx_handler_register(struct net_device *dev,
4710                               rx_handler_func_t *rx_handler,
4711                               void *rx_handler_data)
4712{
4713        if (netdev_is_rx_handler_busy(dev))
4714                return -EBUSY;
4715
4716        if (dev->priv_flags & IFF_NO_RX_HANDLER)
4717                return -EINVAL;
4718
4719        /* Note: rx_handler_data must be set before rx_handler */
4720        rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
4721        rcu_assign_pointer(dev->rx_handler, rx_handler);
4722
4723        return 0;
4724}
4725EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
4726
4727/**
4728 *      netdev_rx_handler_unregister - unregister receive handler
4729 *      @dev: device to unregister a handler from
4730 *
4731 *      Unregister a receive handler from a device.
4732 *
4733 *      The caller must hold the rtnl_mutex.
4734 */
4735void netdev_rx_handler_unregister(struct net_device *dev)
4736{
4737
4738        ASSERT_RTNL();
4739        RCU_INIT_POINTER(dev->rx_handler, NULL);
4740        /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
4741         * section has a guarantee to see a non NULL rx_handler_data
4742         * as well.
4743         */
4744        synchronize_net();
4745        RCU_INIT_POINTER(dev->rx_handler_data, NULL);
4746}
4747EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
4748
4749/*
4750 * Limit the use of PFMEMALLOC reserves to those protocols that implement
4751 * the special handling of PFMEMALLOC skbs.
4752 */
4753static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
4754{
4755        switch (skb->protocol) {
4756        case htons(ETH_P_ARP):
4757        case htons(ETH_P_IP):
4758        case htons(ETH_P_IPV6):
4759        case htons(ETH_P_8021Q):
4760        case htons(ETH_P_8021AD):
4761                return true;
4762        default:
4763                return false;
4764        }
4765}
4766
4767static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
4768                             int *ret, struct net_device *orig_dev)
4769{
4770#ifdef CONFIG_NETFILTER_INGRESS
4771        if (nf_hook_ingress_active(skb)) {
4772                int ingress_retval;
4773
4774                if (*pt_prev) {
4775                        *ret = deliver_skb(skb, *pt_prev, orig_dev);
4776                        *pt_prev = NULL;
4777                }
4778
4779                rcu_read_lock();
4780                ingress_retval = nf_hook_ingress(skb);
4781                rcu_read_unlock();
4782                return ingress_retval;
4783        }
4784#endif /* CONFIG_NETFILTER_INGRESS */
4785        return 0;
4786}
4787
4788static int __netif_receive_skb_core(struct sk_buff *skb, bool pfmemalloc)
4789{
4790        struct packet_type *ptype, *pt_prev;
4791        rx_handler_func_t *rx_handler;
4792        struct net_device *orig_dev;
4793        bool deliver_exact = false;
4794        int ret = NET_RX_DROP;
4795        __be16 type;
4796
4797        net_timestamp_check(!netdev_tstamp_prequeue, skb);
4798
4799        trace_netif_receive_skb(skb);
4800
4801        orig_dev = skb->dev;
4802
4803        skb_reset_network_header(skb);
4804        if (!skb_transport_header_was_set(skb))
4805                skb_reset_transport_header(skb);
4806        skb_reset_mac_len(skb);
4807
4808        pt_prev = NULL;
4809
4810another_round:
4811        skb->skb_iif = skb->dev->ifindex;
4812
4813        __this_cpu_inc(softnet_data.processed);
4814
4815        if (static_branch_unlikely(&generic_xdp_needed_key)) {
4816                int ret2;
4817
4818                preempt_disable();
4819                ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
4820                preempt_enable();
4821
4822                if (ret2 != XDP_PASS)
4823                        return NET_RX_DROP;
4824                skb_reset_mac_len(skb);
4825        }
4826
4827        if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
4828            skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
4829                skb = skb_vlan_untag(skb);
4830                if (unlikely(!skb))
4831                        goto out;
4832        }
4833
4834        if (skb_skip_tc_classify(skb))
4835                goto skip_classify;
4836
4837        if (pfmemalloc)
4838                goto skip_taps;
4839
4840        list_for_each_entry_rcu(ptype, &ptype_all, list) {
4841                if (pt_prev)
4842                        ret = deliver_skb(skb, pt_prev, orig_dev);
4843                pt_prev = ptype;
4844        }
4845
4846        list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
4847                if (pt_prev)
4848                        ret = deliver_skb(skb, pt_prev, orig_dev);
4849                pt_prev = ptype;
4850        }
4851
4852skip_taps:
4853#ifdef CONFIG_NET_INGRESS
4854        if (static_branch_unlikely(&ingress_needed_key)) {
4855                skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev);
4856                if (!skb)
4857                        goto out;
4858
4859                if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
4860                        goto out;
4861        }
4862#endif
4863        skb_reset_tc(skb);
4864skip_classify:
4865        if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
4866                goto drop;
4867
4868        if (skb_vlan_tag_present(skb)) {
4869                if (pt_prev) {
4870                        ret = deliver_skb(skb, pt_prev, orig_dev);
4871                        pt_prev = NULL;
4872                }
4873                if (vlan_do_receive(&skb))
4874                        goto another_round;
4875                else if (unlikely(!skb))
4876                        goto out;
4877        }
4878
4879        rx_handler = rcu_dereference(skb->dev->rx_handler);
4880        if (rx_handler) {
4881                if (pt_prev) {
4882                        ret = deliver_skb(skb, pt_prev, orig_dev);
4883                        pt_prev = NULL;
4884                }
4885                switch (rx_handler(&skb)) {
4886                case RX_HANDLER_CONSUMED:
4887                        ret = NET_RX_SUCCESS;
4888                        goto out;
4889                case RX_HANDLER_ANOTHER:
4890                        goto another_round;
4891                case RX_HANDLER_EXACT:
4892                        deliver_exact = true;
4893                case RX_HANDLER_PASS:
4894                        break;
4895                default:
4896                        BUG();
4897                }
4898        }
4899
4900        if (unlikely(skb_vlan_tag_present(skb))) {
4901                if (skb_vlan_tag_get_id(skb))
4902                        skb->pkt_type = PACKET_OTHERHOST;
4903                /* Note: we might in the future use prio bits
4904                 * and set skb->priority like in vlan_do_receive()
4905                 * For the time being, just ignore Priority Code Point
4906                 */
4907                __vlan_hwaccel_clear_tag(skb);
4908        }
4909
4910        type = skb->protocol;
4911
4912        /* deliver only exact match when indicated */
4913        if (likely(!deliver_exact)) {
4914                deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
4915                                       &ptype_base[ntohs(type) &
4916                                                   PTYPE_HASH_MASK]);
4917        }
4918
4919        deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
4920                               &orig_dev->ptype_specific);
4921
4922        if (unlikely(skb->dev != orig_dev)) {
4923                deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
4924                                       &skb->dev->ptype_specific);
4925        }
4926
4927        if (pt_prev) {
4928                if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
4929                        goto drop;
4930                else
4931                        ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv,
4932                                                 ip_rcv, skb, skb->dev, pt_prev,
4933                                                 orig_dev);
4934        } else {
4935drop:
4936                if (!deliver_exact)
4937                        atomic_long_inc(&skb->dev->rx_dropped);
4938                else
4939                        atomic_long_inc(&skb->dev->rx_nohandler);
4940                kfree_skb(skb);
4941                /* Jamal, now you will not able to escape explaining
4942                 * me how you were going to use this. :-)
4943                 */
4944                ret = NET_RX_DROP;
4945        }
4946
4947out:
4948        return ret;
4949}
4950
4951/**
4952 *      netif_receive_skb_core - special purpose version of netif_receive_skb
4953 *      @skb: buffer to process
4954 *
4955 *      More direct receive version of netif_receive_skb().  It should
4956 *      only be used by callers that have a need to skip RPS and Generic XDP.
4957 *      Caller must also take care of handling if (page_is_)pfmemalloc.
4958 *
4959 *      This function may only be called from softirq context and interrupts
4960 *      should be enabled.
4961 *
4962 *      Return values (usually ignored):
4963 *      NET_RX_SUCCESS: no congestion
4964 *      NET_RX_DROP: packet was dropped
4965 */
4966int netif_receive_skb_core(struct sk_buff *skb)
4967{
4968        int ret;
4969
4970        rcu_read_lock();
4971        ret = __netif_receive_skb_core(skb, false);
4972        rcu_read_unlock();
4973
4974        return ret;
4975}
4976EXPORT_SYMBOL(netif_receive_skb_core);
4977
4978static int __netif_receive_skb(struct sk_buff *skb)
4979{
4980        int ret;
4981
4982        if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
4983                unsigned int noreclaim_flag;
4984
4985                /*
4986                 * PFMEMALLOC skbs are special, they should
4987                 * - be delivered to SOCK_MEMALLOC sockets only
4988                 * - stay away from userspace
4989                 * - have bounded memory usage
4990                 *
4991                 * Use PF_MEMALLOC as this saves us from propagating the allocation
4992                 * context down to all allocation sites.
4993                 */
4994                noreclaim_flag = memalloc_noreclaim_save();
4995                ret = __netif_receive_skb_core(skb, true);
4996                memalloc_noreclaim_restore(noreclaim_flag);
4997        } else
4998                ret = __netif_receive_skb_core(skb, false);
4999
5000        return ret;
5001}
5002
5003static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5004{
5005        struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5006        struct bpf_prog *new = xdp->prog;
5007        int ret = 0;
5008
5009        switch (xdp->command) {
5010        case XDP_SETUP_PROG:
5011                rcu_assign_pointer(dev->xdp_prog, new);
5012                if (old)
5013                        bpf_prog_put(old);
5014
5015                if (old && !new) {
5016                        static_branch_dec(&generic_xdp_needed_key);
5017                } else if (new && !old) {
5018                        static_branch_inc(&generic_xdp_needed_key);
5019                        dev_disable_lro(dev);
5020                        dev_disable_gro_hw(dev);
5021                }
5022                break;
5023
5024        case XDP_QUERY_PROG:
5025                xdp->prog_id = old ? old->aux->id : 0;
5026                break;
5027
5028        default:
5029                ret = -EINVAL;
5030                break;
5031        }
5032
5033        return ret;
5034}
5035
5036static int netif_receive_skb_internal(struct sk_buff *skb)
5037{
5038        int ret;
5039
5040        net_timestamp_check(netdev_tstamp_prequeue, skb);
5041
5042        if (skb_defer_rx_timestamp(skb))
5043                return NET_RX_SUCCESS;
5044
5045        rcu_read_lock();
5046#ifdef CONFIG_RPS
5047        if (static_branch_unlikely(&rps_needed)) {
5048                struct rps_dev_flow voidflow, *rflow = &voidflow;
5049                int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5050
5051                if (cpu >= 0) {
5052                        ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5053                        rcu_read_unlock();
5054                        return ret;
5055                }
5056        }
5057#endif
5058        ret = __netif_receive_skb(skb);
5059        rcu_read_unlock();
5060        return ret;
5061}
5062
5063/* RHEL: when backporting netif_receive_skb_list_internal (upstream commit
5064 * 7da517a3bc52), don't forget to also backport the relevant hunks from
5065 * commits dc05360fee66 and 458bf2f224f0, those commits were applied only
5066 * partially. Then, remove this comment.
5067 */
5068
5069/**
5070 *      netif_receive_skb - process receive buffer from network
5071 *      @skb: buffer to process
5072 *
5073 *      netif_receive_skb() is the main receive data processing function.
5074 *      It always succeeds. The buffer may be dropped during processing
5075 *      for congestion control or by the protocol layers.
5076 *
5077 *      This function may only be called from softirq context and interrupts
5078 *      should be enabled.
5079 *
5080 *      Return values (usually ignored):
5081 *      NET_RX_SUCCESS: no congestion
5082 *      NET_RX_DROP: packet was dropped
5083 */
5084int netif_receive_skb(struct sk_buff *skb)
5085{
5086        trace_netif_receive_skb_entry(skb);
5087
5088        return netif_receive_skb_internal(skb);
5089}
5090EXPORT_SYMBOL(netif_receive_skb);
5091
5092DEFINE_PER_CPU(struct work_struct, flush_works);
5093
5094/* Network device is going away, flush any packets still pending */
5095static void flush_backlog(struct work_struct *work)
5096{
5097        struct sk_buff *skb, *tmp;
5098        struct softnet_data *sd;
5099
5100        local_bh_disable();
5101        sd = this_cpu_ptr(&softnet_data);
5102
5103        local_irq_disable();
5104        rps_lock(sd);
5105        skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5106                if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5107                        __skb_unlink(skb, &sd->input_pkt_queue);
5108                        kfree_skb(skb);
5109                        input_queue_head_incr(sd);
5110                }
5111        }
5112        rps_unlock(sd);
5113        local_irq_enable();
5114
5115        skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5116                if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5117                        __skb_unlink(skb, &sd->process_queue);
5118                        kfree_skb(skb);
5119                        input_queue_head_incr(sd);
5120                }
5121        }
5122        local_bh_enable();
5123}
5124
5125static void flush_all_backlogs(void)
5126{
5127        unsigned int cpu;
5128
5129        get_online_cpus();
5130
5131        for_each_online_cpu(cpu)
5132                queue_work_on(cpu, system_highpri_wq,
5133                              per_cpu_ptr(&flush_works, cpu));
5134
5135        for_each_online_cpu(cpu)
5136                flush_work(per_cpu_ptr(&flush_works, cpu));
5137
5138        put_online_cpus();
5139}
5140
5141INDIRECT_CALLABLE_DECLARE(int inet_gro_complete(struct sk_buff *, int));
5142INDIRECT_CALLABLE_DECLARE(int ipv6_gro_complete(struct sk_buff *, int));
5143static int napi_gro_complete(struct sk_buff *skb)
5144{
5145        struct packet_offload *ptype;
5146        __be16 type = skb->protocol;
5147        struct list_head *head = &offload_base;
5148        int err = -ENOENT;
5149
5150        BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
5151
5152        if (NAPI_GRO_CB(skb)->count == 1) {
5153                skb_shinfo(skb)->gso_size = 0;
5154                goto out;
5155        }
5156
5157        rcu_read_lock();
5158        list_for_each_entry_rcu(ptype, head, list) {
5159                if (ptype->type != type || !ptype->callbacks.gro_complete)
5160                        continue;
5161
5162                err = INDIRECT_CALL_INET(ptype->callbacks.gro_complete,
5163                                         ipv6_gro_complete, inet_gro_complete,
5164                                         skb, 0);
5165                break;
5166        }
5167        rcu_read_unlock();
5168
5169        if (err) {
5170                WARN_ON(&ptype->list == head);
5171                kfree_skb(skb);
5172                return NET_RX_SUCCESS;
5173        }
5174
5175out:
5176        return netif_receive_skb_internal(skb);
5177}
5178
5179/* napi->gro_list contains packets ordered by age.
5180 * youngest packets at the head of it.
5181 * Complete skbs in reverse order to reduce latencies.
5182 */
5183void napi_gro_flush(struct napi_struct *napi, bool flush_old)
5184{
5185        struct sk_buff *skb, *prev = NULL;
5186
5187        /* scan list and build reverse chain */
5188        for (skb = napi->gro_list; skb != NULL; skb = skb->next) {
5189                skb->prev = prev;
5190                prev = skb;
5191        }
5192
5193        for (skb = prev; skb; skb = prev) {
5194                skb->next = NULL;
5195
5196                if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
5197                        return;
5198
5199                prev = skb->prev;
5200                napi_gro_complete(skb);
5201                napi->gro_count--;
5202        }
5203
5204        napi->gro_list = NULL;
5205}
5206EXPORT_SYMBOL(napi_gro_flush);
5207
5208static void gro_list_prepare(struct napi_struct *napi, struct sk_buff *skb)
5209{
5210        struct sk_buff *p;
5211        unsigned int maclen = skb->dev->hard_header_len;
5212        u32 hash = skb_get_hash_raw(skb);
5213
5214        for (p = napi->gro_list; p; p = p->next) {
5215                unsigned long diffs;
5216
5217                NAPI_GRO_CB(p)->flush = 0;
5218
5219                if (hash != skb_get_hash_raw(p)) {
5220                        NAPI_GRO_CB(p)->same_flow = 0;
5221                        continue;
5222                }
5223
5224                diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
5225                diffs |= skb_vlan_tag_present(p) ^ skb_vlan_tag_present(skb);
5226                if (skb_vlan_tag_present(p))
5227                        diffs |= p->vlan_tci ^ skb->vlan_tci;
5228                diffs |= skb_metadata_dst_cmp(p, skb);
5229                diffs |= skb_metadata_differs(p, skb);
5230                if (maclen == ETH_HLEN)
5231                        diffs |= compare_ether_header(skb_mac_header(p),
5232                                                      skb_mac_header(skb));
5233                else if (!diffs)
5234                        diffs = memcmp(skb_mac_header(p),
5235                                       skb_mac_header(skb),
5236                                       maclen);
5237                NAPI_GRO_CB(p)->same_flow = !diffs;
5238        }
5239}
5240
5241static void skb_gro_reset_offset(struct sk_buff *skb)
5242{
5243        const struct skb_shared_info *pinfo = skb_shinfo(skb);
5244        const skb_frag_t *frag0 = &pinfo->frags[0];
5245
5246        NAPI_GRO_CB(skb)->data_offset = 0;
5247        NAPI_GRO_CB(skb)->frag0 = NULL;
5248        NAPI_GRO_CB(skb)->frag0_len = 0;
5249
5250        if (skb_mac_header(skb) == skb_tail_pointer(skb) &&
5251            pinfo->nr_frags &&
5252            !PageHighMem(skb_frag_page(frag0))) {
5253                NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
5254                NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
5255                                                    skb_frag_size(frag0),
5256                                                    skb->end - skb->tail);
5257        }
5258}
5259
5260static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
5261{
5262        struct skb_shared_info *pinfo = skb_shinfo(skb);
5263
5264        BUG_ON(skb->end - skb->tail < grow);
5265
5266        memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
5267
5268        skb->data_len -= grow;
5269        skb->tail += grow;
5270
5271        pinfo->frags[0].page_offset += grow;
5272        skb_frag_size_sub(&pinfo->frags[0], grow);
5273
5274        if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
5275                skb_frag_unref(skb, 0);
5276                memmove(pinfo->frags, pinfo->frags + 1,
5277                        --pinfo->nr_frags * sizeof(pinfo->frags[0]));
5278        }
5279}
5280
5281INDIRECT_CALLABLE_DECLARE(struct sk_buff **inet_gro_receive(struct sk_buff **,
5282                                                            struct sk_buff *));
5283INDIRECT_CALLABLE_DECLARE(struct sk_buff **ipv6_gro_receive(struct sk_buff **,
5284                                                            struct sk_buff *));
5285static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5286{
5287        struct sk_buff **pp = NULL;
5288        struct packet_offload *ptype;
5289        __be16 type = skb->protocol;
5290        struct list_head *head = &offload_base;
5291        int same_flow;
5292        enum gro_result ret;
5293        int grow;
5294
5295        if (netif_elide_gro(skb->dev))
5296                goto normal;
5297
5298        gro_list_prepare(napi, skb);
5299
5300        rcu_read_lock();
5301        list_for_each_entry_rcu(ptype, head, list) {
5302                if (ptype->type != type || !ptype->callbacks.gro_receive)
5303                        continue;
5304
5305                skb_set_network_header(skb, skb_gro_offset(skb));
5306                skb_reset_mac_len(skb);
5307                NAPI_GRO_CB(skb)->same_flow = 0;
5308                NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
5309                NAPI_GRO_CB(skb)->free = 0;
5310                NAPI_GRO_CB(skb)->encap_mark = 0;
5311                NAPI_GRO_CB(skb)->recursion_counter = 0;
5312                NAPI_GRO_CB(skb)->is_fou = 0;
5313                NAPI_GRO_CB(skb)->is_atomic = 1;
5314                NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
5315
5316                /* Setup for GRO checksum validation */
5317                switch (skb->ip_summed) {
5318                case CHECKSUM_COMPLETE:
5319                        NAPI_GRO_CB(skb)->csum = skb->csum;
5320                        NAPI_GRO_CB(skb)->csum_valid = 1;
5321                        NAPI_GRO_CB(skb)->csum_cnt = 0;
5322                        break;
5323                case CHECKSUM_UNNECESSARY:
5324                        NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
5325                        NAPI_GRO_CB(skb)->csum_valid = 0;
5326                        break;
5327                default:
5328                        NAPI_GRO_CB(skb)->csum_cnt = 0;
5329                        NAPI_GRO_CB(skb)->csum_valid = 0;
5330                }
5331
5332                pp = INDIRECT_CALL_INET(ptype->callbacks.gro_receive,
5333                                        ipv6_gro_receive, inet_gro_receive,
5334                                        &napi->gro_list, skb);
5335                break;
5336        }
5337        rcu_read_unlock();
5338
5339        if (&ptype->list == head)
5340                goto normal;
5341
5342        if (IS_ERR(pp) && PTR_ERR(pp) == -EINPROGRESS) {
5343                ret = GRO_CONSUMED;
5344                goto ok;
5345        }
5346
5347        same_flow = NAPI_GRO_CB(skb)->same_flow;
5348        ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
5349
5350        if (pp) {
5351                struct sk_buff *nskb = *pp;
5352
5353                *pp = nskb->next;
5354                nskb->next = NULL;
5355                napi_gro_complete(nskb);
5356                napi->gro_count--;
5357        }
5358
5359        if (same_flow)
5360                goto ok;
5361
5362        if (NAPI_GRO_CB(skb)->flush)
5363                goto normal;
5364
5365        if (unlikely(napi->gro_count >= MAX_GRO_SKBS)) {
5366                struct sk_buff *nskb = napi->gro_list;
5367
5368                /* locate the end of the list to select the 'oldest' flow */
5369                while (nskb->next) {
5370                        pp = &nskb->next;
5371                        nskb = *pp;
5372                }
5373                *pp = NULL;
5374                nskb->next = NULL;
5375                napi_gro_complete(nskb);
5376        } else {
5377                napi->gro_count++;
5378        }
5379        NAPI_GRO_CB(skb)->count = 1;
5380        NAPI_GRO_CB(skb)->age = jiffies;
5381        NAPI_GRO_CB(skb)->last = skb;
5382        skb_shinfo(skb)->gso_size = skb_gro_len(skb);
5383        skb->next = napi->gro_list;
5384        napi->gro_list = skb;
5385        ret = GRO_HELD;
5386
5387pull:
5388        grow = skb_gro_offset(skb) - skb_headlen(skb);
5389        if (grow > 0)
5390                gro_pull_from_frag0(skb, grow);
5391ok:
5392        return ret;
5393
5394normal:
5395        ret = GRO_NORMAL;
5396        goto pull;
5397}
5398
5399struct packet_offload *gro_find_receive_by_type(__be16 type)
5400{
5401        struct list_head *offload_head = &offload_base;
5402        struct packet_offload *ptype;
5403
5404        list_for_each_entry_rcu(ptype, offload_head, list) {
5405                if (ptype->type != type || !ptype->callbacks.gro_receive)
5406                        continue;
5407                return ptype;
5408        }
5409        return NULL;
5410}
5411EXPORT_SYMBOL(gro_find_receive_by_type);
5412
5413struct packet_offload *gro_find_complete_by_type(__be16 type)
5414{
5415        struct list_head *offload_head = &offload_base;
5416        struct packet_offload *ptype;
5417
5418        list_for_each_entry_rcu(ptype, offload_head, list) {
5419                if (ptype->type != type || !ptype->callbacks.gro_complete)
5420                        continue;
5421                return ptype;
5422        }
5423        return NULL;
5424}
5425EXPORT_SYMBOL(gro_find_complete_by_type);
5426
5427static void napi_skb_free_stolen_head(struct sk_buff *skb)
5428{
5429        skb_dst_drop(skb);
5430        skb_ext_put(skb);
5431        kmem_cache_free(skbuff_head_cache, skb);
5432}
5433
5434static gro_result_t napi_skb_finish(gro_result_t ret, struct sk_buff *skb)
5435{
5436        switch (ret) {
5437        case GRO_NORMAL:
5438                if (netif_receive_skb_internal(skb))
5439                        ret = GRO_DROP;
5440                break;
5441
5442        case GRO_DROP:
5443                kfree_skb(skb);
5444                break;
5445
5446        case GRO_MERGED_FREE:
5447                if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
5448                        napi_skb_free_stolen_head(skb);
5449                else
5450                        __kfree_skb(skb);
5451                break;
5452
5453        case GRO_HELD:
5454        case GRO_MERGED:
5455        case GRO_CONSUMED:
5456                break;
5457        }
5458
5459        return ret;
5460}
5461
5462gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5463{
5464        skb_mark_napi_id(skb, napi);
5465        trace_napi_gro_receive_entry(skb);
5466
5467        skb_gro_reset_offset(skb);
5468
5469        return napi_skb_finish(dev_gro_receive(napi, skb), skb);
5470}
5471EXPORT_SYMBOL(napi_gro_receive);
5472
5473static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
5474{
5475        if (unlikely(skb->pfmemalloc)) {
5476                consume_skb(skb);
5477                return;
5478        }
5479        __skb_pull(skb, skb_headlen(skb));
5480        /* restore the reserve we had after netdev_alloc_skb_ip_align() */
5481        skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
5482        __vlan_hwaccel_clear_tag(skb);
5483        skb->dev = napi->dev;
5484        skb->skb_iif = 0;
5485
5486        /* eth_type_trans() assumes pkt_type is PACKET_HOST */
5487        skb->pkt_type = PACKET_HOST;
5488
5489        skb->encapsulation = 0;
5490        skb_shinfo(skb)->gso_type = 0;
5491        skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
5492        skb_ext_reset(skb);
5493
5494        napi->skb = skb;
5495}
5496
5497struct sk_buff *napi_get_frags(struct napi_struct *napi)
5498{
5499        struct sk_buff *skb = napi->skb;
5500
5501        if (!skb) {
5502                skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
5503                if (skb) {
5504                        napi->skb = skb;
5505                        skb_mark_napi_id(skb, napi);
5506                }
5507        }
5508        return skb;
5509}
5510EXPORT_SYMBOL(napi_get_frags);
5511
5512static gro_result_t napi_frags_finish(struct napi_struct *napi,
5513                                      struct sk_buff *skb,
5514                                      gro_result_t ret)
5515{
5516        switch (ret) {
5517        case GRO_NORMAL:
5518        case GRO_HELD:
5519                __skb_push(skb, ETH_HLEN);
5520                skb->protocol = eth_type_trans(skb, skb->dev);
5521                if (ret == GRO_NORMAL && netif_receive_skb_internal(skb))
5522                        ret = GRO_DROP;
5523                break;
5524
5525        case GRO_DROP:
5526                napi_reuse_skb(napi, skb);
5527                break;
5528
5529        case GRO_MERGED_FREE:
5530                if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
5531                        napi_skb_free_stolen_head(skb);
5532                else
5533                        napi_reuse_skb(napi, skb);
5534                break;
5535
5536        case GRO_MERGED:
5537        case GRO_CONSUMED:
5538                break;
5539        }
5540
5541        return ret;
5542}
5543
5544/* Upper GRO stack assumes network header starts at gro_offset=0
5545 * Drivers could call both napi_gro_frags() and napi_gro_receive()
5546 * We copy ethernet header into skb->data to have a common layout.
5547 */
5548static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
5549{
5550        struct sk_buff *skb = napi->skb;
5551        const struct ethhdr *eth;
5552        unsigned int hlen = sizeof(*eth);
5553
5554        napi->skb = NULL;
5555
5556        skb_reset_mac_header(skb);
5557        skb_gro_reset_offset(skb);
5558
5559        if (unlikely(skb_gro_header_hard(skb, hlen))) {
5560                eth = skb_gro_header_slow(skb, hlen, 0);
5561                if (unlikely(!eth)) {
5562                        net_warn_ratelimited("%s: dropping impossible skb from %s\n",
5563                                             __func__, napi->dev->name);
5564                        napi_reuse_skb(napi, skb);
5565                        return NULL;
5566                }
5567        } else {
5568                eth = (const struct ethhdr *)skb->data;
5569                gro_pull_from_frag0(skb, hlen);
5570                NAPI_GRO_CB(skb)->frag0 += hlen;
5571                NAPI_GRO_CB(skb)->frag0_len -= hlen;
5572        }
5573        __skb_pull(skb, hlen);
5574
5575        /*
5576         * This works because the only protocols we care about don't require
5577         * special handling.
5578         * We'll fix it up properly in napi_frags_finish()
5579         */
5580        skb->protocol = eth->h_proto;
5581
5582        return skb;
5583}
5584
5585gro_result_t napi_gro_frags(struct napi_struct *napi)
5586{
5587        struct sk_buff *skb = napi_frags_skb(napi);
5588
5589        if (!skb)
5590                return GRO_DROP;
5591
5592        trace_napi_gro_frags_entry(skb);
5593
5594        return napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
5595}
5596EXPORT_SYMBOL(napi_gro_frags);
5597
5598/* Compute the checksum from gro_offset and return the folded value
5599 * after adding in any pseudo checksum.
5600 */
5601__sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
5602{
5603        __wsum wsum;
5604        __sum16 sum;
5605
5606        wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
5607
5608        /* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
5609        sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
5610        if (likely(!sum)) {
5611                if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
5612                    !skb->csum_complete_sw)
5613                        netdev_rx_csum_fault(skb->dev);
5614        }
5615
5616        NAPI_GRO_CB(skb)->csum = wsum;
5617        NAPI_GRO_CB(skb)->csum_valid = 1;
5618
5619        return sum;
5620}
5621EXPORT_SYMBOL(__skb_gro_checksum_complete);
5622
5623static void net_rps_send_ipi(struct softnet_data *remsd)
5624{
5625#ifdef CONFIG_RPS
5626        while (remsd) {
5627                struct softnet_data *next = remsd->rps_ipi_next;
5628
5629                if (cpu_online(remsd->cpu))
5630                        smp_call_function_single_async(remsd->cpu, &remsd->csd);
5631                remsd = next;
5632        }
5633#endif
5634}
5635
5636/*
5637 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
5638 * Note: called with local irq disabled, but exits with local irq enabled.
5639 */
5640static void net_rps_action_and_irq_enable(struct softnet_data *sd)
5641{
5642#ifdef CONFIG_RPS
5643        struct softnet_data *remsd = sd->rps_ipi_list;
5644
5645        if (remsd) {
5646                sd->rps_ipi_list = NULL;
5647
5648                local_irq_enable();
5649
5650                /* Send pending IPI's to kick RPS processing on remote cpus. */
5651                net_rps_send_ipi(remsd);
5652        } else
5653#endif
5654                local_irq_enable();
5655}
5656
5657static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
5658{
5659#ifdef CONFIG_RPS
5660        return sd->rps_ipi_list != NULL;
5661#else
5662        return false;
5663#endif
5664}
5665
5666static int process_backlog(struct napi_struct *napi, int quota)
5667{
5668        struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
5669        bool again = true;
5670        int work = 0;
5671
5672        /* Check if we have pending ipi, its better to send them now,
5673         * not waiting net_rx_action() end.
5674         */
5675        if (sd_has_rps_ipi_waiting(sd)) {
5676                local_irq_disable();
5677                net_rps_action_and_irq_enable(sd);
5678        }
5679
5680        napi->weight = dev_rx_weight;
5681        while (again) {
5682                struct sk_buff *skb;
5683
5684                while ((skb = __skb_dequeue(&sd->process_queue))) {
5685                        rcu_read_lock();
5686                        __netif_receive_skb(skb);
5687                        rcu_read_unlock();
5688                        input_queue_head_incr(sd);
5689                        if (++work >= quota)
5690                                return work;
5691
5692                }
5693
5694                local_irq_disable();
5695                rps_lock(sd);
5696                if (skb_queue_empty(&sd->input_pkt_queue)) {
5697                        /*
5698                         * Inline a custom version of __napi_complete().
5699                         * only current cpu owns and manipulates this napi,
5700                         * and NAPI_STATE_SCHED is the only possible flag set
5701                         * on backlog.
5702                         * We can use a plain write instead of clear_bit(),
5703                         * and we dont need an smp_mb() memory barrier.
5704                         */
5705                        napi->state = 0;
5706                        again = false;
5707                } else {
5708                        skb_queue_splice_tail_init(&sd->input_pkt_queue,
5709                                                   &sd->process_queue);
5710                }
5711                rps_unlock(sd);
5712                local_irq_enable();
5713        }
5714
5715        return work;
5716}
5717
5718/**
5719 * __napi_schedule - schedule for receive
5720 * @n: entry to schedule
5721 *
5722 * The entry's receive function will be scheduled to run.
5723 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
5724 */
5725void __napi_schedule(struct napi_struct *n)
5726{
5727        unsigned long flags;
5728
5729        local_irq_save(flags);
5730        ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5731        local_irq_restore(flags);
5732}
5733EXPORT_SYMBOL(__napi_schedule);
5734
5735/**
5736 *      napi_schedule_prep - check if napi can be scheduled
5737 *      @n: napi context
5738 *
5739 * Test if NAPI routine is already running, and if not mark
5740 * it as running.  This is used as a condition variable
5741 * insure only one NAPI poll instance runs.  We also make
5742 * sure there is no pending NAPI disable.
5743 */
5744bool napi_schedule_prep(struct napi_struct *n)
5745{
5746        unsigned long val, new;
5747
5748        do {
5749                val = READ_ONCE(n->state);
5750                if (unlikely(val & NAPIF_STATE_DISABLE))
5751                        return false;
5752                new = val | NAPIF_STATE_SCHED;
5753
5754                /* Sets STATE_MISSED bit if STATE_SCHED was already set
5755                 * This was suggested by Alexander Duyck, as compiler
5756                 * emits better code than :
5757                 * if (val & NAPIF_STATE_SCHED)
5758                 *     new |= NAPIF_STATE_MISSED;
5759                 */
5760                new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
5761                                                   NAPIF_STATE_MISSED;
5762        } while (cmpxchg(&n->state, val, new) != val);
5763
5764        return !(val & NAPIF_STATE_SCHED);
5765}
5766EXPORT_SYMBOL(napi_schedule_prep);
5767
5768/**
5769 * __napi_schedule_irqoff - schedule for receive
5770 * @n: entry to schedule
5771 *
5772 * Variant of __napi_schedule() assuming hard irqs are masked
5773 */
5774void __napi_schedule_irqoff(struct napi_struct *n)
5775{
5776        ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5777}
5778EXPORT_SYMBOL(__napi_schedule_irqoff);
5779
5780bool napi_complete_done(struct napi_struct *n, int work_done)
5781{
5782        unsigned long flags, val, new;
5783
5784        /*
5785         * 1) Don't let napi dequeue from the cpu poll list
5786         *    just in case its running on a different cpu.
5787         * 2) If we are busy polling, do nothing here, we have
5788         *    the guarantee we will be called later.
5789         */
5790        if (unlikely(n->state & (NAPIF_STATE_NPSVC |
5791                                 NAPIF_STATE_IN_BUSY_POLL)))
5792                return false;
5793
5794        if (n->gro_list) {
5795                unsigned long timeout = 0;
5796
5797                if (work_done)
5798                        timeout = n->dev->gro_flush_timeout;
5799
5800                /* When the NAPI instance uses a timeout and keeps postponing
5801                 * it, we need to bound somehow the time packets are kept in
5802                 * the GRO layer
5803                 */
5804                napi_gro_flush(n, !!timeout);
5805                if (timeout)
5806                        hrtimer_start(&n->timer, ns_to_ktime(timeout),
5807                                      HRTIMER_MODE_REL_PINNED);
5808        }
5809        if (unlikely(!list_empty(&n->poll_list))) {
5810                /* If n->poll_list is not empty, we need to mask irqs */
5811                local_irq_save(flags);
5812                list_del_init(&n->poll_list);
5813                local_irq_restore(flags);
5814        }
5815
5816        do {
5817                val = READ_ONCE(n->state);
5818
5819                WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
5820
5821                new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED);
5822
5823                /* If STATE_MISSED was set, leave STATE_SCHED set,
5824                 * because we will call napi->poll() one more time.
5825                 * This C code was suggested by Alexander Duyck to help gcc.
5826                 */
5827                new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
5828                                                    NAPIF_STATE_SCHED;
5829        } while (cmpxchg(&n->state, val, new) != val);
5830
5831        if (unlikely(val & NAPIF_STATE_MISSED)) {
5832                __napi_schedule(n);
5833                return false;
5834        }
5835
5836        return true;
5837}
5838EXPORT_SYMBOL(napi_complete_done);
5839
5840/* must be called under rcu_read_lock(), as we dont take a reference */
5841static struct napi_struct *napi_by_id(unsigned int napi_id)
5842{
5843        unsigned int hash = napi_id % HASH_SIZE(napi_hash);
5844        struct napi_struct *napi;
5845
5846        hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
5847                if (napi->napi_id == napi_id)
5848                        return napi;
5849
5850        return NULL;
5851}
5852
5853#if defined(CONFIG_NET_RX_BUSY_POLL)
5854
5855#define BUSY_POLL_BUDGET 8
5856
5857static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock)
5858{
5859        int rc;
5860
5861        /* Busy polling means there is a high chance device driver hard irq
5862         * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
5863         * set in napi_schedule_prep().
5864         * Since we are about to call napi->poll() once more, we can safely
5865         * clear NAPI_STATE_MISSED.
5866         *
5867         * Note: x86 could use a single "lock and ..." instruction
5868         * to perform these two clear_bit()
5869         */
5870        clear_bit(NAPI_STATE_MISSED, &napi->state);
5871        clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
5872
5873        local_bh_disable();
5874
5875        /* All we really want here is to re-enable device interrupts.
5876         * Ideally, a new ndo_busy_poll_stop() could avoid another round.
5877         */
5878        rc = napi->poll(napi, BUSY_POLL_BUDGET);
5879        trace_napi_poll(napi, rc, BUSY_POLL_BUDGET);
5880        netpoll_poll_unlock(have_poll_lock);
5881        if (rc == BUSY_POLL_BUDGET)
5882                __napi_schedule(napi);
5883        local_bh_enable();
5884}
5885
5886void napi_busy_loop(unsigned int napi_id,
5887                    bool (*loop_end)(void *, unsigned long),
5888                    void *loop_end_arg)
5889{
5890        unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
5891        int (*napi_poll)(struct napi_struct *napi, int budget);
5892        void *have_poll_lock = NULL;
5893        struct napi_struct *napi;
5894
5895restart:
5896        napi_poll = NULL;
5897
5898        rcu_read_lock();
5899
5900        napi = napi_by_id(napi_id);
5901        if (!napi)
5902                goto out;
5903
5904        preempt_disable();
5905        for (;;) {
5906                int work = 0;
5907
5908                local_bh_disable();
5909                if (!napi_poll) {
5910                        unsigned long val = READ_ONCE(napi->state);
5911
5912                        /* If multiple threads are competing for this napi,
5913                         * we avoid dirtying napi->state as much as we can.
5914                         */
5915                        if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
5916                                   NAPIF_STATE_IN_BUSY_POLL))
5917                                goto count;
5918                        if (cmpxchg(&napi->state, val,
5919                                    val | NAPIF_STATE_IN_BUSY_POLL |
5920                                          NAPIF_STATE_SCHED) != val)
5921                                goto count;
5922                        have_poll_lock = netpoll_poll_lock(napi);
5923                        napi_poll = napi->poll;
5924                }
5925                work = napi_poll(napi, BUSY_POLL_BUDGET);
5926                trace_napi_poll(napi, work, BUSY_POLL_BUDGET);
5927count:
5928                if (work > 0)
5929                        __NET_ADD_STATS(dev_net(napi->dev),
5930                                        LINUX_MIB_BUSYPOLLRXPACKETS, work);
5931                local_bh_enable();
5932
5933                if (!loop_end || loop_end(loop_end_arg, start_time))
5934                        break;
5935
5936                if (unlikely(need_resched())) {
5937                        if (napi_poll)
5938                                busy_poll_stop(napi, have_poll_lock);
5939                        preempt_enable();
5940                        rcu_read_unlock();
5941                        cond_resched();
5942                        if (loop_end(loop_end_arg, start_time))
5943                                return;
5944                        goto restart;
5945                }
5946                cpu_relax();
5947        }
5948        if (napi_poll)
5949                busy_poll_stop(napi, have_poll_lock);
5950        preempt_enable();
5951out:
5952        rcu_read_unlock();
5953}
5954EXPORT_SYMBOL(napi_busy_loop);
5955
5956#endif /* CONFIG_NET_RX_BUSY_POLL */
5957
5958static void napi_hash_add(struct napi_struct *napi)
5959{
5960        if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state) ||
5961            test_and_set_bit(NAPI_STATE_HASHED, &napi->state))
5962                return;
5963
5964        spin_lock(&napi_hash_lock);
5965
5966        /* 0..NR_CPUS range is reserved for sender_cpu use */
5967        do {
5968                if (unlikely(++napi_gen_id < MIN_NAPI_ID))
5969                        napi_gen_id = MIN_NAPI_ID;
5970        } while (napi_by_id(napi_gen_id));
5971        napi->napi_id = napi_gen_id;
5972
5973        hlist_add_head_rcu(&napi->napi_hash_node,
5974                           &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
5975
5976        spin_unlock(&napi_hash_lock);
5977}
5978
5979/* Warning : caller is responsible to make sure rcu grace period
5980 * is respected before freeing memory containing @napi
5981 */
5982bool napi_hash_del(struct napi_struct *napi)
5983{
5984        bool rcu_sync_needed = false;
5985
5986        spin_lock(&napi_hash_lock);
5987
5988        if (test_and_clear_bit(NAPI_STATE_HASHED, &napi->state)) {
5989                rcu_sync_needed = true;
5990                hlist_del_rcu(&napi->napi_hash_node);
5991        }
5992        spin_unlock(&napi_hash_lock);
5993        return rcu_sync_needed;
5994}
5995EXPORT_SYMBOL_GPL(napi_hash_del);
5996
5997static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
5998{
5999        struct napi_struct *napi;
6000
6001        napi = container_of(timer, struct napi_struct, timer);
6002
6003        /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6004         * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6005         */
6006        if (napi->gro_list && !napi_disable_pending(napi) &&
6007            !test_and_set_bit(NAPI_STATE_SCHED, &napi->state))
6008                __napi_schedule_irqoff(napi);
6009
6010        return HRTIMER_NORESTART;
6011}
6012
6013void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
6014                    int (*poll)(struct napi_struct *, int), int weight)
6015{
6016        INIT_LIST_HEAD(&napi->poll_list);
6017        hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6018        napi->timer.function = napi_watchdog;
6019        napi->gro_count = 0;
6020        napi->gro_list = NULL;
6021        napi->skb = NULL;
6022        napi->poll = poll;
6023        if (weight > NAPI_POLL_WEIGHT)
6024                pr_err_once("netif_napi_add() called with weight %d on device %s\n",
6025                            weight, dev->name);
6026        napi->weight = weight;
6027        list_add(&napi->dev_list, &dev->napi_list);
6028        napi->dev = dev;
6029#ifdef CONFIG_NETPOLL
6030        napi->poll_owner = -1;
6031#endif
6032        set_bit(NAPI_STATE_SCHED, &napi->state);
6033        napi_hash_add(napi);
6034}
6035EXPORT_SYMBOL(netif_napi_add);
6036
6037void napi_disable(struct napi_struct *n)
6038{
6039        might_sleep();
6040        set_bit(NAPI_STATE_DISABLE, &n->state);
6041
6042        while (test_and_set_bit(NAPI_STATE_SCHED, &n->state))
6043                msleep(1);
6044        while (test_and_set_bit(NAPI_STATE_NPSVC, &n->state))
6045                msleep(1);
6046
6047        hrtimer_cancel(&n->timer);
6048
6049        clear_bit(NAPI_STATE_DISABLE, &n->state);
6050}
6051EXPORT_SYMBOL(napi_disable);
6052
6053/* Must be called in process context */
6054void netif_napi_del(struct napi_struct *napi)
6055{
6056        might_sleep();
6057        if (napi_hash_del(napi))
6058                synchronize_net();
6059        list_del_init(&napi->dev_list);
6060        napi_free_frags(napi);
6061
6062        kfree_skb_list(napi->gro_list);
6063        napi->gro_list = NULL;
6064        napi->gro_count = 0;
6065}
6066EXPORT_SYMBOL(netif_napi_del);
6067
6068static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6069{
6070        void *have;
6071        int work, weight;
6072
6073        list_del_init(&n->poll_list);
6074
6075        have = netpoll_poll_lock(n);
6076
6077        weight = n->weight;
6078
6079        /* This NAPI_STATE_SCHED test is for avoiding a race
6080         * with netpoll's poll_napi().  Only the entity which
6081         * obtains the lock and sees NAPI_STATE_SCHED set will
6082         * actually make the ->poll() call.  Therefore we avoid
6083         * accidentally calling ->poll() when NAPI is not scheduled.
6084         */
6085        work = 0;
6086        if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6087                work = n->poll(n, weight);
6088                trace_napi_poll(n, work, weight);
6089        }
6090
6091        WARN_ON_ONCE(work > weight);
6092
6093        if (likely(work < weight))
6094                goto out_unlock;
6095
6096        /* Drivers must not modify the NAPI state if they
6097         * consume the entire weight.  In such cases this code
6098         * still "owns" the NAPI instance and therefore can
6099         * move the instance around on the list at-will.
6100         */
6101        if (unlikely(napi_disable_pending(n))) {
6102                napi_complete(n);
6103                goto out_unlock;
6104        }
6105
6106        if (n->gro_list) {
6107                /* flush too old packets
6108                 * If HZ < 1000, flush all packets.
6109                 */
6110                napi_gro_flush(n, HZ >= 1000);
6111        }
6112
6113        /* Some drivers may have called napi_schedule
6114         * prior to exhausting their budget.
6115         */
6116        if (unlikely(!list_empty(&n->poll_list))) {
6117                pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6118                             n->dev ? n->dev->name : "backlog");
6119                goto out_unlock;
6120        }
6121
6122        list_add_tail(&n->poll_list, repoll);
6123
6124out_unlock:
6125        netpoll_poll_unlock(have);
6126
6127        return work;
6128}
6129
6130static __latent_entropy void net_rx_action(struct softirq_action *h)
6131{
6132        struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6133        unsigned long time_limit = jiffies +
6134                usecs_to_jiffies(netdev_budget_usecs);
6135        int budget = netdev_budget;
6136        LIST_HEAD(list);
6137        LIST_HEAD(repoll);
6138
6139        local_irq_disable();
6140        list_splice_init(&sd->poll_list, &list);
6141        local_irq_enable();
6142
6143        for (;;) {
6144                struct napi_struct *n;
6145
6146                if (list_empty(&list)) {
6147                        if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
6148                                goto out;
6149                        break;
6150                }
6151
6152                n = list_first_entry(&list, struct napi_struct, poll_list);
6153                budget -= napi_poll(n, &repoll);
6154
6155                /* If softirq window is exhausted then punt.
6156                 * Allow this to run for 2 jiffies since which will allow
6157                 * an average latency of 1.5/HZ.
6158                 */
6159                if (unlikely(budget <= 0 ||
6160                             time_after_eq(jiffies, time_limit))) {
6161                        sd->time_squeeze++;
6162                        break;
6163                }
6164        }
6165
6166        local_irq_disable();
6167
6168        list_splice_tail_init(&sd->poll_list, &list);
6169        list_splice_tail(&repoll, &list);
6170        list_splice(&list, &sd->poll_list);
6171        if (!list_empty(&sd->poll_list))
6172                __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6173
6174        net_rps_action_and_irq_enable(sd);
6175out:
6176        __kfree_skb_flush();
6177}
6178
6179struct netdev_adjacent {
6180        struct net_device *dev;
6181
6182        /* upper master flag, there can only be one master device per list */
6183        bool master;
6184
6185        /* counter for the number of times this device was added to us */
6186        u16 ref_nr;
6187
6188        /* private field for the users */
6189        void *private;
6190
6191        struct list_head list;
6192        struct rcu_head rcu;
6193};
6194
6195static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6196                                                 struct list_head *adj_list)
6197{
6198        struct netdev_adjacent *adj;
6199
6200        list_for_each_entry(adj, adj_list, list) {
6201                if (adj->dev == adj_dev)
6202                        return adj;
6203        }
6204        return NULL;
6205}
6206
6207static int __netdev_has_upper_dev(struct net_device *upper_dev, void *data)
6208{
6209        struct net_device *dev = data;
6210
6211        return upper_dev == dev;
6212}
6213
6214/**
6215 * netdev_has_upper_dev - Check if device is linked to an upper device
6216 * @dev: device
6217 * @upper_dev: upper device to check
6218 *
6219 * Find out if a device is linked to specified upper device and return true
6220 * in case it is. Note that this checks only immediate upper device,
6221 * not through a complete stack of devices. The caller must hold the RTNL lock.
6222 */
6223bool netdev_has_upper_dev(struct net_device *dev,
6224                          struct net_device *upper_dev)
6225{
6226        ASSERT_RTNL();
6227
6228        return netdev_walk_all_upper_dev_rcu(dev, __netdev_has_upper_dev,
6229                                             upper_dev);
6230}
6231EXPORT_SYMBOL(netdev_has_upper_dev);
6232
6233/**
6234 * netdev_has_upper_dev_all - Check if device is linked to an upper device
6235 * @dev: device
6236 * @upper_dev: upper device to check
6237 *
6238 * Find out if a device is linked to specified upper device and return true
6239 * in case it is. Note that this checks the entire upper device chain.
6240 * The caller must hold rcu lock.
6241 */
6242
6243bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6244                                  struct net_device *upper_dev)
6245{
6246        return !!netdev_walk_all_upper_dev_rcu(dev, __netdev_has_upper_dev,
6247                                               upper_dev);
6248}
6249EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6250
6251/**
6252 * netdev_has_any_upper_dev - Check if device is linked to some device
6253 * @dev: device
6254 *
6255 * Find out if a device is linked to an upper device and return true in case
6256 * it is. The caller must hold the RTNL lock.
6257 */
6258bool netdev_has_any_upper_dev(struct net_device *dev)
6259{
6260        ASSERT_RTNL();
6261
6262        return !list_empty(&dev->adj_list.upper);
6263}
6264EXPORT_SYMBOL(netdev_has_any_upper_dev);
6265
6266/**
6267 * netdev_master_upper_dev_get - Get master upper device
6268 * @dev: device
6269 *
6270 * Find a master upper device and return pointer to it or NULL in case
6271 * it's not there. The caller must hold the RTNL lock.
6272 */
6273struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6274{
6275        struct netdev_adjacent *upper;
6276
6277        ASSERT_RTNL();
6278
6279        if (list_empty(&dev->adj_list.upper))
6280                return NULL;
6281
6282        upper = list_first_entry(&dev->adj_list.upper,
6283                                 struct netdev_adjacent, list);
6284        if (likely(upper->master))
6285                return upper->dev;
6286        return NULL;
6287}
6288EXPORT_SYMBOL(netdev_master_upper_dev_get);
6289
6290/**
6291 * netdev_has_any_lower_dev - Check if device is linked to some device
6292 * @dev: device
6293 *
6294 * Find out if a device is linked to a lower device and return true in case
6295 * it is. The caller must hold the RTNL lock.
6296 */
6297static bool netdev_has_any_lower_dev(struct net_device *dev)
6298{
6299        ASSERT_RTNL();
6300
6301        return !list_empty(&dev->adj_list.lower);
6302}
6303
6304void *netdev_adjacent_get_private(struct list_head *adj_list)
6305{
6306        struct netdev_adjacent *adj;
6307
6308        adj = list_entry(adj_list, struct netdev_adjacent, list);
6309
6310        return adj->private;
6311}
6312EXPORT_SYMBOL(netdev_adjacent_get_private);
6313
6314/**
6315 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
6316 * @dev: device
6317 * @iter: list_head ** of the current position
6318 *
6319 * Gets the next device from the dev's upper list, starting from iter
6320 * position. The caller must hold RCU read lock.
6321 */
6322struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
6323                                                 struct list_head **iter)
6324{
6325        struct netdev_adjacent *upper;
6326
6327        WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6328
6329        upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6330
6331        if (&upper->list == &dev->adj_list.upper)
6332                return NULL;
6333
6334        *iter = &upper->list;
6335
6336        return upper->dev;
6337}
6338EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
6339
6340static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
6341                                                    struct list_head **iter)
6342{
6343        struct netdev_adjacent *upper;
6344
6345        WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6346
6347        upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6348
6349        if (&upper->list == &dev->adj_list.upper)
6350                return NULL;
6351
6352        *iter = &upper->list;
6353
6354        return upper->dev;
6355}
6356
6357int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
6358                                  int (*fn)(struct net_device *dev,
6359                                            void *data),
6360                                  void *data)
6361{
6362        struct net_device *udev;
6363        struct list_head *iter;
6364        int ret;
6365
6366        for (iter = &dev->adj_list.upper,
6367             udev = netdev_next_upper_dev_rcu(dev, &iter);
6368             udev;
6369             udev = netdev_next_upper_dev_rcu(dev, &iter)) {
6370                /* first is the upper device itself */
6371                ret = fn(udev, data);
6372                if (ret)
6373                        return ret;
6374
6375                /* then look at all of its upper devices */
6376                ret = netdev_walk_all_upper_dev_rcu(udev, fn, data);
6377                if (ret)
6378                        return ret;
6379        }
6380
6381        return 0;
6382}
6383EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
6384
6385/**
6386 * netdev_lower_get_next_private - Get the next ->private from the
6387 *                                 lower neighbour list
6388 * @dev: device
6389 * @iter: list_head ** of the current position
6390 *
6391 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6392 * list, starting from iter position. The caller must hold either hold the
6393 * RTNL lock or its own locking that guarantees that the neighbour lower
6394 * list will remain unchanged.
6395 */
6396void *netdev_lower_get_next_private(struct net_device *dev,
6397                                    struct list_head **iter)
6398{
6399        struct netdev_adjacent *lower;
6400
6401        lower = list_entry(*iter, struct netdev_adjacent, list);
6402
6403        if (&lower->list == &dev->adj_list.lower)
6404                return NULL;
6405
6406        *iter = lower->list.next;
6407
6408        return lower->private;
6409}
6410EXPORT_SYMBOL(netdev_lower_get_next_private);
6411
6412/**
6413 * netdev_lower_get_next_private_rcu - Get the next ->private from the
6414 *                                     lower neighbour list, RCU
6415 *                                     variant
6416 * @dev: device
6417 * @iter: list_head ** of the current position
6418 *
6419 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6420 * list, starting from iter position. The caller must hold RCU read lock.
6421 */
6422void *netdev_lower_get_next_private_rcu(struct net_device *dev,
6423                                        struct list_head **iter)
6424{
6425        struct netdev_adjacent *lower;
6426
6427        WARN_ON_ONCE(!rcu_read_lock_held());
6428
6429        lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6430
6431        if (&lower->list == &dev->adj_list.lower)
6432                return NULL;
6433
6434        *iter = &lower->list;
6435
6436        return lower->private;
6437}
6438EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
6439
6440/**
6441 * netdev_lower_get_next - Get the next device from the lower neighbour
6442 *                         list
6443 * @dev: device
6444 * @iter: list_head ** of the current position
6445 *
6446 * Gets the next netdev_adjacent from the dev's lower neighbour
6447 * list, starting from iter position. The caller must hold RTNL lock or
6448 * its own locking that guarantees that the neighbour lower
6449 * list will remain unchanged.
6450 */
6451void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
6452{
6453        struct netdev_adjacent *lower;
6454
6455        lower = list_entry(*iter, struct netdev_adjacent, list);
6456
6457        if (&lower->list == &dev->adj_list.lower)
6458                return NULL;
6459
6460        *iter = lower->list.next;
6461
6462        return lower->dev;
6463}
6464EXPORT_SYMBOL(netdev_lower_get_next);
6465
6466static struct net_device *netdev_next_lower_dev(struct net_device *dev,
6467                                                struct list_head **iter)
6468{
6469        struct netdev_adjacent *lower;
6470
6471        lower = list_entry((*iter)->next, struct netdev_adjacent, list);
6472
6473        if (&lower->list == &dev->adj_list.lower)
6474                return NULL;
6475
6476        *iter = &lower->list;
6477
6478        return lower->dev;
6479}
6480
6481int netdev_walk_all_lower_dev(struct net_device *dev,
6482                              int (*fn)(struct net_device *dev,
6483                                        void *data),
6484                              void *data)
6485{
6486        struct net_device *ldev;
6487        struct list_head *iter;
6488        int ret;
6489
6490        for (iter = &dev->adj_list.lower,
6491             ldev = netdev_next_lower_dev(dev, &iter);
6492             ldev;
6493             ldev = netdev_next_lower_dev(dev, &iter)) {
6494                /* first is the lower device itself */
6495                ret = fn(ldev, data);
6496                if (ret)
6497                        return ret;
6498
6499                /* then look at all of its lower devices */
6500                ret = netdev_walk_all_lower_dev(ldev, fn, data);
6501                if (ret)
6502                        return ret;
6503        }
6504
6505        return 0;
6506}
6507EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
6508
6509static struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
6510                                                    struct list_head **iter)
6511{
6512        struct netdev_adjacent *lower;
6513
6514        lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6515        if (&lower->list == &dev->adj_list.lower)
6516                return NULL;
6517
6518        *iter = &lower->list;
6519
6520        return lower->dev;
6521}
6522
6523int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
6524                                  int (*fn)(struct net_device *dev,
6525                                            void *data),
6526                                  void *data)
6527{
6528        struct net_device *ldev;
6529        struct list_head *iter;
6530        int ret;
6531
6532        for (iter = &dev->adj_list.lower,
6533             ldev = netdev_next_lower_dev_rcu(dev, &iter);
6534             ldev;
6535             ldev = netdev_next_lower_dev_rcu(dev, &iter)) {
6536                /* first is the lower device itself */
6537                ret = fn(ldev, data);
6538                if (ret)
6539                        return ret;
6540
6541                /* then look at all of its lower devices */
6542                ret = netdev_walk_all_lower_dev_rcu(ldev, fn, data);
6543                if (ret)
6544                        return ret;
6545        }
6546
6547        return 0;
6548}
6549EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
6550
6551/**
6552 * netdev_lower_get_first_private_rcu - Get the first ->private from the
6553 *                                     lower neighbour list, RCU
6554 *                                     variant
6555 * @dev: device
6556 *
6557 * Gets the first netdev_adjacent->private from the dev's lower neighbour
6558 * list. The caller must hold RCU read lock.
6559 */
6560void *netdev_lower_get_first_private_rcu(struct net_device *dev)
6561{
6562        struct netdev_adjacent *lower;
6563
6564        lower = list_first_or_null_rcu(&dev->adj_list.lower,
6565                        struct netdev_adjacent, list);
6566        if (lower)
6567                return lower->private;
6568        return NULL;
6569}
6570EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
6571
6572/**
6573 * netdev_master_upper_dev_get_rcu - Get master upper device
6574 * @dev: device
6575 *
6576 * Find a master upper device and return pointer to it or NULL in case
6577 * it's not there. The caller must hold the RCU read lock.
6578 */
6579struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
6580{
6581        struct netdev_adjacent *upper;
6582
6583        upper = list_first_or_null_rcu(&dev->adj_list.upper,
6584                                       struct netdev_adjacent, list);
6585        if (upper && likely(upper->master))
6586                return upper->dev;
6587        return NULL;
6588}
6589EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
6590
6591static int netdev_adjacent_sysfs_add(struct net_device *dev,
6592                              struct net_device *adj_dev,
6593                              struct list_head *dev_list)
6594{
6595        char linkname[IFNAMSIZ+7];
6596
6597        sprintf(linkname, dev_list == &dev->adj_list.upper ?
6598                "upper_%s" : "lower_%s", adj_dev->name);
6599        return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
6600                                 linkname);
6601}
6602static void netdev_adjacent_sysfs_del(struct net_device *dev,
6603                               char *name,
6604                               struct list_head *dev_list)
6605{
6606        char linkname[IFNAMSIZ+7];
6607
6608        sprintf(linkname, dev_list == &dev->adj_list.upper ?
6609                "upper_%s" : "lower_%s", name);
6610        sysfs_remove_link(&(dev->dev.kobj), linkname);
6611}
6612
6613static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
6614                                                 struct net_device *adj_dev,
6615                                                 struct list_head *dev_list)
6616{
6617        return (dev_list == &dev->adj_list.upper ||
6618                dev_list == &dev->adj_list.lower) &&
6619                net_eq(dev_net(dev), dev_net(adj_dev));
6620}
6621
6622static int __netdev_adjacent_dev_insert(struct net_device *dev,
6623                                        struct net_device *adj_dev,
6624                                        struct list_head *dev_list,
6625                                        void *private, bool master)
6626{
6627        struct netdev_adjacent *adj;
6628        int ret;
6629
6630        adj = __netdev_find_adj(adj_dev, dev_list);
6631
6632        if (adj) {
6633                adj->ref_nr += 1;
6634                pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
6635                         dev->name, adj_dev->name, adj->ref_nr);
6636
6637                return 0;
6638        }
6639
6640        adj = kmalloc(sizeof(*adj), GFP_KERNEL);
6641        if (!adj)
6642                return -ENOMEM;
6643
6644        adj->dev = adj_dev;
6645        adj->master = master;
6646        adj->ref_nr = 1;
6647        adj->private = private;
6648        dev_hold(adj_dev);
6649
6650        pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
6651                 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
6652
6653        if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
6654                ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
6655                if (ret)
6656                        goto free_adj;
6657        }
6658
6659        /* Ensure that master link is always the first item in list. */
6660        if (master) {
6661                ret = sysfs_create_link(&(dev->dev.kobj),
6662                                        &(adj_dev->dev.kobj), "master");
6663                if (ret)
6664                        goto remove_symlinks;
6665
6666                list_add_rcu(&adj->list, dev_list);
6667        } else {
6668                list_add_tail_rcu(&adj->list, dev_list);
6669        }
6670
6671        return 0;
6672
6673remove_symlinks:
6674        if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
6675                netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
6676free_adj:
6677        kfree(adj);
6678        dev_put(adj_dev);
6679
6680        return ret;
6681}
6682
6683static void __netdev_adjacent_dev_remove(struct net_device *dev,
6684                                         struct net_device *adj_dev,
6685                                         u16 ref_nr,
6686                                         struct list_head *dev_list)
6687{
6688        struct netdev_adjacent *adj;
6689
6690        pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
6691                 dev->name, adj_dev->name, ref_nr);
6692
6693        adj = __netdev_find_adj(adj_dev, dev_list);
6694
6695        if (!adj) {
6696                pr_err("Adjacency does not exist for device %s from %s\n",
6697                       dev->name, adj_dev->name);
6698                WARN_ON(1);
6699                return;
6700        }
6701
6702        if (adj->ref_nr > ref_nr) {
6703                pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
6704                         dev->name, adj_dev->name, ref_nr,
6705                         adj->ref_nr - ref_nr);
6706                adj->ref_nr -= ref_nr;
6707                return;
6708        }
6709
6710        if (adj->master)
6711                sysfs_remove_link(&(dev->dev.kobj), "master");
6712
6713        if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
6714                netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
6715
6716        list_del_rcu(&adj->list);
6717        pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
6718                 adj_dev->name, dev->name, adj_dev->name);
6719        dev_put(adj_dev);
6720        kfree_rcu(adj, rcu);
6721}
6722
6723static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
6724                                            struct net_device *upper_dev,
6725                                            struct list_head *up_list,
6726                                            struct list_head *down_list,
6727                                            void *private, bool master)
6728{
6729        int ret;
6730
6731        ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
6732                                           private, master);
6733        if (ret)
6734                return ret;
6735
6736        ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
6737                                           private, false);
6738        if (ret) {
6739                __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
6740                return ret;
6741        }
6742
6743        return 0;
6744}
6745
6746static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
6747                                               struct net_device *upper_dev,
6748                                               u16 ref_nr,
6749                                               struct list_head *up_list,
6750                                               struct list_head *down_list)
6751{
6752        __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
6753        __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
6754}
6755
6756static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
6757                                                struct net_device *upper_dev,
6758                                                void *private, bool master)
6759{
6760        return __netdev_adjacent_dev_link_lists(dev, upper_dev,
6761                                                &dev->adj_list.upper,
6762                                                &upper_dev->adj_list.lower,
6763                                                private, master);
6764}
6765
6766static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
6767                                                   struct net_device *upper_dev)
6768{
6769        __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
6770                                           &dev->adj_list.upper,
6771                                           &upper_dev->adj_list.lower);
6772}
6773
6774static int __netdev_upper_dev_link(struct net_device *dev,
6775                                   struct net_device *upper_dev, bool master,
6776                                   void *upper_priv, void *upper_info,
6777                                   struct netlink_ext_ack *extack)
6778{
6779        struct netdev_notifier_changeupper_info changeupper_info = {
6780                .info = {
6781                        .dev = dev,
6782                        .extack = extack,
6783                },
6784                .upper_dev = upper_dev,
6785                .master = master,
6786                .linking = true,
6787                .upper_info = upper_info,
6788        };
6789        struct net_device *master_dev;
6790        int ret = 0;
6791
6792        ASSERT_RTNL();
6793
6794        if (dev == upper_dev)
6795                return -EBUSY;
6796
6797        /* To prevent loops, check if dev is not upper device to upper_dev. */
6798        if (netdev_has_upper_dev(upper_dev, dev))
6799                return -EBUSY;
6800
6801        if (!master) {
6802                if (netdev_has_upper_dev(dev, upper_dev))
6803                        return -EEXIST;
6804        } else {
6805                master_dev = netdev_master_upper_dev_get(dev);
6806                if (master_dev)
6807                        return master_dev == upper_dev ? -EEXIST : -EBUSY;
6808        }
6809
6810        ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
6811                                            &changeupper_info.info);
6812        ret = notifier_to_errno(ret);
6813        if (ret)
6814                return ret;
6815
6816        ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
6817                                                   master);
6818        if (ret)
6819                return ret;
6820
6821        ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
6822                                            &changeupper_info.info);
6823        ret = notifier_to_errno(ret);
6824        if (ret)
6825                goto rollback;
6826
6827        return 0;
6828
6829rollback:
6830        __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
6831
6832        return ret;
6833}
6834
6835/**
6836 * netdev_upper_dev_link - Add a link to the upper device
6837 * @dev: device
6838 * @upper_dev: new upper device
6839 * @extack: netlink extended ack
6840 *
6841 * Adds a link to device which is upper to this one. The caller must hold
6842 * the RTNL lock. On a failure a negative errno code is returned.
6843 * On success the reference counts are adjusted and the function
6844 * returns zero.
6845 */
6846int netdev_upper_dev_link(struct net_device *dev,
6847                          struct net_device *upper_dev,
6848                          struct netlink_ext_ack *extack)
6849{
6850        return __netdev_upper_dev_link(dev, upper_dev, false,
6851                                       NULL, NULL, extack);
6852}
6853EXPORT_SYMBOL(netdev_upper_dev_link);
6854
6855/**
6856 * netdev_master_upper_dev_link - Add a master link to the upper device
6857 * @dev: device
6858 * @upper_dev: new upper device
6859 * @upper_priv: upper device private
6860 * @upper_info: upper info to be passed down via notifier
6861 * @extack: netlink extended ack
6862 *
6863 * Adds a link to device which is upper to this one. In this case, only
6864 * one master upper device can be linked, although other non-master devices
6865 * might be linked as well. The caller must hold the RTNL lock.
6866 * On a failure a negative errno code is returned. On success the reference
6867 * counts are adjusted and the function returns zero.
6868 */
6869int netdev_master_upper_dev_link(struct net_device *dev,
6870                                 struct net_device *upper_dev,
6871                                 void *upper_priv, void *upper_info,
6872                                 struct netlink_ext_ack *extack)
6873{
6874        return __netdev_upper_dev_link(dev, upper_dev, true,
6875                                       upper_priv, upper_info, extack);
6876}
6877EXPORT_SYMBOL(netdev_master_upper_dev_link);
6878
6879/**
6880 * netdev_upper_dev_unlink - Removes a link to upper device
6881 * @dev: device
6882 * @upper_dev: new upper device
6883 *
6884 * Removes a link to device which is upper to this one. The caller must hold
6885 * the RTNL lock.
6886 */
6887void netdev_upper_dev_unlink(struct net_device *dev,
6888                             struct net_device *upper_dev)
6889{
6890        struct netdev_notifier_changeupper_info changeupper_info = {
6891                .info = {
6892                        .dev = dev,
6893                },
6894                .upper_dev = upper_dev,
6895                .linking = false,
6896        };
6897
6898        ASSERT_RTNL();
6899
6900        changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
6901
6902        call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
6903                                      &changeupper_info.info);
6904
6905        __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
6906
6907        call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
6908                                      &changeupper_info.info);
6909}
6910EXPORT_SYMBOL(netdev_upper_dev_unlink);
6911
6912/**
6913 * netdev_bonding_info_change - Dispatch event about slave change
6914 * @dev: device
6915 * @bonding_info: info to dispatch
6916 *
6917 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
6918 * The caller must hold the RTNL lock.
6919 */
6920void netdev_bonding_info_change(struct net_device *dev,
6921                                struct netdev_bonding_info *bonding_info)
6922{
6923        struct netdev_notifier_bonding_info info = {
6924                .info.dev = dev,
6925        };
6926
6927        memcpy(&info.bonding_info, bonding_info,
6928               sizeof(struct netdev_bonding_info));
6929        call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
6930                                      &info.info);
6931}
6932EXPORT_SYMBOL(netdev_bonding_info_change);
6933
6934static void netdev_adjacent_add_links(struct net_device *dev)
6935{
6936        struct netdev_adjacent *iter;
6937
6938        struct net *net = dev_net(dev);
6939
6940        list_for_each_entry(iter, &dev->adj_list.upper, list) {
6941                if (!net_eq(net, dev_net(iter->dev)))
6942                        continue;
6943                netdev_adjacent_sysfs_add(iter->dev, dev,
6944                                          &iter->dev->adj_list.lower);
6945                netdev_adjacent_sysfs_add(dev, iter->dev,
6946                                          &dev->adj_list.upper);
6947        }
6948
6949        list_for_each_entry(iter, &dev->adj_list.lower, list) {
6950                if (!net_eq(net, dev_net(iter->dev)))
6951                        continue;
6952                netdev_adjacent_sysfs_add(iter->dev, dev,
6953                                          &iter->dev->adj_list.upper);
6954                netdev_adjacent_sysfs_add(dev, iter->dev,
6955                                          &dev->adj_list.lower);
6956        }
6957}
6958
6959static void netdev_adjacent_del_links(struct net_device *dev)
6960{
6961        struct netdev_adjacent *iter;
6962
6963        struct net *net = dev_net(dev);
6964
6965        list_for_each_entry(iter, &dev->adj_list.upper, list) {
6966                if (!net_eq(net, dev_net(iter->dev)))
6967                        continue;
6968                netdev_adjacent_sysfs_del(iter->dev, dev->name,
6969                                          &iter->dev->adj_list.lower);
6970                netdev_adjacent_sysfs_del(dev, iter->dev->name,
6971                                          &dev->adj_list.upper);
6972        }
6973
6974        list_for_each_entry(iter, &dev->adj_list.lower, list) {
6975                if (!net_eq(net, dev_net(iter->dev)))
6976                        continue;
6977                netdev_adjacent_sysfs_del(iter->dev, dev->name,
6978                                          &iter->dev->adj_list.upper);
6979                netdev_adjacent_sysfs_del(dev, iter->dev->name,
6980                                          &dev->adj_list.lower);
6981        }
6982}
6983
6984void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
6985{
6986        struct netdev_adjacent *iter;
6987
6988        struct net *net = dev_net(dev);
6989
6990        list_for_each_entry(iter, &dev->adj_list.upper, list) {
6991                if (!net_eq(net, dev_net(iter->dev)))
6992                        continue;
6993                netdev_adjacent_sysfs_del(iter->dev, oldname,
6994                                          &iter->dev->adj_list.lower);
6995                netdev_adjacent_sysfs_add(iter->dev, dev,
6996                                          &iter->dev->adj_list.lower);
6997        }
6998
6999        list_for_each_entry(iter, &dev->adj_list.lower, list) {
7000                if (!net_eq(net, dev_net(iter->dev)))
7001                        continue;
7002                netdev_adjacent_sysfs_del(iter->dev, oldname,
7003                                          &iter->dev->adj_list.upper);
7004                netdev_adjacent_sysfs_add(iter->dev, dev,
7005                                          &iter->dev->adj_list.upper);
7006        }
7007}
7008
7009void *netdev_lower_dev_get_private(struct net_device *dev,
7010                                   struct net_device *lower_dev)
7011{
7012        struct netdev_adjacent *lower;
7013
7014        if (!lower_dev)
7015                return NULL;
7016        lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
7017        if (!lower)
7018                return NULL;
7019
7020        return lower->private;
7021}
7022EXPORT_SYMBOL(netdev_lower_dev_get_private);
7023
7024
7025int dev_get_nest_level(struct net_device *dev)
7026{
7027        struct net_device *lower = NULL;
7028        struct list_head *iter;
7029        int max_nest = -1;
7030        int nest;
7031
7032        ASSERT_RTNL();
7033
7034        netdev_for_each_lower_dev(dev, lower, iter) {
7035                nest = dev_get_nest_level(lower);
7036                if (max_nest < nest)
7037                        max_nest = nest;
7038        }
7039
7040        return max_nest + 1;
7041}
7042EXPORT_SYMBOL(dev_get_nest_level);
7043
7044/**
7045 * netdev_lower_change - Dispatch event about lower device state change
7046 * @lower_dev: device
7047 * @lower_state_info: state to dispatch
7048 *
7049 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
7050 * The caller must hold the RTNL lock.
7051 */
7052void netdev_lower_state_changed(struct net_device *lower_dev,
7053                                void *lower_state_info)
7054{
7055        struct netdev_notifier_changelowerstate_info changelowerstate_info = {
7056                .info.dev = lower_dev,
7057        };
7058
7059        ASSERT_RTNL();
7060        changelowerstate_info.lower_state_info = lower_state_info;
7061        call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
7062                                      &changelowerstate_info.info);
7063}
7064EXPORT_SYMBOL(netdev_lower_state_changed);
7065
7066static void dev_change_rx_flags(struct net_device *dev, int flags)
7067{
7068        const struct net_device_ops *ops = dev->netdev_ops;
7069
7070        if (ops->ndo_change_rx_flags)
7071                ops->ndo_change_rx_flags(dev, flags);
7072}
7073
7074static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
7075{
7076        unsigned int old_flags = dev->flags;
7077        kuid_t uid;
7078        kgid_t gid;
7079
7080        ASSERT_RTNL();
7081
7082        dev->flags |= IFF_PROMISC;
7083        dev->promiscuity += inc;
7084        if (dev->promiscuity == 0) {
7085                /*
7086                 * Avoid overflow.
7087                 * If inc causes overflow, untouch promisc and return error.
7088                 */
7089                if (inc < 0)
7090                        dev->flags &= ~IFF_PROMISC;
7091                else {
7092                        dev->promiscuity -= inc;
7093                        pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
7094                                dev->name);
7095                        return -EOVERFLOW;
7096                }
7097        }
7098        if (dev->flags != old_flags) {
7099                pr_info("device %s %s promiscuous mode\n",
7100                        dev->name,
7101                        dev->flags & IFF_PROMISC ? "entered" : "left");
7102                if (audit_enabled) {
7103                        current_uid_gid(&uid, &gid);
7104                        audit_log(audit_context(), GFP_ATOMIC,
7105                                  AUDIT_ANOM_PROMISCUOUS,
7106                                  "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
7107                                  dev->name, (dev->flags & IFF_PROMISC),
7108                                  (old_flags & IFF_PROMISC),
7109                                  from_kuid(&init_user_ns, audit_get_loginuid(current)),
7110                                  from_kuid(&init_user_ns, uid),
7111                                  from_kgid(&init_user_ns, gid),
7112                                  audit_get_sessionid(current));
7113                }
7114
7115                dev_change_rx_flags(dev, IFF_PROMISC);
7116        }
7117        if (notify)
7118                __dev_notify_flags(dev, old_flags, IFF_PROMISC);
7119        return 0;
7120}
7121
7122/**
7123 *      dev_set_promiscuity     - update promiscuity count on a device
7124 *      @dev: device
7125 *      @inc: modifier
7126 *
7127 *      Add or remove promiscuity from a device. While the count in the device
7128 *      remains above zero the interface remains promiscuous. Once it hits zero
7129 *      the device reverts back to normal filtering operation. A negative inc
7130 *      value is used to drop promiscuity on the device.
7131 *      Return 0 if successful or a negative errno code on error.
7132 */
7133int dev_set_promiscuity(struct net_device *dev, int inc)
7134{
7135        unsigned int old_flags = dev->flags;
7136        int err;
7137
7138        err = __dev_set_promiscuity(dev, inc, true);
7139        if (err < 0)
7140                return err;
7141        if (dev->flags != old_flags)
7142                dev_set_rx_mode(dev);
7143        return err;
7144}
7145EXPORT_SYMBOL(dev_set_promiscuity);
7146
7147static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
7148{
7149        unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
7150
7151        ASSERT_RTNL();
7152
7153        dev->flags |= IFF_ALLMULTI;
7154        dev->allmulti += inc;
7155        if (dev->allmulti == 0) {
7156                /*
7157                 * Avoid overflow.
7158                 * If inc causes overflow, untouch allmulti and return error.
7159                 */
7160                if (inc < 0)
7161                        dev->flags &= ~IFF_ALLMULTI;
7162                else {
7163                        dev->allmulti -= inc;
7164                        pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
7165                                dev->name);
7166                        return -EOVERFLOW;
7167                }
7168        }
7169        if (dev->flags ^ old_flags) {
7170                dev_change_rx_flags(dev, IFF_ALLMULTI);
7171                dev_set_rx_mode(dev);
7172                if (notify)
7173                        __dev_notify_flags(dev, old_flags,
7174                                           dev->gflags ^ old_gflags);
7175        }
7176        return 0;
7177}
7178
7179/**
7180 *      dev_set_allmulti        - update allmulti count on a device
7181 *      @dev: device
7182 *      @inc: modifier
7183 *
7184 *      Add or remove reception of all multicast frames to a device. While the
7185 *      count in the device remains above zero the interface remains listening
7186 *      to all interfaces. Once it hits zero the device reverts back to normal
7187 *      filtering operation. A negative @inc value is used to drop the counter
7188 *      when releasing a resource needing all multicasts.
7189 *      Return 0 if successful or a negative errno code on error.
7190 */
7191
7192int dev_set_allmulti(struct net_device *dev, int inc)
7193{
7194        return __dev_set_allmulti(dev, inc, true);
7195}
7196EXPORT_SYMBOL(dev_set_allmulti);
7197
7198/*
7199 *      Upload unicast and multicast address lists to device and
7200 *      configure RX filtering. When the device doesn't support unicast
7201 *      filtering it is put in promiscuous mode while unicast addresses
7202 *      are present.
7203 */
7204void __dev_set_rx_mode(struct net_device *dev)
7205{
7206        const struct net_device_ops *ops = dev->netdev_ops;
7207
7208        /* dev_open will call this function so the list will stay sane. */
7209        if (!(dev->flags&IFF_UP))
7210                return;
7211
7212        if (!netif_device_present(dev))
7213                return;
7214
7215        if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
7216                /* Unicast addresses changes may only happen under the rtnl,
7217                 * therefore calling __dev_set_promiscuity here is safe.
7218                 */
7219                if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
7220                        __dev_set_promiscuity(dev, 1, false);
7221                        dev->uc_promisc = true;
7222                } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
7223                        __dev_set_promiscuity(dev, -1, false);
7224                        dev->uc_promisc = false;
7225                }
7226        }
7227
7228        if (ops->ndo_set_rx_mode)
7229                ops->ndo_set_rx_mode(dev);
7230}
7231
7232void dev_set_rx_mode(struct net_device *dev)
7233{
7234        netif_addr_lock_bh(dev);
7235        __dev_set_rx_mode(dev);
7236        netif_addr_unlock_bh(dev);
7237}
7238
7239/**
7240 *      dev_get_flags - get flags reported to userspace
7241 *      @dev: device
7242 *
7243 *      Get the combination of flag bits exported through APIs to userspace.
7244 */
7245unsigned int dev_get_flags(const struct net_device *dev)
7246{
7247        unsigned int flags;
7248
7249        flags = (dev->flags & ~(IFF_PROMISC |
7250                                IFF_ALLMULTI |
7251                                IFF_RUNNING |
7252                                IFF_LOWER_UP |
7253                                IFF_DORMANT)) |
7254                (dev->gflags & (IFF_PROMISC |
7255                                IFF_ALLMULTI));
7256
7257        if (netif_running(dev)) {
7258                if (netif_oper_up(dev))
7259                        flags |= IFF_RUNNING;
7260                if (netif_carrier_ok(dev))
7261                        flags |= IFF_LOWER_UP;
7262                if (netif_dormant(dev))
7263                        flags |= IFF_DORMANT;
7264        }
7265
7266        return flags;
7267}
7268EXPORT_SYMBOL(dev_get_flags);
7269
7270int __dev_change_flags(struct net_device *dev, unsigned int flags,
7271                       struct netlink_ext_ack *extack)
7272{
7273        unsigned int old_flags = dev->flags;
7274        int ret;
7275
7276        ASSERT_RTNL();
7277
7278        /*
7279         *      Set the flags on our device.
7280         */
7281
7282        dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
7283                               IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
7284                               IFF_AUTOMEDIA)) |
7285                     (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
7286                                    IFF_ALLMULTI));
7287
7288        /*
7289         *      Load in the correct multicast list now the flags have changed.
7290         */
7291
7292        if ((old_flags ^ flags) & IFF_MULTICAST)
7293                dev_change_rx_flags(dev, IFF_MULTICAST);
7294
7295        dev_set_rx_mode(dev);
7296
7297        /*
7298         *      Have we downed the interface. We handle IFF_UP ourselves
7299         *      according to user attempts to set it, rather than blindly
7300         *      setting it.
7301         */
7302
7303        ret = 0;
7304        if ((old_flags ^ flags) & IFF_UP) {
7305                if (old_flags & IFF_UP)
7306                        __dev_close(dev);
7307                else
7308                        ret = __dev_open(dev, extack);
7309        }
7310
7311        if ((flags ^ dev->gflags) & IFF_PROMISC) {
7312                int inc = (flags & IFF_PROMISC) ? 1 : -1;
7313                unsigned int old_flags = dev->flags;
7314
7315                dev->gflags ^= IFF_PROMISC;
7316
7317                if (__dev_set_promiscuity(dev, inc, false) >= 0)
7318                        if (dev->flags != old_flags)
7319                                dev_set_rx_mode(dev);
7320        }
7321
7322        /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
7323         * is important. Some (broken) drivers set IFF_PROMISC, when
7324         * IFF_ALLMULTI is requested not asking us and not reporting.
7325         */
7326        if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
7327                int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
7328
7329                dev->gflags ^= IFF_ALLMULTI;
7330                __dev_set_allmulti(dev, inc, false);
7331        }
7332
7333        return ret;
7334}
7335
7336void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
7337                        unsigned int gchanges)
7338{
7339        unsigned int changes = dev->flags ^ old_flags;
7340
7341        if (gchanges)
7342                rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
7343
7344        if (changes & IFF_UP) {
7345                if (dev->flags & IFF_UP)
7346                        call_netdevice_notifiers(NETDEV_UP, dev);
7347                else
7348                        call_netdevice_notifiers(NETDEV_DOWN, dev);
7349        }
7350
7351        if (dev->flags & IFF_UP &&
7352            (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
7353                struct netdev_notifier_change_info change_info = {
7354                        .info = {
7355                                .dev = dev,
7356                        },
7357                        .flags_changed = changes,
7358                };
7359
7360                call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
7361        }
7362}
7363
7364/**
7365 *      dev_change_flags - change device settings
7366 *      @dev: device
7367 *      @flags: device state flags
7368 *      @extack: netlink extended ack
7369 *
7370 *      Change settings on device based state flags. The flags are
7371 *      in the userspace exported format.
7372 */
7373int dev_change_flags(struct net_device *dev, unsigned int flags,
7374                     struct netlink_ext_ack *extack)
7375{
7376        int ret;
7377        unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
7378
7379        ret = __dev_change_flags(dev, flags, extack);
7380        if (ret < 0)
7381                return ret;
7382
7383        changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
7384        __dev_notify_flags(dev, old_flags, changes);
7385        return ret;
7386}
7387EXPORT_SYMBOL(dev_change_flags);
7388
7389int __dev_set_mtu(struct net_device *dev, int new_mtu)
7390{
7391        const struct net_device_ops *ops = dev->netdev_ops;
7392
7393        if (ops->ndo_change_mtu)
7394                return ops->ndo_change_mtu(dev, new_mtu);
7395
7396        /* Pairs with all the lockless reads of dev->mtu in the stack */
7397        WRITE_ONCE(dev->mtu, new_mtu);
7398        return 0;
7399}
7400EXPORT_SYMBOL(__dev_set_mtu);
7401
7402int dev_validate_mtu(struct net_device *dev, int new_mtu,
7403                     struct netlink_ext_ack *extack)
7404{
7405        /* MTU must be positive, and in range */
7406        if (new_mtu < 0 || new_mtu < dev->min_mtu) {
7407                NL_SET_ERR_MSG(extack, "mtu less than device minimum");
7408                return -EINVAL;
7409        }
7410
7411        if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
7412                NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
7413                return -EINVAL;
7414        }
7415        return 0;
7416}
7417
7418/**
7419 *      dev_set_mtu_ext - Change maximum transfer unit
7420 *      @dev: device
7421 *      @new_mtu: new transfer unit
7422 *      @extack: netlink extended ack
7423 *
7424 *      Change the maximum transfer size of the network device.
7425 */
7426int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
7427                    struct netlink_ext_ack *extack)
7428{
7429        int err, orig_mtu;
7430
7431        if (new_mtu == dev->mtu)
7432                return 0;
7433
7434        err = dev_validate_mtu(dev, new_mtu, extack);
7435        if (err)
7436                return err;
7437
7438        if (!netif_device_present(dev))
7439                return -ENODEV;
7440
7441        err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
7442        err = notifier_to_errno(err);
7443        if (err)
7444                return err;
7445
7446        orig_mtu = dev->mtu;
7447        err = __dev_set_mtu(dev, new_mtu);
7448
7449        if (!err) {
7450                err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
7451                                                   orig_mtu);
7452                err = notifier_to_errno(err);
7453                if (err) {
7454                        /* setting mtu back and notifying everyone again,
7455                         * so that they have a chance to revert changes.
7456                         */
7457                        __dev_set_mtu(dev, orig_mtu);
7458                        call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
7459                                                     new_mtu);
7460                }
7461        }
7462        return err;
7463}
7464
7465int dev_set_mtu(struct net_device *dev, int new_mtu)
7466{
7467        struct netlink_ext_ack extack;
7468        int err;
7469
7470        memset(&extack, 0, sizeof(extack));
7471        err = dev_set_mtu_ext(dev, new_mtu, &extack);
7472        if (err && extack._msg)
7473                net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
7474        return err;
7475}
7476EXPORT_SYMBOL(dev_set_mtu);
7477
7478/**
7479 *      dev_change_tx_queue_len - Change TX queue length of a netdevice
7480 *      @dev: device
7481 *      @new_len: new tx queue length
7482 */
7483int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
7484{
7485        unsigned int orig_len = dev->tx_queue_len;
7486        int res;
7487
7488        if (new_len != (unsigned int)new_len)
7489                return -ERANGE;
7490
7491        if (new_len != orig_len) {
7492                dev->tx_queue_len = new_len;
7493                res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
7494                res = notifier_to_errno(res);
7495                if (res)
7496                        goto err_rollback;
7497                res = dev_qdisc_change_tx_queue_len(dev);
7498                if (res)
7499                        goto err_rollback;
7500        }
7501
7502        return 0;
7503
7504err_rollback:
7505        netdev_err(dev, "refused to change device tx_queue_len\n");
7506        dev->tx_queue_len = orig_len;
7507        return res;
7508}
7509
7510/**
7511 *      dev_set_group - Change group this device belongs to
7512 *      @dev: device
7513 *      @new_group: group this device should belong to
7514 */
7515void dev_set_group(struct net_device *dev, int new_group)
7516{
7517        dev->group = new_group;
7518}
7519EXPORT_SYMBOL(dev_set_group);
7520
7521/**
7522 *      dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
7523 *      @dev: device
7524 *      @addr: new address
7525 *      @extack: netlink extended ack
7526 */
7527int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
7528                              struct netlink_ext_ack *extack)
7529{
7530        struct netdev_notifier_pre_changeaddr_info info = {
7531                .info.dev = dev,
7532                .info.extack = extack,
7533                .dev_addr = addr,
7534        };
7535        int rc;
7536
7537        rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
7538        return notifier_to_errno(rc);
7539}
7540EXPORT_SYMBOL(dev_pre_changeaddr_notify);
7541
7542/**
7543 *      dev_set_mac_address - Change Media Access Control Address
7544 *      @dev: device
7545 *      @sa: new address
7546 *      @extack: netlink extended ack
7547 *
7548 *      Change the hardware (MAC) address of the device
7549 */
7550int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
7551                        struct netlink_ext_ack *extack)
7552{
7553        const struct net_device_ops *ops = dev->netdev_ops;
7554        int err;
7555
7556        if (!ops->ndo_set_mac_address)
7557                return -EOPNOTSUPP;
7558        if (sa->sa_family != dev->type)
7559                return -EINVAL;
7560        if (!netif_device_present(dev))
7561                return -ENODEV;
7562        err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
7563        if (err)
7564                return err;
7565        err = ops->ndo_set_mac_address(dev, sa);
7566        if (err)
7567                return err;
7568        dev->addr_assign_type = NET_ADDR_SET;
7569        call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
7570        add_device_randomness(dev->dev_addr, dev->addr_len);
7571        return 0;
7572}
7573EXPORT_SYMBOL(dev_set_mac_address);
7574
7575/**
7576 *      dev_change_carrier - Change device carrier
7577 *      @dev: device
7578 *      @new_carrier: new value
7579 *
7580 *      Change device carrier
7581 */
7582int dev_change_carrier(struct net_device *dev, bool new_carrier)
7583{
7584        const struct net_device_ops *ops = dev->netdev_ops;
7585
7586        if (!ops->ndo_change_carrier)
7587                return -EOPNOTSUPP;
7588        if (!netif_device_present(dev))
7589                return -ENODEV;
7590        return ops->ndo_change_carrier(dev, new_carrier);
7591}
7592EXPORT_SYMBOL(dev_change_carrier);
7593
7594/**
7595 *      dev_get_phys_port_id - Get device physical port ID
7596 *      @dev: device
7597 *      @ppid: port ID
7598 *
7599 *      Get device physical port ID
7600 */
7601int dev_get_phys_port_id(struct net_device *dev,
7602                         struct netdev_phys_item_id *ppid)
7603{
7604        const struct net_device_ops *ops = dev->netdev_ops;
7605
7606        if (!ops->ndo_get_phys_port_id)
7607                return -EOPNOTSUPP;
7608        return ops->ndo_get_phys_port_id(dev, ppid);
7609}
7610EXPORT_SYMBOL(dev_get_phys_port_id);
7611
7612/**
7613 *      dev_get_phys_port_name - Get device physical port name
7614 *      @dev: device
7615 *      @name: port name
7616 *      @len: limit of bytes to copy to name
7617 *
7618 *      Get device physical port name
7619 */
7620int dev_get_phys_port_name(struct net_device *dev,
7621                           char *name, size_t len)
7622{
7623        const struct net_device_ops *ops = dev->netdev_ops;
7624        int err;
7625
7626        if (ops->ndo_get_phys_port_name) {
7627                err = ops->ndo_get_phys_port_name(dev, name, len);
7628                if (err != -EOPNOTSUPP)
7629                        return err;
7630        }
7631        return devlink_compat_phys_port_name_get(dev, name, len);
7632}
7633EXPORT_SYMBOL(dev_get_phys_port_name);
7634
7635/**
7636 *      dev_get_port_parent_id - Get the device's port parent identifier
7637 *      @dev: network device
7638 *      @ppid: pointer to a storage for the port's parent identifier
7639 *      @recurse: allow/disallow recursion to lower devices
7640 *
7641 *      Get the devices's port parent identifier
7642 */
7643int dev_get_port_parent_id(struct net_device *dev,
7644                           struct netdev_phys_item_id *ppid,
7645                           bool recurse)
7646{
7647        const struct net_device_ops *ops = dev->netdev_ops;
7648        struct netdev_phys_item_id first = { };
7649        struct net_device *lower_dev;
7650        struct list_head *iter;
7651        int err;
7652
7653        if (ops->ndo_get_port_parent_id) {
7654                err = ops->ndo_get_port_parent_id(dev, ppid);
7655                if (err != -EOPNOTSUPP)
7656                        return err;
7657        }
7658
7659        err = devlink_compat_switch_id_get(dev, ppid);
7660        if (!err || err != -EOPNOTSUPP)
7661                return err;
7662
7663        if (!recurse)
7664                return -EOPNOTSUPP;
7665
7666        netdev_for_each_lower_dev(dev, lower_dev, iter) {
7667                err = dev_get_port_parent_id(lower_dev, ppid, recurse);
7668                if (err)
7669                        break;
7670                if (!first.id_len)
7671                        first = *ppid;
7672                else if (memcmp(&first, ppid, sizeof(*ppid)))
7673                        return -ENODATA;
7674        }
7675
7676        return err;
7677}
7678EXPORT_SYMBOL(dev_get_port_parent_id);
7679
7680/**
7681 *      netdev_port_same_parent_id - Indicate if two network devices have
7682 *      the same port parent identifier
7683 *      @a: first network device
7684 *      @b: second network device
7685 */
7686bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
7687{
7688        struct netdev_phys_item_id a_id = { };
7689        struct netdev_phys_item_id b_id = { };
7690
7691        if (dev_get_port_parent_id(a, &a_id, true) ||
7692            dev_get_port_parent_id(b, &b_id, true))
7693                return false;
7694
7695        return netdev_phys_item_id_same(&a_id, &b_id);
7696}
7697EXPORT_SYMBOL(netdev_port_same_parent_id);
7698
7699/**
7700 *      dev_change_proto_down - update protocol port state information
7701 *      @dev: device
7702 *      @proto_down: new value
7703 *
7704 *      This info can be used by switch drivers to set the phys state of the
7705 *      port.
7706 */
7707int dev_change_proto_down(struct net_device *dev, bool proto_down)
7708{
7709        const struct net_device_ops *ops = dev->netdev_ops;
7710
7711        if (!ops->ndo_change_proto_down)
7712                return -EOPNOTSUPP;
7713        if (!netif_device_present(dev))
7714                return -ENODEV;
7715        return ops->ndo_change_proto_down(dev, proto_down);
7716}
7717EXPORT_SYMBOL(dev_change_proto_down);
7718
7719u32 __dev_xdp_query(struct net_device *dev, bpf_op_t bpf_op,
7720                    enum bpf_netdev_command cmd)
7721{
7722        struct netdev_bpf xdp;
7723
7724        if (!bpf_op)
7725                return 0;
7726
7727        memset(&xdp, 0, sizeof(xdp));
7728        xdp.command = cmd;
7729
7730        /* Query must always succeed. */
7731        WARN_ON(bpf_op(dev, &xdp) < 0 && cmd == XDP_QUERY_PROG);
7732
7733        return xdp.prog_id;
7734}
7735
7736static int dev_xdp_install(struct net_device *dev, bpf_op_t bpf_op,
7737                           struct netlink_ext_ack *extack, u32 flags,
7738                           struct bpf_prog *prog)
7739{
7740        struct netdev_bpf xdp;
7741
7742        memset(&xdp, 0, sizeof(xdp));
7743        if (flags & XDP_FLAGS_HW_MODE)
7744                xdp.command = XDP_SETUP_PROG_HW;
7745        else
7746                xdp.command = XDP_SETUP_PROG;
7747        xdp.extack = extack;
7748        xdp.flags = flags;
7749        xdp.prog = prog;
7750
7751        return bpf_op(dev, &xdp);
7752}
7753
7754static void dev_xdp_uninstall(struct net_device *dev)
7755{
7756        struct netdev_bpf xdp;
7757        bpf_op_t ndo_bpf;
7758
7759        /* Remove generic XDP */
7760        WARN_ON(dev_xdp_install(dev, generic_xdp_install, NULL, 0, NULL));
7761
7762        /* Remove from the driver */
7763        ndo_bpf = dev->netdev_ops->ndo_bpf;
7764        if (!ndo_bpf)
7765                return;
7766
7767        memset(&xdp, 0, sizeof(xdp));
7768        xdp.command = XDP_QUERY_PROG;
7769        WARN_ON(ndo_bpf(dev, &xdp));
7770        if (xdp.prog_id)
7771                WARN_ON(dev_xdp_install(dev, ndo_bpf, NULL, xdp.prog_flags,
7772                                        NULL));
7773
7774        /* Remove HW offload */
7775        memset(&xdp, 0, sizeof(xdp));
7776        xdp.command = XDP_QUERY_PROG_HW;
7777        if (!ndo_bpf(dev, &xdp) && xdp.prog_id)
7778                WARN_ON(dev_xdp_install(dev, ndo_bpf, NULL, xdp.prog_flags,
7779                                        NULL));
7780}
7781
7782/**
7783 *      dev_change_xdp_fd - set or clear a bpf program for a device rx path
7784 *      @dev: device
7785 *      @extack: netlink extended ack
7786 *      @fd: new program fd or negative value to clear
7787 *      @flags: xdp-related flags
7788 *
7789 *      Set or clear a bpf program for a device
7790 */
7791int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
7792                      int fd, u32 flags)
7793{
7794        const struct net_device_ops *ops = dev->netdev_ops;
7795        enum bpf_netdev_command query;
7796        struct bpf_prog *prog = NULL;
7797        bpf_op_t bpf_op, bpf_chk;
7798        bool offload;
7799        int err;
7800
7801        ASSERT_RTNL();
7802
7803        rh_mark_used_feature("eBPF/xdp");
7804
7805        offload = flags & XDP_FLAGS_HW_MODE;
7806        query = offload ? XDP_QUERY_PROG_HW : XDP_QUERY_PROG;
7807
7808        bpf_op = bpf_chk = ops->ndo_bpf;
7809        if (!bpf_op && (flags & (XDP_FLAGS_DRV_MODE | XDP_FLAGS_HW_MODE))) {
7810                NL_SET_ERR_MSG(extack, "underlying driver does not support XDP in native mode");
7811                return -EOPNOTSUPP;
7812        }
7813        if (!bpf_op || (flags & XDP_FLAGS_SKB_MODE))
7814                bpf_op = generic_xdp_install;
7815        if (bpf_op == bpf_chk)
7816                bpf_chk = generic_xdp_install;
7817
7818        if (fd >= 0) {
7819                if (!offload && __dev_xdp_query(dev, bpf_chk, XDP_QUERY_PROG)) {
7820                        NL_SET_ERR_MSG(extack, "native and generic XDP can't be active at the same time");
7821                        return -EEXIST;
7822                }
7823                if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) &&
7824                    __dev_xdp_query(dev, bpf_op, query)) {
7825                        NL_SET_ERR_MSG(extack, "XDP program already attached");
7826                        return -EBUSY;
7827                }
7828
7829                prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
7830                                             bpf_op == ops->ndo_bpf);
7831                if (IS_ERR(prog))
7832                        return PTR_ERR(prog);
7833
7834                if (!offload && bpf_prog_is_dev_bound(prog->aux)) {
7835                        NL_SET_ERR_MSG(extack, "using device-bound program without HW_MODE flag is not supported");
7836                        bpf_prog_put(prog);
7837                        return -EINVAL;
7838                }
7839        }
7840
7841        err = dev_xdp_install(dev, bpf_op, extack, flags, prog);
7842        if (err < 0 && prog)
7843                bpf_prog_put(prog);
7844
7845        return err;
7846}
7847
7848/**
7849 *      dev_new_index   -       allocate an ifindex
7850 *      @net: the applicable net namespace
7851 *
7852 *      Returns a suitable unique value for a new device interface
7853 *      number.  The caller must hold the rtnl semaphore or the
7854 *      dev_base_lock to be sure it remains unique.
7855 */
7856static int dev_new_index(struct net *net)
7857{
7858        int ifindex = net->ifindex;
7859
7860        for (;;) {
7861                if (++ifindex <= 0)
7862                        ifindex = 1;
7863                if (!__dev_get_by_index(net, ifindex))
7864                        return net->ifindex = ifindex;
7865        }
7866}
7867
7868/* Delayed registration/unregisteration */
7869static LIST_HEAD(net_todo_list);
7870DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
7871
7872static void net_set_todo(struct net_device *dev)
7873{
7874        list_add_tail(&dev->todo_list, &net_todo_list);
7875        dev_net(dev)->dev_unreg_count++;
7876}
7877
7878static void rollback_registered_many(struct list_head *head)
7879{
7880        struct net_device *dev, *tmp;
7881        LIST_HEAD(close_head);
7882
7883        BUG_ON(dev_boot_phase);
7884        ASSERT_RTNL();
7885
7886        list_for_each_entry_safe(dev, tmp, head, unreg_list) {
7887                /* Some devices call without registering
7888                 * for initialization unwind. Remove those
7889                 * devices and proceed with the remaining.
7890                 */
7891                if (dev->reg_state == NETREG_UNINITIALIZED) {
7892                        pr_debug("unregister_netdevice: device %s/%p never was registered\n",
7893                                 dev->name, dev);
7894
7895                        WARN_ON(1);
7896                        list_del(&dev->unreg_list);
7897                        continue;
7898                }
7899                dev->dismantle = true;
7900                BUG_ON(dev->reg_state != NETREG_REGISTERED);
7901        }
7902
7903        /* If device is running, close it first. */
7904        list_for_each_entry(dev, head, unreg_list)
7905                list_add_tail(&dev->close_list, &close_head);
7906        dev_close_many(&close_head, true);
7907
7908        list_for_each_entry(dev, head, unreg_list) {
7909                /* And unlink it from device chain. */
7910                unlist_netdevice(dev);
7911
7912                dev->reg_state = NETREG_UNREGISTERING;
7913        }
7914        flush_all_backlogs();
7915
7916        synchronize_net();
7917
7918        list_for_each_entry(dev, head, unreg_list) {
7919                struct sk_buff *skb = NULL;
7920
7921                /* Shutdown queueing discipline. */
7922                dev_shutdown(dev);
7923
7924                dev_xdp_uninstall(dev);
7925
7926                /* Notify protocols, that we are about to destroy
7927                 * this device. They should clean all the things.
7928                 */
7929                call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
7930
7931                if (!dev->rtnl_link_ops ||
7932                    dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
7933                        skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
7934                                                     GFP_KERNEL, NULL, 0);
7935
7936                /*
7937                 *      Flush the unicast and multicast chains
7938                 */
7939                dev_uc_flush(dev);
7940                dev_mc_flush(dev);
7941
7942                if (dev->netdev_ops->ndo_uninit)
7943                        dev->netdev_ops->ndo_uninit(dev);
7944
7945                if (skb)
7946                        rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
7947
7948                /* Notifier chain MUST detach us all upper devices. */
7949                WARN_ON(netdev_has_any_upper_dev(dev));
7950                WARN_ON(netdev_has_any_lower_dev(dev));
7951
7952                /* Remove entries from kobject tree */
7953                netdev_unregister_kobject(dev);
7954#ifdef CONFIG_XPS
7955                /* Remove XPS queueing entries */
7956                netif_reset_xps_queues_gt(dev, 0);
7957#endif
7958        }
7959
7960        synchronize_net();
7961
7962        list_for_each_entry(dev, head, unreg_list)
7963                dev_put(dev);
7964}
7965
7966static void rollback_registered(struct net_device *dev)
7967{
7968        LIST_HEAD(single);
7969
7970        list_add(&dev->unreg_list, &single);
7971        rollback_registered_many(&single);
7972        list_del(&single);
7973}
7974
7975static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
7976        struct net_device *upper, netdev_features_t features)
7977{
7978        netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
7979        netdev_features_t feature;
7980        int feature_bit;
7981
7982        for_each_netdev_feature(&upper_disables, feature_bit) {
7983                feature = __NETIF_F_BIT(feature_bit);
7984                if (!(upper->wanted_features & feature)
7985                    && (features & feature)) {
7986                        netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
7987                                   &feature, upper->name);
7988                        features &= ~feature;
7989                }
7990        }
7991
7992        return features;
7993}
7994
7995static void netdev_sync_lower_features(struct net_device *upper,
7996        struct net_device *lower, netdev_features_t features)
7997{
7998        netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
7999        netdev_features_t feature;
8000        int feature_bit;
8001
8002        for_each_netdev_feature(&upper_disables, feature_bit) {
8003                feature = __NETIF_F_BIT(feature_bit);
8004                if (!(features & feature) && (lower->features & feature)) {
8005                        netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
8006                                   &feature, lower->name);
8007                        lower->wanted_features &= ~feature;
8008                        netdev_update_features(lower);
8009
8010                        if (unlikely(lower->features & feature))
8011                                netdev_WARN(upper, "failed to disable %pNF on %s!\n",
8012                                            &feature, lower->name);
8013                }
8014        }
8015}
8016
8017static netdev_features_t netdev_fix_features(struct net_device *dev,
8018        netdev_features_t features)
8019{
8020        /* Fix illegal checksum combinations */
8021        if ((features & NETIF_F_HW_CSUM) &&
8022            (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
8023                netdev_warn(dev, "mixed HW and IP checksum settings.\n");
8024                features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
8025        }
8026
8027        /* TSO requires that SG is present as well. */
8028        if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
8029                netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
8030                features &= ~NETIF_F_ALL_TSO;
8031        }
8032
8033        if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
8034                                        !(features & NETIF_F_IP_CSUM)) {
8035                netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
8036                features &= ~NETIF_F_TSO;
8037                features &= ~NETIF_F_TSO_ECN;
8038        }
8039
8040        if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
8041                                         !(features & NETIF_F_IPV6_CSUM)) {
8042                netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
8043                features &= ~NETIF_F_TSO6;
8044        }
8045
8046        /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
8047        if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
8048                features &= ~NETIF_F_TSO_MANGLEID;
8049
8050        /* TSO ECN requires that TSO is present as well. */
8051        if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
8052                features &= ~NETIF_F_TSO_ECN;
8053
8054        /* Software GSO depends on SG. */
8055        if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
8056                netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
8057                features &= ~NETIF_F_GSO;
8058        }
8059
8060        /* GSO partial features require GSO partial be set */
8061        if ((features & dev->gso_partial_features) &&
8062            !(features & NETIF_F_GSO_PARTIAL)) {
8063                netdev_dbg(dev,
8064                           "Dropping partially supported GSO features since no GSO partial.\n");
8065                features &= ~dev->gso_partial_features;
8066        }
8067
8068        if (!(features & NETIF_F_RXCSUM)) {
8069                /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
8070                 * successfully merged by hardware must also have the
8071                 * checksum verified by hardware.  If the user does not
8072                 * want to enable RXCSUM, logically, we should disable GRO_HW.
8073                 */
8074                if (features & NETIF_F_GRO_HW) {
8075                        netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
8076                        features &= ~NETIF_F_GRO_HW;
8077                }
8078        }
8079
8080        /* LRO/HW-GRO features cannot be combined with RX-FCS */
8081        if (features & NETIF_F_RXFCS) {
8082                if (features & NETIF_F_LRO) {
8083                        netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
8084                        features &= ~NETIF_F_LRO;
8085                }
8086
8087                if (features & NETIF_F_GRO_HW) {
8088                        netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
8089                        features &= ~NETIF_F_GRO_HW;
8090                }
8091        }
8092
8093        return features;
8094}
8095
8096int __netdev_update_features(struct net_device *dev)
8097{
8098        struct net_device *upper, *lower;
8099        netdev_features_t features;
8100        struct list_head *iter;
8101        int err = -1;
8102
8103        ASSERT_RTNL();
8104
8105        features = netdev_get_wanted_features(dev);
8106
8107        if (dev->netdev_ops->ndo_fix_features)
8108                features = dev->netdev_ops->ndo_fix_features(dev, features);
8109
8110        /* driver might be less strict about feature dependencies */
8111        features = netdev_fix_features(dev, features);
8112
8113        /* some features can't be enabled if they're off an an upper device */
8114        netdev_for_each_upper_dev_rcu(dev, upper, iter)
8115                features = netdev_sync_upper_features(dev, upper, features);
8116
8117        if (dev->features == features)
8118                goto sync_lower;
8119
8120        netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
8121                &dev->features, &features);
8122
8123        if (dev->netdev_ops->ndo_set_features)
8124                err = dev->netdev_ops->ndo_set_features(dev, features);
8125        else
8126                err = 0;
8127
8128        if (unlikely(err < 0)) {
8129                netdev_err(dev,
8130                        "set_features() failed (%d); wanted %pNF, left %pNF\n",
8131                        err, &features, &dev->features);
8132                /* return non-0 since some features might have changed and
8133                 * it's better to fire a spurious notification than miss it
8134                 */
8135                return -1;
8136        }
8137
8138sync_lower:
8139        /* some features must be disabled on lower devices when disabled
8140         * on an upper device (think: bonding master or bridge)
8141         */
8142        netdev_for_each_lower_dev(dev, lower, iter)
8143                netdev_sync_lower_features(dev, lower, features);
8144
8145        if (!err) {
8146                netdev_features_t diff = features ^ dev->features;
8147
8148                if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
8149                        /* udp_tunnel_{get,drop}_rx_info both need
8150                         * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
8151                         * device, or they won't do anything.
8152                         * Thus we need to update dev->features
8153                         * *before* calling udp_tunnel_get_rx_info,
8154                         * but *after* calling udp_tunnel_drop_rx_info.
8155                         */
8156                        if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
8157                                dev->features = features;
8158                                udp_tunnel_get_rx_info(dev);
8159                        } else {
8160                                udp_tunnel_drop_rx_info(dev);
8161                        }
8162                }
8163
8164                if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
8165                        if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
8166                                dev->features = features;
8167                                err |= vlan_get_rx_ctag_filter_info(dev);
8168                        } else {
8169                                vlan_drop_rx_ctag_filter_info(dev);
8170                        }
8171                }
8172
8173                if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
8174                        if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
8175                                dev->features = features;
8176                                err |= vlan_get_rx_stag_filter_info(dev);
8177                        } else {
8178                                vlan_drop_rx_stag_filter_info(dev);
8179                        }
8180                }
8181
8182                dev->features = features;
8183        }
8184
8185        return err < 0 ? 0 : 1;
8186}
8187
8188/**
8189 *      netdev_update_features - recalculate device features
8190 *      @dev: the device to check
8191 *
8192 *      Recalculate dev->features set and send notifications if it
8193 *      has changed. Should be called after driver or hardware dependent
8194 *      conditions might have changed that influence the features.
8195 */
8196void netdev_update_features(struct net_device *dev)
8197{
8198        if (__netdev_update_features(dev))
8199                netdev_features_change(dev);
8200}
8201EXPORT_SYMBOL(netdev_update_features);
8202
8203/**
8204 *      netdev_change_features - recalculate device features
8205 *      @dev: the device to check
8206 *
8207 *      Recalculate dev->features set and send notifications even
8208 *      if they have not changed. Should be called instead of
8209 *      netdev_update_features() if also dev->vlan_features might
8210 *      have changed to allow the changes to be propagated to stacked
8211 *      VLAN devices.
8212 */
8213void netdev_change_features(struct net_device *dev)
8214{
8215        __netdev_update_features(dev);
8216        netdev_features_change(dev);
8217}
8218EXPORT_SYMBOL(netdev_change_features);
8219
8220/**
8221 *      netif_stacked_transfer_operstate -      transfer operstate
8222 *      @rootdev: the root or lower level device to transfer state from
8223 *      @dev: the device to transfer operstate to
8224 *
8225 *      Transfer operational state from root to device. This is normally
8226 *      called when a stacking relationship exists between the root
8227 *      device and the device(a leaf device).
8228 */
8229void netif_stacked_transfer_operstate(const struct net_device *rootdev,
8230                                        struct net_device *dev)
8231{
8232        if (rootdev->operstate == IF_OPER_DORMANT)
8233                netif_dormant_on(dev);
8234        else
8235                netif_dormant_off(dev);
8236
8237        if (netif_carrier_ok(rootdev))
8238                netif_carrier_on(dev);
8239        else
8240                netif_carrier_off(dev);
8241}
8242EXPORT_SYMBOL(netif_stacked_transfer_operstate);
8243
8244static int netif_alloc_rx_queues(struct net_device *dev)
8245{
8246        unsigned int i, count = dev->num_rx_queues;
8247        struct netdev_rx_queue *rx;
8248        size_t sz = count * sizeof(*rx);
8249        int err = 0;
8250
8251        BUG_ON(count < 1);
8252
8253        rx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
8254        if (!rx)
8255                return -ENOMEM;
8256
8257        dev->_rx = rx;
8258
8259        for (i = 0; i < count; i++) {
8260                rx[i].dev = dev;
8261
8262                /* XDP RX-queue setup */
8263                err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i);
8264                if (err < 0)
8265                        goto err_rxq_info;
8266        }
8267        return 0;
8268
8269err_rxq_info:
8270        /* Rollback successful reg's and free other resources */
8271        while (i--)
8272                xdp_rxq_info_unreg(&rx[i].xdp_rxq);
8273        kvfree(dev->_rx);
8274        dev->_rx = NULL;
8275        return err;
8276}
8277
8278static void netif_free_rx_queues(struct net_device *dev)
8279{
8280        unsigned int i, count = dev->num_rx_queues;
8281
8282        /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
8283        if (!dev->_rx)
8284                return;
8285
8286        for (i = 0; i < count; i++)
8287                xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
8288
8289        kvfree(dev->_rx);
8290}
8291
8292static void netdev_init_one_queue(struct net_device *dev,
8293                                  struct netdev_queue *queue, void *_unused)
8294{
8295        /* Initialize queue lock */
8296        spin_lock_init(&queue->_xmit_lock);
8297        netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
8298        queue->xmit_lock_owner = -1;
8299        netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
8300        queue->dev = dev;
8301#ifdef CONFIG_BQL
8302        dql_init(&queue->dql, HZ);
8303#endif
8304}
8305
8306static void netif_free_tx_queues(struct net_device *dev)
8307{
8308        kvfree(dev->_tx);
8309}
8310
8311static int netif_alloc_netdev_queues(struct net_device *dev)
8312{
8313        unsigned int count = dev->num_tx_queues;
8314        struct netdev_queue *tx;
8315        size_t sz = count * sizeof(*tx);
8316
8317        if (count < 1 || count > 0xffff)
8318                return -EINVAL;
8319
8320        tx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
8321        if (!tx)
8322                return -ENOMEM;
8323
8324        dev->_tx = tx;
8325
8326        netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
8327        spin_lock_init(&dev->tx_global_lock);
8328
8329        return 0;
8330}
8331
8332void netif_tx_stop_all_queues(struct net_device *dev)
8333{
8334        unsigned int i;
8335
8336        for (i = 0; i < dev->num_tx_queues; i++) {
8337                struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
8338
8339                netif_tx_stop_queue(txq);
8340        }
8341}
8342EXPORT_SYMBOL(netif_tx_stop_all_queues);
8343
8344/**
8345 *      register_netdevice      - register a network device
8346 *      @dev: device to register
8347 *
8348 *      Take a completed network device structure and add it to the kernel
8349 *      interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
8350 *      chain. 0 is returned on success. A negative errno code is returned
8351 *      on a failure to set up the device, or if the name is a duplicate.
8352 *
8353 *      Callers must hold the rtnl semaphore. You may want
8354 *      register_netdev() instead of this.
8355 *
8356 *      BUGS:
8357 *      The locking appears insufficient to guarantee two parallel registers
8358 *      will not get the same name.
8359 */
8360
8361int register_netdevice(struct net_device *dev)
8362{
8363        int ret;
8364        struct net *net = dev_net(dev);
8365
8366        BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
8367                     NETDEV_FEATURE_COUNT);
8368        BUG_ON(dev_boot_phase);
8369        ASSERT_RTNL();
8370
8371        might_sleep();
8372
8373        /* When net_device's are persistent, this will be fatal. */
8374        BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
8375        BUG_ON(!net);
8376
8377        spin_lock_init(&dev->addr_list_lock);
8378        netdev_set_addr_lockdep_class(dev);
8379
8380        ret = dev_get_valid_name(net, dev, dev->name);
8381        if (ret < 0)
8382                goto out;
8383
8384        /* Init, if this function is available */
8385        if (dev->netdev_ops->ndo_init) {
8386                ret = dev->netdev_ops->ndo_init(dev);
8387                if (ret) {
8388                        if (ret > 0)
8389                                ret = -EIO;
8390                        goto out;
8391                }
8392        }
8393
8394        if (((dev->hw_features | dev->features) &
8395             NETIF_F_HW_VLAN_CTAG_FILTER) &&
8396            (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
8397             !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
8398                netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
8399                ret = -EINVAL;
8400                goto err_uninit;
8401        }
8402
8403        ret = -EBUSY;
8404        if (!dev->ifindex)
8405                dev->ifindex = dev_new_index(net);
8406        else if (__dev_get_by_index(net, dev->ifindex))
8407                goto err_uninit;
8408
8409        /* Transfer changeable features to wanted_features and enable
8410         * software offloads (GSO and GRO).
8411         */
8412        dev->hw_features |= NETIF_F_SOFT_FEATURES;
8413        dev->features |= NETIF_F_SOFT_FEATURES;
8414
8415        if (dev->netdev_ops->ndo_udp_tunnel_add) {
8416                dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
8417                dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
8418        }
8419
8420        dev->wanted_features = dev->features & dev->hw_features;
8421
8422        if (!(dev->flags & IFF_LOOPBACK))
8423                dev->hw_features |= NETIF_F_NOCACHE_COPY;
8424
8425        /* If IPv4 TCP segmentation offload is supported we should also
8426         * allow the device to enable segmenting the frame with the option
8427         * of ignoring a static IP ID value.  This doesn't enable the
8428         * feature itself but allows the user to enable it later.
8429         */
8430        if (dev->hw_features & NETIF_F_TSO)
8431                dev->hw_features |= NETIF_F_TSO_MANGLEID;
8432        if (dev->vlan_features & NETIF_F_TSO)
8433                dev->vlan_features |= NETIF_F_TSO_MANGLEID;
8434        if (dev->mpls_features & NETIF_F_TSO)
8435                dev->mpls_features |= NETIF_F_TSO_MANGLEID;
8436        if (dev->hw_enc_features & NETIF_F_TSO)
8437                dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
8438
8439        /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
8440         */
8441        dev->vlan_features |= NETIF_F_HIGHDMA;
8442
8443        /* Make NETIF_F_SG inheritable to tunnel devices.
8444         */
8445        dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
8446
8447        /* Make NETIF_F_SG inheritable to MPLS.
8448         */
8449        dev->mpls_features |= NETIF_F_SG;
8450
8451        ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
8452        ret = notifier_to_errno(ret);
8453        if (ret)
8454                goto err_uninit;
8455
8456        ret = netdev_register_kobject(dev);
8457        if (ret)
8458                goto err_uninit;
8459        dev->reg_state = NETREG_REGISTERED;
8460
8461        __netdev_update_features(dev);
8462
8463        /*
8464         *      Default initial state at registry is that the
8465         *      device is present.
8466         */
8467
8468        set_bit(__LINK_STATE_PRESENT, &dev->state);
8469
8470        linkwatch_init_dev(dev);
8471
8472        dev_init_scheduler(dev);
8473        dev_hold(dev);
8474        list_netdevice(dev);
8475        add_device_randomness(dev->dev_addr, dev->addr_len);
8476
8477        /* If the device has permanent device address, driver should
8478         * set dev_addr and also addr_assign_type should be set to
8479         * NET_ADDR_PERM (default value).
8480         */
8481        if (dev->addr_assign_type == NET_ADDR_PERM)
8482                memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
8483
8484        /* Notify protocols, that a new device appeared. */
8485        ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
8486        ret = notifier_to_errno(ret);
8487        if (ret) {
8488                rollback_registered(dev);
8489                rcu_barrier();
8490
8491                dev->reg_state = NETREG_UNREGISTERED;
8492        }
8493        /*
8494         *      Prevent userspace races by waiting until the network
8495         *      device is fully setup before sending notifications.
8496         */
8497        if (!dev->rtnl_link_ops ||
8498            dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
8499                rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
8500
8501out:
8502        return ret;
8503
8504err_uninit:
8505        if (dev->netdev_ops->ndo_uninit)
8506                dev->netdev_ops->ndo_uninit(dev);
8507        if (dev->priv_destructor)
8508                dev->priv_destructor(dev);
8509        goto out;
8510}
8511EXPORT_SYMBOL(register_netdevice);
8512
8513/**
8514 *      init_dummy_netdev       - init a dummy network device for NAPI
8515 *      @dev: device to init
8516 *
8517 *      This takes a network device structure and initialize the minimum
8518 *      amount of fields so it can be used to schedule NAPI polls without
8519 *      registering a full blown interface. This is to be used by drivers
8520 *      that need to tie several hardware interfaces to a single NAPI
8521 *      poll scheduler due to HW limitations.
8522 */
8523int init_dummy_netdev(struct net_device *dev)
8524{
8525        /* Clear everything. Note we don't initialize spinlocks
8526         * are they aren't supposed to be taken by any of the
8527         * NAPI code and this dummy netdev is supposed to be
8528         * only ever used for NAPI polls
8529         */
8530        memset(dev, 0, sizeof(struct net_device));
8531
8532        /* make sure we BUG if trying to hit standard
8533         * register/unregister code path
8534         */
8535        dev->reg_state = NETREG_DUMMY;
8536
8537        /* NAPI wants this */
8538        INIT_LIST_HEAD(&dev->napi_list);
8539
8540        /* a dummy interface is started by default */
8541        set_bit(__LINK_STATE_PRESENT, &dev->state);
8542        set_bit(__LINK_STATE_START, &dev->state);
8543
8544        /* napi_busy_loop stats accounting wants this */
8545        dev_net_set(dev, &init_net);
8546
8547        /* Note : We dont allocate pcpu_refcnt for dummy devices,
8548         * because users of this 'device' dont need to change
8549         * its refcount.
8550         */
8551
8552        return 0;
8553}
8554EXPORT_SYMBOL_GPL(init_dummy_netdev);
8555
8556
8557/**
8558 *      register_netdev - register a network device
8559 *      @dev: device to register
8560 *
8561 *      Take a completed network device structure and add it to the kernel
8562 *      interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
8563 *      chain. 0 is returned on success. A negative errno code is returned
8564 *      on a failure to set up the device, or if the name is a duplicate.
8565 *
8566 *      This is a wrapper around register_netdevice that takes the rtnl semaphore
8567 *      and expands the device name if you passed a format string to
8568 *      alloc_netdev.
8569 */
8570int register_netdev(struct net_device *dev)
8571{
8572        int err;
8573
8574        if (rtnl_lock_killable())
8575                return -EINTR;
8576        err = register_netdevice(dev);
8577        rtnl_unlock();
8578        return err;
8579}
8580EXPORT_SYMBOL(register_netdev);
8581
8582int netdev_refcnt_read(const struct net_device *dev)
8583{
8584        int i, refcnt = 0;
8585
8586        for_each_possible_cpu(i)
8587                refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
8588        return refcnt;
8589}
8590EXPORT_SYMBOL(netdev_refcnt_read);
8591
8592/**
8593 * netdev_wait_allrefs - wait until all references are gone.
8594 * @dev: target net_device
8595 *
8596 * This is called when unregistering network devices.
8597 *
8598 * Any protocol or device that holds a reference should register
8599 * for netdevice notification, and cleanup and put back the
8600 * reference if they receive an UNREGISTER event.
8601 * We can get stuck here if buggy protocols don't correctly
8602 * call dev_put.
8603 */
8604static void netdev_wait_allrefs(struct net_device *dev)
8605{
8606        unsigned long rebroadcast_time, warning_time;
8607        int refcnt;
8608
8609        linkwatch_forget_dev(dev);
8610
8611        rebroadcast_time = warning_time = jiffies;
8612        refcnt = netdev_refcnt_read(dev);
8613
8614        while (refcnt != 0) {
8615                if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
8616                        rtnl_lock();
8617
8618                        /* Rebroadcast unregister notification */
8619                        call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
8620
8621                        __rtnl_unlock();
8622                        rcu_barrier();
8623                        rtnl_lock();
8624
8625                        if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
8626                                     &dev->state)) {
8627                                /* We must not have linkwatch events
8628                                 * pending on unregister. If this
8629                                 * happens, we simply run the queue
8630                                 * unscheduled, resulting in a noop
8631                                 * for this device.
8632                                 */
8633                                linkwatch_run_queue();
8634                        }
8635
8636                        __rtnl_unlock();
8637
8638                        rebroadcast_time = jiffies;
8639                }
8640
8641                msleep(250);
8642
8643                refcnt = netdev_refcnt_read(dev);
8644
8645                if (refcnt && time_after(jiffies, warning_time + 10 * HZ)) {
8646                        pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
8647                                 dev->name, refcnt);
8648                        warning_time = jiffies;
8649                }
8650        }
8651}
8652
8653/* The sequence is:
8654 *
8655 *      rtnl_lock();
8656 *      ...
8657 *      register_netdevice(x1);
8658 *      register_netdevice(x2);
8659 *      ...
8660 *      unregister_netdevice(y1);
8661 *      unregister_netdevice(y2);
8662 *      ...
8663 *      rtnl_unlock();
8664 *      free_netdev(y1);
8665 *      free_netdev(y2);
8666 *
8667 * We are invoked by rtnl_unlock().
8668 * This allows us to deal with problems:
8669 * 1) We can delete sysfs objects which invoke hotplug
8670 *    without deadlocking with linkwatch via keventd.
8671 * 2) Since we run with the RTNL semaphore not held, we can sleep
8672 *    safely in order to wait for the netdev refcnt to drop to zero.
8673 *
8674 * We must not return until all unregister events added during
8675 * the interval the lock was held have been completed.
8676 */
8677void netdev_run_todo(void)
8678{
8679        struct list_head list;
8680
8681        /* Snapshot list, allow later requests */
8682        list_replace_init(&net_todo_list, &list);
8683
8684        __rtnl_unlock();
8685
8686
8687        /* Wait for rcu callbacks to finish before next phase */
8688        if (!list_empty(&list))
8689                rcu_barrier();
8690
8691        while (!list_empty(&list)) {
8692                struct net_device *dev
8693                        = list_first_entry(&list, struct net_device, todo_list);
8694                list_del(&dev->todo_list);
8695
8696                if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
8697                        pr_err("network todo '%s' but state %d\n",
8698                               dev->name, dev->reg_state);
8699                        dump_stack();
8700                        continue;
8701                }
8702
8703                dev->reg_state = NETREG_UNREGISTERED;
8704
8705                netdev_wait_allrefs(dev);
8706
8707                /* paranoia */
8708                BUG_ON(netdev_refcnt_read(dev));
8709                BUG_ON(!list_empty(&dev->ptype_all));
8710                BUG_ON(!list_empty(&dev->ptype_specific));
8711                WARN_ON(rcu_access_pointer(dev->ip_ptr));
8712                WARN_ON(rcu_access_pointer(dev->ip6_ptr));
8713#if IS_ENABLED(CONFIG_DECNET)
8714                WARN_ON(dev->dn_ptr);
8715#endif
8716                if (dev->priv_destructor)
8717                        dev->priv_destructor(dev);
8718                if (dev->needs_free_netdev)
8719                        free_netdev(dev);
8720
8721                /* Report a network device has been unregistered */
8722                rtnl_lock();
8723                dev_net(dev)->dev_unreg_count--;
8724                __rtnl_unlock();
8725                wake_up(&netdev_unregistering_wq);
8726
8727                /* Free network device */
8728                kobject_put(&dev->dev.kobj);
8729        }
8730}
8731
8732/* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
8733 * all the same fields in the same order as net_device_stats, with only
8734 * the type differing, but rtnl_link_stats64 may have additional fields
8735 * at the end for newer counters.
8736 */
8737void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
8738                             const struct net_device_stats *netdev_stats)
8739{
8740#if BITS_PER_LONG == 64
8741        BUILD_BUG_ON(sizeof_rtnl_link_stats64 < sizeof(*netdev_stats));
8742        memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
8743        /* zero out counters that only exist in rtnl_link_stats64 */
8744        memset((char *)stats64 + sizeof(*netdev_stats), 0,
8745               sizeof_rtnl_link_stats64 - sizeof(*netdev_stats));
8746#else
8747        size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
8748        const unsigned long *src = (const unsigned long *)netdev_stats;
8749        u64 *dst = (u64 *)stats64;
8750
8751        BUILD_BUG_ON(n > sizeof_rtnl_link_stats64 / sizeof(u64));
8752        for (i = 0; i < n; i++)
8753                dst[i] = src[i];
8754        /* zero out counters that only exist in rtnl_link_stats64 */
8755        memset((char *)stats64 + n * sizeof(u64), 0,
8756               sizeof_rtnl_link_stats64 - n * sizeof(u64));
8757#endif
8758}
8759EXPORT_SYMBOL(netdev_stats_to_stats64);
8760
8761/**
8762 *      dev_get_stats   - get network device statistics
8763 *      @dev: device to get statistics from
8764 *      @storage: place to store stats
8765 *
8766 *      Get network statistics from device. Return @storage.
8767 *      The device driver may provide its own method by setting
8768 *      dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
8769 *      otherwise the internal statistics structure is used.
8770 */
8771struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
8772                                        struct rtnl_link_stats64 *storage)
8773{
8774        const struct net_device_ops *ops = dev->netdev_ops;
8775
8776        if (ops->ndo_get_stats64) {
8777                memset(storage, 0, sizeof(*storage));
8778                ops->ndo_get_stats64(dev, storage);
8779        } else if (ops->ndo_get_stats) {
8780                netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
8781        } else {
8782                netdev_stats_to_stats64(storage, &dev->stats);
8783        }
8784        storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
8785        storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
8786        storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
8787        return storage;
8788}
8789EXPORT_SYMBOL(dev_get_stats);
8790
8791struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
8792{
8793        struct netdev_queue *queue = dev_ingress_queue(dev);
8794
8795#ifdef CONFIG_NET_CLS_ACT
8796        if (queue)
8797                return queue;
8798        queue = kzalloc(sizeof(*queue), GFP_KERNEL);
8799        if (!queue)
8800                return NULL;
8801        netdev_init_one_queue(dev, queue, NULL);
8802        RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
8803        queue->qdisc_sleeping = &noop_qdisc;
8804        rcu_assign_pointer(dev->ingress_queue, queue);
8805#endif
8806        return queue;
8807}
8808
8809static const struct ethtool_ops default_ethtool_ops;
8810
8811void netdev_set_default_ethtool_ops(struct net_device *dev,
8812                                    const struct ethtool_ops *ops)
8813{
8814        if (dev->ethtool_ops == &default_ethtool_ops)
8815                dev->ethtool_ops = ops;
8816}
8817EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
8818
8819void netdev_freemem(struct net_device *dev)
8820{
8821        char *addr = (char *)dev - dev->padded;
8822
8823        kvfree(addr);
8824}
8825
8826/**
8827 * alloc_netdev_mqs - allocate network device
8828 * @sizeof_priv: size of private data to allocate space for
8829 * @name: device name format string
8830 * @name_assign_type: origin of device name
8831 * @setup: callback to initialize device
8832 * @txqs: the number of TX subqueues to allocate
8833 * @rxqs: the number of RX subqueues to allocate
8834 *
8835 * Allocates a struct net_device with private data area for driver use
8836 * and performs basic initialization.  Also allocates subqueue structs
8837 * for each queue on the device.
8838 */
8839struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
8840                unsigned char name_assign_type,
8841                void (*setup)(struct net_device *),
8842                unsigned int txqs, unsigned int rxqs)
8843{
8844        struct net_device *dev;
8845        unsigned int alloc_size;
8846        struct net_device *p;
8847
8848        BUG_ON(strlen(name) >= sizeof(dev->name));
8849
8850        if (txqs < 1) {
8851                pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
8852                return NULL;
8853        }
8854
8855        if (rxqs < 1) {
8856                pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
8857                return NULL;
8858        }
8859
8860        alloc_size = sizeof(struct net_device);
8861        if (sizeof_priv) {
8862                /* ensure 32-byte alignment of private area */
8863                alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
8864                alloc_size += sizeof_priv;
8865        }
8866        /* ensure 32-byte alignment of whole construct */
8867        alloc_size += NETDEV_ALIGN - 1;
8868
8869        p = kvzalloc(alloc_size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
8870        if (!p)
8871                return NULL;
8872
8873        dev = PTR_ALIGN(p, NETDEV_ALIGN);
8874        dev->padded = (char *)dev - (char *)p;
8875
8876        dev->pcpu_refcnt = alloc_percpu(int);
8877        if (!dev->pcpu_refcnt)
8878                goto free_dev;
8879
8880        if (dev_addr_init(dev))
8881                goto free_pcpu;
8882
8883        dev_mc_init(dev);
8884        dev_uc_init(dev);
8885
8886        dev_net_set(dev, &init_net);
8887
8888        dev->gso_max_size = GSO_MAX_SIZE;
8889        dev->gso_max_segs = GSO_MAX_SEGS;
8890
8891        INIT_LIST_HEAD(&dev->napi_list);
8892        INIT_LIST_HEAD(&dev->unreg_list);
8893        INIT_LIST_HEAD(&dev->close_list);
8894        INIT_LIST_HEAD(&dev->link_watch_list);
8895        INIT_LIST_HEAD(&dev->adj_list.upper);
8896        INIT_LIST_HEAD(&dev->adj_list.lower);
8897        INIT_LIST_HEAD(&dev->ptype_all);
8898        INIT_LIST_HEAD(&dev->ptype_specific);
8899#ifdef CONFIG_NET_SCHED
8900        hash_init(dev->qdisc_hash);
8901#endif
8902        dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
8903        setup(dev);
8904
8905        if (!dev->tx_queue_len) {
8906                dev->priv_flags |= IFF_NO_QUEUE;
8907                dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
8908        }
8909
8910        dev->num_tx_queues = txqs;
8911        dev->real_num_tx_queues = txqs;
8912        if (netif_alloc_netdev_queues(dev))
8913                goto free_all;
8914
8915        dev->num_rx_queues = rxqs;
8916        dev->real_num_rx_queues = rxqs;
8917        if (netif_alloc_rx_queues(dev))
8918                goto free_all;
8919
8920        strcpy(dev->name, name);
8921        dev->name_assign_type = name_assign_type;
8922        dev->group = INIT_NETDEV_GROUP;
8923        if (!dev->ethtool_ops)
8924                dev->ethtool_ops = &default_ethtool_ops;
8925
8926        nf_hook_ingress_init(dev);
8927
8928        return dev;
8929
8930free_all:
8931        free_netdev(dev);
8932        return NULL;
8933
8934free_pcpu:
8935        free_percpu(dev->pcpu_refcnt);
8936free_dev:
8937        netdev_freemem(dev);
8938        return NULL;
8939}
8940EXPORT_SYMBOL(alloc_netdev_mqs);
8941
8942/**
8943 * free_netdev - free network device
8944 * @dev: device
8945 *
8946 * This function does the last stage of destroying an allocated device
8947 * interface. The reference to the device object is released. If this
8948 * is the last reference then it will be freed.Must be called in process
8949 * context.
8950 */
8951void free_netdev(struct net_device *dev)
8952{
8953        struct napi_struct *p, *n;
8954
8955        might_sleep();
8956        netif_free_tx_queues(dev);
8957        netif_free_rx_queues(dev);
8958
8959        kfree(rcu_dereference_protected(dev->ingress_queue, 1));
8960
8961        /* Flush device addresses */
8962        dev_addr_flush(dev);
8963
8964        list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
8965                netif_napi_del(p);
8966
8967        free_percpu(dev->pcpu_refcnt);
8968        dev->pcpu_refcnt = NULL;
8969
8970        /*  Compatibility with error handling in drivers */
8971        if (dev->reg_state == NETREG_UNINITIALIZED) {
8972                netdev_freemem(dev);
8973                return;
8974        }
8975
8976        BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
8977        dev->reg_state = NETREG_RELEASED;
8978
8979        /* will free via device release */
8980        put_device(&dev->dev);
8981}
8982EXPORT_SYMBOL(free_netdev);
8983
8984/**
8985 *      synchronize_net -  Synchronize with packet receive processing
8986 *
8987 *      Wait for packets currently being received to be done.
8988 *      Does not block later packets from starting.
8989 */
8990void synchronize_net(void)
8991{
8992        might_sleep();
8993        if (rtnl_is_locked())
8994                synchronize_rcu_expedited();
8995        else
8996                synchronize_rcu();
8997}
8998EXPORT_SYMBOL(synchronize_net);
8999
9000/**
9001 *      unregister_netdevice_queue - remove device from the kernel
9002 *      @dev: device
9003 *      @head: list
9004 *
9005 *      This function shuts down a device interface and removes it
9006 *      from the kernel tables.
9007 *      If head not NULL, device is queued to be unregistered later.
9008 *
9009 *      Callers must hold the rtnl semaphore.  You may want
9010 *      unregister_netdev() instead of this.
9011 */
9012
9013void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
9014{
9015        ASSERT_RTNL();
9016
9017        if (head) {
9018                list_move_tail(&dev->unreg_list, head);
9019        } else {
9020                rollback_registered(dev);
9021                /* Finish processing unregister after unlock */
9022                net_set_todo(dev);
9023        }
9024}
9025EXPORT_SYMBOL(unregister_netdevice_queue);
9026
9027/**
9028 *      unregister_netdevice_many - unregister many devices
9029 *      @head: list of devices
9030 *
9031 *  Note: As most callers use a stack allocated list_head,
9032 *  we force a list_del() to make sure stack wont be corrupted later.
9033 */
9034void unregister_netdevice_many(struct list_head *head)
9035{
9036        struct net_device *dev;
9037
9038        if (!list_empty(head)) {
9039                rollback_registered_many(head);
9040                list_for_each_entry(dev, head, unreg_list)
9041                        net_set_todo(dev);
9042                list_del(head);
9043        }
9044}
9045EXPORT_SYMBOL(unregister_netdevice_many);
9046
9047/**
9048 *      unregister_netdev - remove device from the kernel
9049 *      @dev: device
9050 *
9051 *      This function shuts down a device interface and removes it
9052 *      from the kernel tables.
9053 *
9054 *      This is just a wrapper for unregister_netdevice that takes
9055 *      the rtnl semaphore.  In general you want to use this and not
9056 *      unregister_netdevice.
9057 */
9058void unregister_netdev(struct net_device *dev)
9059{
9060        rtnl_lock();
9061        unregister_netdevice(dev);
9062        rtnl_unlock();
9063}
9064EXPORT_SYMBOL(unregister_netdev);
9065
9066/**
9067 *      dev_change_net_namespace - move device to different nethost namespace
9068 *      @dev: device
9069 *      @net: network namespace
9070 *      @pat: If not NULL name pattern to try if the current device name
9071 *            is already taken in the destination network namespace.
9072 *
9073 *      This function shuts down a device interface and moves it
9074 *      to a new network namespace. On success 0 is returned, on
9075 *      a failure a netagive errno code is returned.
9076 *
9077 *      Callers must hold the rtnl semaphore.
9078 */
9079
9080int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
9081{
9082        int err, new_nsid, new_ifindex;
9083
9084        ASSERT_RTNL();
9085
9086        /* Don't allow namespace local devices to be moved. */
9087        err = -EINVAL;
9088        if (dev->features & NETIF_F_NETNS_LOCAL)
9089                goto out;
9090
9091        /* Ensure the device has been registrered */
9092        if (dev->reg_state != NETREG_REGISTERED)
9093                goto out;
9094
9095        /* Get out if there is nothing todo */
9096        err = 0;
9097        if (net_eq(dev_net(dev), net))
9098                goto out;
9099
9100        /* Pick the destination device name, and ensure
9101         * we can use it in the destination network namespace.
9102         */
9103        err = -EEXIST;
9104        if (__dev_get_by_name(net, dev->name)) {
9105                /* We get here if we can't use the current device name */
9106                if (!pat)
9107                        goto out;
9108                err = dev_get_valid_name(net, dev, pat);
9109                if (err < 0)
9110                        goto out;
9111        }
9112
9113        /*
9114         * And now a mini version of register_netdevice unregister_netdevice.
9115         */
9116
9117        /* If device is running close it first. */
9118        dev_close(dev);
9119
9120        /* And unlink it from device chain */
9121        unlist_netdevice(dev);
9122
9123        synchronize_net();
9124
9125        /* Shutdown queueing discipline. */
9126        dev_shutdown(dev);
9127
9128        /* Notify protocols, that we are about to destroy
9129         * this device. They should clean all the things.
9130         *
9131         * Note that dev->reg_state stays at NETREG_REGISTERED.
9132         * This is wanted because this way 8021q and macvlan know
9133         * the device is just moving and can keep their slaves up.
9134         */
9135        call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
9136        rcu_barrier();
9137
9138        new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
9139        /* If there is an ifindex conflict assign a new one */
9140        if (__dev_get_by_index(net, dev->ifindex))
9141                new_ifindex = dev_new_index(net);
9142        else
9143                new_ifindex = dev->ifindex;
9144
9145        rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
9146                            new_ifindex);
9147
9148        /*
9149         *      Flush the unicast and multicast chains
9150         */
9151        dev_uc_flush(dev);
9152        dev_mc_flush(dev);
9153
9154        /* Send a netdev-removed uevent to the old namespace */
9155        kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
9156        netdev_adjacent_del_links(dev);
9157
9158        /* Actually switch the network namespace */
9159        dev_net_set(dev, net);
9160        dev->ifindex = new_ifindex;
9161
9162        /* Send a netdev-add uevent to the new namespace */
9163        kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
9164        netdev_adjacent_add_links(dev);
9165
9166        /* Fixup kobjects */
9167        err = device_rename(&dev->dev, dev->name);
9168        WARN_ON(err);
9169
9170        /* Add the device back in the hashes */
9171        list_netdevice(dev);
9172
9173        /* Notify protocols, that a new device appeared. */
9174        call_netdevice_notifiers(NETDEV_REGISTER, dev);
9175
9176        /*
9177         *      Prevent userspace races by waiting until the network
9178         *      device is fully setup before sending notifications.
9179         */
9180        rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
9181
9182        synchronize_net();
9183        err = 0;
9184out:
9185        return err;
9186}
9187EXPORT_SYMBOL_GPL(dev_change_net_namespace);
9188
9189static int dev_cpu_dead(unsigned int oldcpu)
9190{
9191        struct sk_buff **list_skb;
9192        struct sk_buff *skb;
9193        unsigned int cpu;
9194        struct softnet_data *sd, *oldsd, *remsd = NULL;
9195
9196        local_irq_disable();
9197        cpu = smp_processor_id();
9198        sd = &per_cpu(softnet_data, cpu);
9199        oldsd = &per_cpu(softnet_data, oldcpu);
9200
9201        /* Find end of our completion_queue. */
9202        list_skb = &sd->completion_queue;
9203        while (*list_skb)
9204                list_skb = &(*list_skb)->next;
9205        /* Append completion queue from offline CPU. */
9206        *list_skb = oldsd->completion_queue;
9207        oldsd->completion_queue = NULL;
9208
9209        /* Append output queue from offline CPU. */
9210        if (oldsd->output_queue) {
9211                *sd->output_queue_tailp = oldsd->output_queue;
9212                sd->output_queue_tailp = oldsd->output_queue_tailp;
9213                oldsd->output_queue = NULL;
9214                oldsd->output_queue_tailp = &oldsd->output_queue;
9215        }
9216        /* Append NAPI poll list from offline CPU, with one exception :
9217         * process_backlog() must be called by cpu owning percpu backlog.
9218         * We properly handle process_queue & input_pkt_queue later.
9219         */
9220        while (!list_empty(&oldsd->poll_list)) {
9221                struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
9222                                                            struct napi_struct,
9223                                                            poll_list);
9224
9225                list_del_init(&napi->poll_list);
9226                if (napi->poll == process_backlog)
9227                        napi->state = 0;
9228                else
9229                        ____napi_schedule(sd, napi);
9230        }
9231
9232        raise_softirq_irqoff(NET_TX_SOFTIRQ);
9233        local_irq_enable();
9234
9235#ifdef CONFIG_RPS
9236        remsd = oldsd->rps_ipi_list;
9237        oldsd->rps_ipi_list = NULL;
9238#endif
9239        /* send out pending IPI's on offline CPU */
9240        net_rps_send_ipi(remsd);
9241
9242        /* Process offline CPU's input_pkt_queue */
9243        while ((skb = __skb_dequeue(&oldsd->process_queue))) {
9244                netif_rx_ni(skb);
9245                input_queue_head_incr(oldsd);
9246        }
9247        while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
9248                netif_rx_ni(skb);
9249                input_queue_head_incr(oldsd);
9250        }
9251
9252        return 0;
9253}
9254
9255/**
9256 *      netdev_increment_features - increment feature set by one
9257 *      @all: current feature set
9258 *      @one: new feature set
9259 *      @mask: mask feature set
9260 *
9261 *      Computes a new feature set after adding a device with feature set
9262 *      @one to the master device with current feature set @all.  Will not
9263 *      enable anything that is off in @mask. Returns the new feature set.
9264 */
9265netdev_features_t netdev_increment_features(netdev_features_t all,
9266        netdev_features_t one, netdev_features_t mask)
9267{
9268        if (mask & NETIF_F_HW_CSUM)
9269                mask |= NETIF_F_CSUM_MASK;
9270        mask |= NETIF_F_VLAN_CHALLENGED;
9271
9272        all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
9273        all &= one | ~NETIF_F_ALL_FOR_ALL;
9274
9275        /* If one device supports hw checksumming, set for all. */
9276        if (all & NETIF_F_HW_CSUM)
9277                all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
9278
9279        return all;
9280}
9281EXPORT_SYMBOL(netdev_increment_features);
9282
9283static struct hlist_head * __net_init netdev_create_hash(void)
9284{
9285        int i;
9286        struct hlist_head *hash;
9287
9288        hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
9289        if (hash != NULL)
9290                for (i = 0; i < NETDEV_HASHENTRIES; i++)
9291                        INIT_HLIST_HEAD(&hash[i]);
9292
9293        return hash;
9294}
9295
9296/* Initialize per network namespace state */
9297static int __net_init netdev_init(struct net *net)
9298{
9299        if (net != &init_net)
9300                INIT_LIST_HEAD(&net->dev_base_head);
9301
9302        net->dev_name_head = netdev_create_hash();
9303        if (net->dev_name_head == NULL)
9304                goto err_name;
9305
9306        net->dev_index_head = netdev_create_hash();
9307        if (net->dev_index_head == NULL)
9308                goto err_idx;
9309
9310        return 0;
9311
9312err_idx:
9313        kfree(net->dev_name_head);
9314err_name:
9315        return -ENOMEM;
9316}
9317
9318/**
9319 *      netdev_drivername - network driver for the device
9320 *      @dev: network device
9321 *
9322 *      Determine network driver for device.
9323 */
9324const char *netdev_drivername(const struct net_device *dev)
9325{
9326        const struct device_driver *driver;
9327        const struct device *parent;
9328        const char *empty = "";
9329
9330        parent = dev->dev.parent;
9331        if (!parent)
9332                return empty;
9333
9334        driver = parent->driver;
9335        if (driver && driver->name)
9336                return driver->name;
9337        return empty;
9338}
9339
9340static void __netdev_printk(const char *level, const struct net_device *dev,
9341                            struct va_format *vaf)
9342{
9343        if (dev && dev->dev.parent) {
9344                dev_printk_emit(level[1] - '0',
9345                                dev->dev.parent,
9346                                "%s %s %s%s: %pV",
9347                                dev_driver_string(dev->dev.parent),
9348                                dev_name(dev->dev.parent),
9349                                netdev_name(dev), netdev_reg_state(dev),
9350                                vaf);
9351        } else if (dev) {
9352                printk("%s%s%s: %pV",
9353                       level, netdev_name(dev), netdev_reg_state(dev), vaf);
9354        } else {
9355                printk("%s(NULL net_device): %pV", level, vaf);
9356        }
9357}
9358
9359void netdev_printk(const char *level, const struct net_device *dev,
9360                   const char *format, ...)
9361{
9362        struct va_format vaf;
9363        va_list args;
9364
9365        va_start(args, format);
9366
9367        vaf.fmt = format;
9368        vaf.va = &args;
9369
9370        __netdev_printk(level, dev, &vaf);
9371
9372        va_end(args);
9373}
9374EXPORT_SYMBOL(netdev_printk);
9375
9376#define define_netdev_printk_level(func, level)                 \
9377void func(const struct net_device *dev, const char *fmt, ...)   \
9378{                                                               \
9379        struct va_format vaf;                                   \
9380        va_list args;                                           \
9381                                                                \
9382        va_start(args, fmt);                                    \
9383                                                                \
9384        vaf.fmt = fmt;                                          \
9385        vaf.va = &args;                                         \
9386                                                                \
9387        __netdev_printk(level, dev, &vaf);                      \
9388                                                                \
9389        va_end(args);                                           \
9390}                                                               \
9391EXPORT_SYMBOL(func);
9392
9393define_netdev_printk_level(netdev_emerg, KERN_EMERG);
9394define_netdev_printk_level(netdev_alert, KERN_ALERT);
9395define_netdev_printk_level(netdev_crit, KERN_CRIT);
9396define_netdev_printk_level(netdev_err, KERN_ERR);
9397define_netdev_printk_level(netdev_warn, KERN_WARNING);
9398define_netdev_printk_level(netdev_notice, KERN_NOTICE);
9399define_netdev_printk_level(netdev_info, KERN_INFO);
9400
9401static void __net_exit netdev_exit(struct net *net)
9402{
9403        kfree(net->dev_name_head);
9404        kfree(net->dev_index_head);
9405        if (net != &init_net)
9406                WARN_ON_ONCE(!list_empty(&net->dev_base_head));
9407}
9408
9409static struct pernet_operations __net_initdata netdev_net_ops = {
9410        .init = netdev_init,
9411        .exit = netdev_exit,
9412};
9413
9414static void __net_exit default_device_exit(struct net *net)
9415{
9416        struct net_device *dev, *aux;
9417        /*
9418         * Push all migratable network devices back to the
9419         * initial network namespace
9420         */
9421        rtnl_lock();
9422        for_each_netdev_safe(net, dev, aux) {
9423                int err;
9424                char fb_name[IFNAMSIZ];
9425
9426                /* Ignore unmoveable devices (i.e. loopback) */
9427                if (dev->features & NETIF_F_NETNS_LOCAL)
9428                        continue;
9429
9430                /* Leave virtual devices for the generic cleanup */
9431                if (dev->rtnl_link_ops)
9432                        continue;
9433
9434                /* Push remaining network devices to init_net */
9435                snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
9436                if (__dev_get_by_name(&init_net, fb_name))
9437                        snprintf(fb_name, IFNAMSIZ, "dev%%d");
9438                err = dev_change_net_namespace(dev, &init_net, fb_name);
9439                if (err) {
9440                        pr_emerg("%s: failed to move %s to init_net: %d\n",
9441                                 __func__, dev->name, err);
9442                        BUG();
9443                }
9444        }
9445        rtnl_unlock();
9446}
9447
9448static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
9449{
9450        /* Return with the rtnl_lock held when there are no network
9451         * devices unregistering in any network namespace in net_list.
9452         */
9453        struct net *net;
9454        bool unregistering;
9455        DEFINE_WAIT_FUNC(wait, woken_wake_function);
9456
9457        add_wait_queue(&netdev_unregistering_wq, &wait);
9458        for (;;) {
9459                unregistering = false;
9460                rtnl_lock();
9461                list_for_each_entry(net, net_list, exit_list) {
9462                        if (net->dev_unreg_count > 0) {
9463                                unregistering = true;
9464                                break;
9465                        }
9466                }
9467                if (!unregistering)
9468                        break;
9469                __rtnl_unlock();
9470
9471                wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
9472        }
9473        remove_wait_queue(&netdev_unregistering_wq, &wait);
9474}
9475
9476static void __net_exit default_device_exit_batch(struct list_head *net_list)
9477{
9478        /* At exit all network devices most be removed from a network
9479         * namespace.  Do this in the reverse order of registration.
9480         * Do this across as many network namespaces as possible to
9481         * improve batching efficiency.
9482         */
9483        struct net_device *dev;
9484        struct net *net;
9485        LIST_HEAD(dev_kill_list);
9486
9487        /* To prevent network device cleanup code from dereferencing
9488         * loopback devices or network devices that have been freed
9489         * wait here for all pending unregistrations to complete,
9490         * before unregistring the loopback device and allowing the
9491         * network namespace be freed.
9492         *
9493         * The netdev todo list containing all network devices
9494         * unregistrations that happen in default_device_exit_batch
9495         * will run in the rtnl_unlock() at the end of
9496         * default_device_exit_batch.
9497         */
9498        rtnl_lock_unregistering(net_list);
9499        list_for_each_entry(net, net_list, exit_list) {
9500                for_each_netdev_reverse(net, dev) {
9501                        if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
9502                                dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
9503                        else
9504                                unregister_netdevice_queue(dev, &dev_kill_list);
9505                }
9506        }
9507        unregister_netdevice_many(&dev_kill_list);
9508        rtnl_unlock();
9509}
9510
9511static struct pernet_operations __net_initdata default_device_ops = {
9512        .exit = default_device_exit,
9513        .exit_batch = default_device_exit_batch,
9514};
9515
9516/*
9517 *      Initialize the DEV module. At boot time this walks the device list and
9518 *      unhooks any devices that fail to initialise (normally hardware not
9519 *      present) and leaves us with a valid list of present and active devices.
9520 *
9521 */
9522
9523/*
9524 *       This is called single threaded during boot, so no need
9525 *       to take the rtnl semaphore.
9526 */
9527static int __init net_dev_init(void)
9528{
9529        int i, rc = -ENOMEM;
9530
9531        BUG_ON(!dev_boot_phase);
9532
9533        if (dev_proc_init())
9534                goto out;
9535
9536        if (netdev_kobject_init())
9537                goto out;
9538
9539        INIT_LIST_HEAD(&ptype_all);
9540        for (i = 0; i < PTYPE_HASH_SIZE; i++)
9541                INIT_LIST_HEAD(&ptype_base[i]);
9542
9543        INIT_LIST_HEAD(&offload_base);
9544
9545        if (register_pernet_subsys(&netdev_net_ops))
9546                goto out;
9547
9548        /*
9549         *      Initialise the packet receive queues.
9550         */
9551
9552        for_each_possible_cpu(i) {
9553                struct work_struct *flush = per_cpu_ptr(&flush_works, i);
9554                struct softnet_data *sd = &per_cpu(softnet_data, i);
9555
9556                INIT_WORK(flush, flush_backlog);
9557
9558                skb_queue_head_init(&sd->input_pkt_queue);
9559                skb_queue_head_init(&sd->process_queue);
9560#ifdef CONFIG_XFRM_OFFLOAD
9561                skb_queue_head_init(&sd->xfrm_backlog);
9562#endif
9563                INIT_LIST_HEAD(&sd->poll_list);
9564                sd->output_queue_tailp = &sd->output_queue;
9565#ifdef CONFIG_RPS
9566                sd->csd.func = rps_trigger_softirq;
9567                sd->csd.info = sd;
9568                sd->cpu = i;
9569#endif
9570
9571                sd->backlog.poll = process_backlog;
9572                sd->backlog.weight = weight_p;
9573        }
9574
9575        dev_boot_phase = 0;
9576
9577        /* The loopback device is special if any other network devices
9578         * is present in a network namespace the loopback device must
9579         * be present. Since we now dynamically allocate and free the
9580         * loopback device ensure this invariant is maintained by
9581         * keeping the loopback device as the first device on the
9582         * list of network devices.  Ensuring the loopback devices
9583         * is the first device that appears and the last network device
9584         * that disappears.
9585         */
9586        if (register_pernet_device(&loopback_net_ops))
9587                goto out;
9588
9589        if (register_pernet_device(&default_device_ops))
9590                goto out;
9591
9592        open_softirq(NET_TX_SOFTIRQ, net_tx_action);
9593        open_softirq(NET_RX_SOFTIRQ, net_rx_action);
9594
9595        rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
9596                                       NULL, dev_cpu_dead);
9597        WARN_ON(rc < 0);
9598        rc = 0;
9599out:
9600        return rc;
9601}
9602
9603subsys_initcall(net_dev_init);
9604