File Index
Files and directories
Sign in
FILE

dev.c

File preview with syntax highlighting.

linux-6.19.14/net/core/dev.c C
    1// SPDX-License-Identifier: GPL-2.0-or-later
    2/*
    3 *      NET3    Protocol independent device support routines.
    4 *
    5 *	Derived from the non IP parts of dev.c 1.0.19
    6 *              Authors:	Ross Biro
    7 *				Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
    8 *				Mark Evans, <evansmp@uhura.aston.ac.uk>
    9 *
   10 *	Additional Authors:
   11 *		Florian la Roche <rzsfl@rz.uni-sb.de>
   12 *		Alan Cox <gw4pts@gw4pts.ampr.org>
   13 *		David Hinds <dahinds@users.sourceforge.net>
   14 *		Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
   15 *		Adam Sulmicki <adam@cfar.umd.edu>
   16 *              Pekka Riikonen <priikone@poesidon.pspt.fi>
   17 *
   18 *	Changes:
   19 *              D.J. Barrow     :       Fixed bug where dev->refcnt gets set
   20 *                                      to 2 if register_netdev gets called
   21 *                                      before net_dev_init & also removed a
   22 *                                      few lines of code in the process.
   23 *		Alan Cox	:	device private ioctl copies fields back.
   24 *		Alan Cox	:	Transmit queue code does relevant
   25 *					stunts to keep the queue safe.
   26 *		Alan Cox	:	Fixed double lock.
   27 *		Alan Cox	:	Fixed promisc NULL pointer trap
   28 *		????????	:	Support the full private ioctl range
   29 *		Alan Cox	:	Moved ioctl permission check into
   30 *					drivers
   31 *		Tim Kordas	:	SIOCADDMULTI/SIOCDELMULTI
   32 *		Alan Cox	:	100 backlog just doesn't cut it when
   33 *					you start doing multicast video 8)
   34 *		Alan Cox	:	Rewrote net_bh and list manager.
   35 *              Alan Cox        :       Fix ETH_P_ALL echoback lengths.
   36 *		Alan Cox	:	Took out transmit every packet pass
   37 *					Saved a few bytes in the ioctl handler
   38 *		Alan Cox	:	Network driver sets packet type before
   39 *					calling netif_rx. Saves a function
   40 *					call a packet.
   41 *		Alan Cox	:	Hashed net_bh()
   42 *		Richard Kooijman:	Timestamp fixes.
   43 *		Alan Cox	:	Wrong field in SIOCGIFDSTADDR
   44 *		Alan Cox	:	Device lock protection.
   45 *              Alan Cox        :       Fixed nasty side effect of device close
   46 *					changes.
   47 *		Rudi Cilibrasi	:	Pass the right thing to
   48 *					set_mac_address()
   49 *		Dave Miller	:	32bit quantity for the device lock to
   50 *					make it work out on a Sparc.
   51 *		Bjorn Ekwall	:	Added KERNELD hack.
   52 *		Alan Cox	:	Cleaned up the backlog initialise.
   53 *		Craig Metz	:	SIOCGIFCONF fix if space for under
   54 *					1 device.
   55 *	    Thomas Bogendoerfer :	Return ENODEV for dev_open, if there
   56 *					is no device open function.
   57 *		Andi Kleen	:	Fix error reporting for SIOCGIFCONF
   58 *	    Michael Chastain	:	Fix signed/unsigned for SIOCGIFCONF
   59 *		Cyrus Durgin	:	Cleaned for KMOD
   60 *		Adam Sulmicki   :	Bug Fix : Network Device Unload
   61 *					A network device unload needs to purge
   62 *					the backlog queue.
   63 *	Paul Rusty Russell	:	SIOCSIFNAME
   64 *              Pekka Riikonen  :	Netdev boot-time settings code
   65 *              Andrew Morton   :       Make unregister_netdevice wait
   66 *                                      indefinitely on dev->refcnt
   67 *              J Hadi Salim    :       - Backlog queue sampling
   68 *				        - netif_rx() feedback
   69 */
   70
   71#include <linux/uaccess.h>
   72#include <linux/bitmap.h>
   73#include <linux/capability.h>
   74#include <linux/cpu.h>
   75#include <linux/types.h>
   76#include <linux/kernel.h>
   77#include <linux/hash.h>
   78#include <linux/slab.h>
   79#include <linux/sched.h>
   80#include <linux/sched/isolation.h>
   81#include <linux/sched/mm.h>
   82#include <linux/smpboot.h>
   83#include <linux/mutex.h>
   84#include <linux/rwsem.h>
   85#include <linux/string.h>
   86#include <linux/mm.h>
   87#include <linux/socket.h>
   88#include <linux/sockios.h>
   89#include <linux/errno.h>
   90#include <linux/interrupt.h>
   91#include <linux/if_ether.h>
   92#include <linux/netdevice.h>
   93#include <linux/etherdevice.h>
   94#include <linux/ethtool.h>
   95#include <linux/ethtool_netlink.h>
   96#include <linux/skbuff.h>
   97#include <linux/kthread.h>
   98#include <linux/bpf.h>
   99#include <linux/bpf_trace.h>
  100#include <net/net_namespace.h>
  101#include <net/sock.h>
  102#include <net/busy_poll.h>
  103#include <linux/rtnetlink.h>
  104#include <linux/stat.h>
  105#include <net/dsa.h>
  106#include <net/dst.h>
  107#include <net/dst_metadata.h>
  108#include <net/gro.h>
  109#include <net/netdev_queues.h>
  110#include <net/pkt_sched.h>
  111#include <net/pkt_cls.h>
  112#include <net/checksum.h>
  113#include <net/xfrm.h>
  114#include <net/tcx.h>
  115#include <linux/highmem.h>
  116#include <linux/init.h>
  117#include <linux/module.h>
  118#include <linux/netpoll.h>
  119#include <linux/rcupdate.h>
  120#include <linux/delay.h>
  121#include <net/iw_handler.h>
  122#include <asm/current.h>
  123#include <linux/audit.h>
  124#include <linux/dmaengine.h>
  125#include <linux/err.h>
  126#include <linux/ctype.h>
  127#include <linux/if_arp.h>
  128#include <linux/if_vlan.h>
  129#include <linux/ip.h>
  130#include <net/ip.h>
  131#include <net/mpls.h>
  132#include <linux/ipv6.h>
  133#include <linux/in.h>
  134#include <linux/jhash.h>
  135#include <linux/random.h>
  136#include <trace/events/napi.h>
  137#include <trace/events/net.h>
  138#include <trace/events/skb.h>
  139#include <trace/events/qdisc.h>
  140#include <trace/events/xdp.h>
  141#include <linux/inetdevice.h>
  142#include <linux/cpu_rmap.h>
  143#include <linux/static_key.h>
  144#include <linux/hashtable.h>
  145#include <linux/vmalloc.h>
  146#include <linux/if_macvlan.h>
  147#include <linux/errqueue.h>
  148#include <linux/hrtimer.h>
  149#include <linux/netfilter_netdev.h>
  150#include <linux/crash_dump.h>
  151#include <linux/sctp.h>
  152#include <net/udp_tunnel.h>
  153#include <linux/net_namespace.h>
  154#include <linux/indirect_call_wrapper.h>
  155#include <net/devlink.h>
  156#include <linux/pm_runtime.h>
  157#include <linux/prandom.h>
  158#include <linux/once_lite.h>
  159#include <net/netdev_lock.h>
  160#include <net/netdev_rx_queue.h>
  161#include <net/page_pool/types.h>
  162#include <net/page_pool/helpers.h>
  163#include <net/page_pool/memory_provider.h>
  164#include <net/rps.h>
  165#include <linux/phy_link_topology.h>
  166
  167#include "dev.h"
  168#include "devmem.h"
  169#include "net-sysfs.h"
  170
  171static DEFINE_SPINLOCK(ptype_lock);
  172struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
  173
  174static int netif_rx_internal(struct sk_buff *skb);
  175static int call_netdevice_notifiers_extack(unsigned long val,
  176					   struct net_device *dev,
  177					   struct netlink_ext_ack *extack);
  178
  179static DEFINE_MUTEX(ifalias_mutex);
  180
  181/* protects napi_hash addition/deletion and napi_gen_id */
  182static DEFINE_SPINLOCK(napi_hash_lock);
  183
  184static unsigned int napi_gen_id = NR_CPUS;
  185static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
  186
  187static inline void dev_base_seq_inc(struct net *net)
  188{
  189	unsigned int val = net->dev_base_seq + 1;
  190
  191	WRITE_ONCE(net->dev_base_seq, val ?: 1);
  192}
  193
  194static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
  195{
  196	unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
  197
  198	return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
  199}
  200
  201static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
  202{
  203	return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
  204}
  205
  206#ifndef CONFIG_PREEMPT_RT
  207
  208static DEFINE_STATIC_KEY_FALSE(use_backlog_threads_key);
  209
  210static int __init setup_backlog_napi_threads(char *arg)
  211{
  212	static_branch_enable(&use_backlog_threads_key);
  213	return 0;
  214}
  215early_param("thread_backlog_napi", setup_backlog_napi_threads);
  216
  217static bool use_backlog_threads(void)
  218{
  219	return static_branch_unlikely(&use_backlog_threads_key);
  220}
  221
  222#else
  223
  224static bool use_backlog_threads(void)
  225{
  226	return true;
  227}
  228
  229#endif
  230
  231static inline void backlog_lock_irq_save(struct softnet_data *sd,
  232					 unsigned long *flags)
  233{
  234	if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
  235		spin_lock_irqsave(&sd->input_pkt_queue.lock, *flags);
  236	else
  237		local_irq_save(*flags);
  238}
  239
  240static inline void backlog_lock_irq_disable(struct softnet_data *sd)
  241{
  242	if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
  243		spin_lock_irq(&sd->input_pkt_queue.lock);
  244	else
  245		local_irq_disable();
  246}
  247
  248static inline void backlog_unlock_irq_restore(struct softnet_data *sd,
  249					      unsigned long *flags)
  250{
  251	if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
  252		spin_unlock_irqrestore(&sd->input_pkt_queue.lock, *flags);
  253	else
  254		local_irq_restore(*flags);
  255}
  256
  257static inline void backlog_unlock_irq_enable(struct softnet_data *sd)
  258{
  259	if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
  260		spin_unlock_irq(&sd->input_pkt_queue.lock);
  261	else
  262		local_irq_enable();
  263}
  264
  265static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
  266						       const char *name)
  267{
  268	struct netdev_name_node *name_node;
  269
  270	name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
  271	if (!name_node)
  272		return NULL;
  273	INIT_HLIST_NODE(&name_node->hlist);
  274	name_node->dev = dev;
  275	name_node->name = name;
  276	return name_node;
  277}
  278
  279static struct netdev_name_node *
  280netdev_name_node_head_alloc(struct net_device *dev)
  281{
  282	struct netdev_name_node *name_node;
  283
  284	name_node = netdev_name_node_alloc(dev, dev->name);
  285	if (!name_node)
  286		return NULL;
  287	INIT_LIST_HEAD(&name_node->list);
  288	return name_node;
  289}
  290
  291static void netdev_name_node_free(struct netdev_name_node *name_node)
  292{
  293	kfree(name_node);
  294}
  295
  296static void netdev_name_node_add(struct net *net,
  297				 struct netdev_name_node *name_node)
  298{
  299	hlist_add_head_rcu(&name_node->hlist,
  300			   dev_name_hash(net, name_node->name));
  301}
  302
  303static void netdev_name_node_del(struct netdev_name_node *name_node)
  304{
  305	hlist_del_rcu(&name_node->hlist);
  306}
  307
  308static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
  309							const char *name)
  310{
  311	struct hlist_head *head = dev_name_hash(net, name);
  312	struct netdev_name_node *name_node;
  313
  314	hlist_for_each_entry(name_node, head, hlist)
  315		if (!strcmp(name_node->name, name))
  316			return name_node;
  317	return NULL;
  318}
  319
  320static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
  321							    const char *name)
  322{
  323	struct hlist_head *head = dev_name_hash(net, name);
  324	struct netdev_name_node *name_node;
  325
  326	hlist_for_each_entry_rcu(name_node, head, hlist)
  327		if (!strcmp(name_node->name, name))
  328			return name_node;
  329	return NULL;
  330}
  331
  332bool netdev_name_in_use(struct net *net, const char *name)
  333{
  334	return netdev_name_node_lookup(net, name);
  335}
  336EXPORT_SYMBOL(netdev_name_in_use);
  337
  338int netdev_name_node_alt_create(struct net_device *dev, const char *name)
  339{
  340	struct netdev_name_node *name_node;
  341	struct net *net = dev_net(dev);
  342
  343	name_node = netdev_name_node_lookup(net, name);
  344	if (name_node)
  345		return -EEXIST;
  346	name_node = netdev_name_node_alloc(dev, name);
  347	if (!name_node)
  348		return -ENOMEM;
  349	netdev_name_node_add(net, name_node);
  350	/* The node that holds dev->name acts as a head of per-device list. */
  351	list_add_tail_rcu(&name_node->list, &dev->name_node->list);
  352
  353	return 0;
  354}
  355
  356static void netdev_name_node_alt_free(struct rcu_head *head)
  357{
  358	struct netdev_name_node *name_node =
  359		container_of(head, struct netdev_name_node, rcu);
  360
  361	kfree(name_node->name);
  362	netdev_name_node_free(name_node);
  363}
  364
  365static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
  366{
  367	netdev_name_node_del(name_node);
  368	list_del(&name_node->list);
  369	call_rcu(&name_node->rcu, netdev_name_node_alt_free);
  370}
  371
  372int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
  373{
  374	struct netdev_name_node *name_node;
  375	struct net *net = dev_net(dev);
  376
  377	name_node = netdev_name_node_lookup(net, name);
  378	if (!name_node)
  379		return -ENOENT;
  380	/* lookup might have found our primary name or a name belonging
  381	 * to another device.
  382	 */
  383	if (name_node == dev->name_node || name_node->dev != dev)
  384		return -EINVAL;
  385
  386	__netdev_name_node_alt_destroy(name_node);
  387	return 0;
  388}
  389
  390static void netdev_name_node_alt_flush(struct net_device *dev)
  391{
  392	struct netdev_name_node *name_node, *tmp;
  393
  394	list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list) {
  395		list_del(&name_node->list);
  396		netdev_name_node_alt_free(&name_node->rcu);
  397	}
  398}
  399
  400/* Device list insertion */
  401static void list_netdevice(struct net_device *dev)
  402{
  403	struct netdev_name_node *name_node;
  404	struct net *net = dev_net(dev);
  405
  406	ASSERT_RTNL();
  407
  408	list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
  409	netdev_name_node_add(net, dev->name_node);
  410	hlist_add_head_rcu(&dev->index_hlist,
  411			   dev_index_hash(net, dev->ifindex));
  412
  413	netdev_for_each_altname(dev, name_node)
  414		netdev_name_node_add(net, name_node);
  415
  416	/* We reserved the ifindex, this can't fail */
  417	WARN_ON(xa_store(&net->dev_by_index, dev->ifindex, dev, GFP_KERNEL));
  418
  419	dev_base_seq_inc(net);
  420}
  421
  422/* Device list removal
  423 * caller must respect a RCU grace period before freeing/reusing dev
  424 */
  425static void unlist_netdevice(struct net_device *dev)
  426{
  427	struct netdev_name_node *name_node;
  428	struct net *net = dev_net(dev);
  429
  430	ASSERT_RTNL();
  431
  432	xa_erase(&net->dev_by_index, dev->ifindex);
  433
  434	netdev_for_each_altname(dev, name_node)
  435		netdev_name_node_del(name_node);
  436
  437	/* Unlink dev from the device chain */
  438	list_del_rcu(&dev->dev_list);
  439	netdev_name_node_del(dev->name_node);
  440	hlist_del_rcu(&dev->index_hlist);
  441
  442	dev_base_seq_inc(dev_net(dev));
  443}
  444
  445/*
  446 *	Our notifier list
  447 */
  448
  449static RAW_NOTIFIER_HEAD(netdev_chain);
  450
  451/*
  452 *	Device drivers call our routines to queue packets here. We empty the
  453 *	queue in the local softnet handler.
  454 */
  455
  456DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data) = {
  457	.process_queue_bh_lock = INIT_LOCAL_LOCK(process_queue_bh_lock),
  458};
  459EXPORT_PER_CPU_SYMBOL(softnet_data);
  460
  461/* Page_pool has a lockless array/stack to alloc/recycle pages.
  462 * PP consumers must pay attention to run APIs in the appropriate context
  463 * (e.g. NAPI context).
  464 */
  465DEFINE_PER_CPU(struct page_pool_bh, system_page_pool) = {
  466	.bh_lock = INIT_LOCAL_LOCK(bh_lock),
  467};
  468
  469#ifdef CONFIG_LOCKDEP
  470/*
  471 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
  472 * according to dev->type
  473 */
  474static const unsigned short netdev_lock_type[] = {
  475	 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
  476	 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
  477	 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
  478	 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
  479	 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
  480	 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
  481	 ARPHRD_CAN, ARPHRD_MCTP,
  482	 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
  483	 ARPHRD_RAWHDLC, ARPHRD_RAWIP,
  484	 ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
  485	 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
  486	 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
  487	 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
  488	 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
  489	 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
  490	 ARPHRD_IEEE80211_RADIOTAP,
  491	 ARPHRD_IEEE802154, ARPHRD_IEEE802154_MONITOR,
  492	 ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
  493	 ARPHRD_CAIF, ARPHRD_IP6GRE, ARPHRD_NETLINK, ARPHRD_6LOWPAN,
  494	 ARPHRD_VSOCKMON,
  495	 ARPHRD_VOID, ARPHRD_NONE};
  496
  497static const char *const netdev_lock_name[] = {
  498	"_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
  499	"_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
  500	"_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
  501	"_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
  502	"_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
  503	"_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
  504	"_xmit_CAN", "_xmit_MCTP",
  505	"_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
  506	"_xmit_RAWHDLC", "_xmit_RAWIP",
  507	"_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
  508	"_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
  509	"_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
  510	"_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
  511	"_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
  512	"_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
  513	"_xmit_IEEE80211_RADIOTAP",
  514	"_xmit_IEEE802154", "_xmit_IEEE802154_MONITOR",
  515	"_xmit_PHONET", "_xmit_PHONET_PIPE",
  516	"_xmit_CAIF", "_xmit_IP6GRE", "_xmit_NETLINK", "_xmit_6LOWPAN",
  517	"_xmit_VSOCKMON",
  518	"_xmit_VOID", "_xmit_NONE"};
  519
  520static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
  521static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
  522
  523static inline unsigned short netdev_lock_pos(unsigned short dev_type)
  524{
  525	int i;
  526
  527	for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
  528		if (netdev_lock_type[i] == dev_type)
  529			return i;
  530	/* the last key is used by default */
  531	WARN_ONCE(1, "netdev_lock_pos() could not find dev_type=%u\n", dev_type);
  532	return ARRAY_SIZE(netdev_lock_type) - 1;
  533}
  534
  535static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
  536						 unsigned short dev_type)
  537{
  538	int i;
  539
  540	i = netdev_lock_pos(dev_type);
  541	lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
  542				   netdev_lock_name[i]);
  543}
  544
  545static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
  546{
  547	int i;
  548
  549	i = netdev_lock_pos(dev->type);
  550	lockdep_set_class_and_name(&dev->addr_list_lock,
  551				   &netdev_addr_lock_key[i],
  552				   netdev_lock_name[i]);
  553}
  554#else
  555static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
  556						 unsigned short dev_type)
  557{
  558}
  559
  560static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
  561{
  562}
  563#endif
  564
  565/*******************************************************************************
  566 *
  567 *		Protocol management and registration routines
  568 *
  569 *******************************************************************************/
  570
  571
  572/*
  573 *	Add a protocol ID to the list. Now that the input handler is
  574 *	smarter we can dispense with all the messy stuff that used to be
  575 *	here.
  576 *
  577 *	BEWARE!!! Protocol handlers, mangling input packets,
  578 *	MUST BE last in hash buckets and checking protocol handlers
  579 *	MUST start from promiscuous ptype_all chain in net_bh.
  580 *	It is true now, do not change it.
  581 *	Explanation follows: if protocol handler, mangling packet, will
  582 *	be the first on list, it is not able to sense, that packet
  583 *	is cloned and should be copied-on-write, so that it will
  584 *	change it and subsequent readers will get broken packet.
  585 *							--ANK (980803)
  586 */
  587
  588static inline struct list_head *ptype_head(const struct packet_type *pt)
  589{
  590	if (pt->type == htons(ETH_P_ALL)) {
  591		if (!pt->af_packet_net && !pt->dev)
  592			return NULL;
  593
  594		return pt->dev ? &pt->dev->ptype_all :
  595				 &pt->af_packet_net->ptype_all;
  596	}
  597
  598	if (pt->dev)
  599		return &pt->dev->ptype_specific;
  600
  601	return pt->af_packet_net ? &pt->af_packet_net->ptype_specific :
  602				 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
  603}
  604
  605/**
  606 *	dev_add_pack - add packet handler
  607 *	@pt: packet type declaration
  608 *
  609 *	Add a protocol handler to the networking stack. The passed &packet_type
  610 *	is linked into kernel lists and may not be freed until it has been
  611 *	removed from the kernel lists.
  612 *
  613 *	This call does not sleep therefore it can not
  614 *	guarantee all CPU's that are in middle of receiving packets
  615 *	will see the new packet type (until the next received packet).
  616 */
  617
  618void dev_add_pack(struct packet_type *pt)
  619{
  620	struct list_head *head = ptype_head(pt);
  621
  622	if (WARN_ON_ONCE(!head))
  623		return;
  624
  625	spin_lock(&ptype_lock);
  626	list_add_rcu(&pt->list, head);
  627	spin_unlock(&ptype_lock);
  628}
  629EXPORT_SYMBOL(dev_add_pack);
  630
  631/**
  632 *	__dev_remove_pack	 - remove packet handler
  633 *	@pt: packet type declaration
  634 *
  635 *	Remove a protocol handler that was previously added to the kernel
  636 *	protocol handlers by dev_add_pack(). The passed &packet_type is removed
  637 *	from the kernel lists and can be freed or reused once this function
  638 *	returns.
  639 *
  640 *      The packet type might still be in use by receivers
  641 *	and must not be freed until after all the CPU's have gone
  642 *	through a quiescent state.
  643 */
  644void __dev_remove_pack(struct packet_type *pt)
  645{
  646	struct list_head *head = ptype_head(pt);
  647	struct packet_type *pt1;
  648
  649	if (!head)
  650		return;
  651
  652	spin_lock(&ptype_lock);
  653
  654	list_for_each_entry(pt1, head, list) {
  655		if (pt == pt1) {
  656			list_del_rcu(&pt->list);
  657			goto out;
  658		}
  659	}
  660
  661	pr_warn("dev_remove_pack: %p not found\n", pt);
  662out:
  663	spin_unlock(&ptype_lock);
  664}
  665EXPORT_SYMBOL(__dev_remove_pack);
  666
  667/**
  668 *	dev_remove_pack	 - remove packet handler
  669 *	@pt: packet type declaration
  670 *
  671 *	Remove a protocol handler that was previously added to the kernel
  672 *	protocol handlers by dev_add_pack(). The passed &packet_type is removed
  673 *	from the kernel lists and can be freed or reused once this function
  674 *	returns.
  675 *
  676 *	This call sleeps to guarantee that no CPU is looking at the packet
  677 *	type after return.
  678 */
  679void dev_remove_pack(struct packet_type *pt)
  680{
  681	__dev_remove_pack(pt);
  682
  683	synchronize_net();
  684}
  685EXPORT_SYMBOL(dev_remove_pack);
  686
  687
  688/*******************************************************************************
  689 *
  690 *			    Device Interface Subroutines
  691 *
  692 *******************************************************************************/
  693
  694/**
  695 *	dev_get_iflink	- get 'iflink' value of a interface
  696 *	@dev: targeted interface
  697 *
  698 *	Indicates the ifindex the interface is linked to.
  699 *	Physical interfaces have the same 'ifindex' and 'iflink' values.
  700 */
  701
  702int dev_get_iflink(const struct net_device *dev)
  703{
  704	if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
  705		return dev->netdev_ops->ndo_get_iflink(dev);
  706
  707	return READ_ONCE(dev->ifindex);
  708}
  709EXPORT_SYMBOL(dev_get_iflink);
  710
  711/**
  712 *	dev_fill_metadata_dst - Retrieve tunnel egress information.
  713 *	@dev: targeted interface
  714 *	@skb: The packet.
  715 *
  716 *	For better visibility of tunnel traffic OVS needs to retrieve
  717 *	egress tunnel information for a packet. Following API allows
  718 *	user to get this info.
  719 */
  720int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
  721{
  722	struct ip_tunnel_info *info;
  723
  724	if (!dev->netdev_ops  || !dev->netdev_ops->ndo_fill_metadata_dst)
  725		return -EINVAL;
  726
  727	info = skb_tunnel_info_unclone(skb);
  728	if (!info)
  729		return -ENOMEM;
  730	if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
  731		return -EINVAL;
  732
  733	return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
  734}
  735EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
  736
  737static struct net_device_path *dev_fwd_path(struct net_device_path_stack *stack)
  738{
  739	int k = stack->num_paths++;
  740
  741	if (k >= NET_DEVICE_PATH_STACK_MAX)
  742		return NULL;
  743
  744	return &stack->path[k];
  745}
  746
  747int dev_fill_forward_path(const struct net_device *dev, const u8 *daddr,
  748			  struct net_device_path_stack *stack)
  749{
  750	const struct net_device *last_dev;
  751	struct net_device_path_ctx ctx = {
  752		.dev	= dev,
  753	};
  754	struct net_device_path *path;
  755	int ret = 0;
  756
  757	memcpy(ctx.daddr, daddr, sizeof(ctx.daddr));
  758	stack->num_paths = 0;
  759	while (ctx.dev && ctx.dev->netdev_ops->ndo_fill_forward_path) {
  760		last_dev = ctx.dev;
  761		path = dev_fwd_path(stack);
  762		if (!path)
  763			return -1;
  764
  765		memset(path, 0, sizeof(struct net_device_path));
  766		ret = ctx.dev->netdev_ops->ndo_fill_forward_path(&ctx, path);
  767		if (ret < 0)
  768			return -1;
  769
  770		if (WARN_ON_ONCE(last_dev == ctx.dev))
  771			return -1;
  772	}
  773
  774	if (!ctx.dev)
  775		return ret;
  776
  777	path = dev_fwd_path(stack);
  778	if (!path)
  779		return -1;
  780	path->type = DEV_PATH_ETHERNET;
  781	path->dev = ctx.dev;
  782
  783	return ret;
  784}
  785EXPORT_SYMBOL_GPL(dev_fill_forward_path);
  786
  787/* must be called under rcu_read_lock(), as we dont take a reference */
  788static struct napi_struct *napi_by_id(unsigned int napi_id)
  789{
  790	unsigned int hash = napi_id % HASH_SIZE(napi_hash);
  791	struct napi_struct *napi;
  792
  793	hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
  794		if (napi->napi_id == napi_id)
  795			return napi;
  796
  797	return NULL;
  798}
  799
  800/* must be called under rcu_read_lock(), as we dont take a reference */
  801static struct napi_struct *
  802netdev_napi_by_id(struct net *net, unsigned int napi_id)
  803{
  804	struct napi_struct *napi;
  805
  806	napi = napi_by_id(napi_id);
  807	if (!napi)
  808		return NULL;
  809
  810	if (WARN_ON_ONCE(!napi->dev))
  811		return NULL;
  812	if (!net_eq(net, dev_net(napi->dev)))
  813		return NULL;
  814
  815	return napi;
  816}
  817
  818/**
  819 *	netdev_napi_by_id_lock() - find a device by NAPI ID and lock it
  820 *	@net: the applicable net namespace
  821 *	@napi_id: ID of a NAPI of a target device
  822 *
  823 *	Find a NAPI instance with @napi_id. Lock its device.
  824 *	The device must be in %NETREG_REGISTERED state for lookup to succeed.
  825 *	netdev_unlock() must be called to release it.
  826 *
  827 *	Return: pointer to NAPI, its device with lock held, NULL if not found.
  828 */
  829struct napi_struct *
  830netdev_napi_by_id_lock(struct net *net, unsigned int napi_id)
  831{
  832	struct napi_struct *napi;
  833	struct net_device *dev;
  834
  835	rcu_read_lock();
  836	napi = netdev_napi_by_id(net, napi_id);
  837	if (!napi || READ_ONCE(napi->dev->reg_state) != NETREG_REGISTERED) {
  838		rcu_read_unlock();
  839		return NULL;
  840	}
  841
  842	dev = napi->dev;
  843	dev_hold(dev);
  844	rcu_read_unlock();
  845
  846	dev = __netdev_put_lock(dev, net);
  847	if (!dev)
  848		return NULL;
  849
  850	rcu_read_lock();
  851	napi = netdev_napi_by_id(net, napi_id);
  852	if (napi && napi->dev != dev)
  853		napi = NULL;
  854	rcu_read_unlock();
  855
  856	if (!napi)
  857		netdev_unlock(dev);
  858	return napi;
  859}
  860
  861/**
  862 *	__dev_get_by_name	- find a device by its name
  863 *	@net: the applicable net namespace
  864 *	@name: name to find
  865 *
  866 *	Find an interface by name. Must be called under RTNL semaphore.
  867 *	If the name is found a pointer to the device is returned.
  868 *	If the name is not found then %NULL is returned. The
  869 *	reference counters are not incremented so the caller must be
  870 *	careful with locks.
  871 */
  872
  873struct net_device *__dev_get_by_name(struct net *net, const char *name)
  874{
  875	struct netdev_name_node *node_name;
  876
  877	node_name = netdev_name_node_lookup(net, name);
  878	return node_name ? node_name->dev : NULL;
  879}
  880EXPORT_SYMBOL(__dev_get_by_name);
  881
  882/**
  883 * dev_get_by_name_rcu	- find a device by its name
  884 * @net: the applicable net namespace
  885 * @name: name to find
  886 *
  887 * Find an interface by name.
  888 * If the name is found a pointer to the device is returned.
  889 * If the name is not found then %NULL is returned.
  890 * The reference counters are not incremented so the caller must be
  891 * careful with locks. The caller must hold RCU lock.
  892 */
  893
  894struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
  895{
  896	struct netdev_name_node *node_name;
  897
  898	node_name = netdev_name_node_lookup_rcu(net, name);
  899	return node_name ? node_name->dev : NULL;
  900}
  901EXPORT_SYMBOL(dev_get_by_name_rcu);
  902
  903/* Deprecated for new users, call netdev_get_by_name() instead */
  904struct net_device *dev_get_by_name(struct net *net, const char *name)
  905{
  906	struct net_device *dev;
  907
  908	rcu_read_lock();
  909	dev = dev_get_by_name_rcu(net, name);
  910	dev_hold(dev);
  911	rcu_read_unlock();
  912	return dev;
  913}
  914EXPORT_SYMBOL(dev_get_by_name);
  915
  916/**
  917 *	netdev_get_by_name() - find a device by its name
  918 *	@net: the applicable net namespace
  919 *	@name: name to find
  920 *	@tracker: tracking object for the acquired reference
  921 *	@gfp: allocation flags for the tracker
  922 *
  923 *	Find an interface by name. This can be called from any
  924 *	context and does its own locking. The returned handle has
  925 *	the usage count incremented and the caller must use netdev_put() to
  926 *	release it when it is no longer needed. %NULL is returned if no
  927 *	matching device is found.
  928 */
  929struct net_device *netdev_get_by_name(struct net *net, const char *name,
  930				      netdevice_tracker *tracker, gfp_t gfp)
  931{
  932	struct net_device *dev;
  933
  934	dev = dev_get_by_name(net, name);
  935	if (dev)
  936		netdev_tracker_alloc(dev, tracker, gfp);
  937	return dev;
  938}
  939EXPORT_SYMBOL(netdev_get_by_name);
  940
  941/**
  942 *	__dev_get_by_index - find a device by its ifindex
  943 *	@net: the applicable net namespace
  944 *	@ifindex: index of device
  945 *
  946 *	Search for an interface by index. Returns %NULL if the device
  947 *	is not found or a pointer to the device. The device has not
  948 *	had its reference counter increased so the caller must be careful
  949 *	about locking. The caller must hold the RTNL semaphore.
  950 */
  951
  952struct net_device *__dev_get_by_index(struct net *net, int ifindex)
  953{
  954	struct net_device *dev;
  955	struct hlist_head *head = dev_index_hash(net, ifindex);
  956
  957	hlist_for_each_entry(dev, head, index_hlist)
  958		if (dev->ifindex == ifindex)
  959			return dev;
  960
  961	return NULL;
  962}
  963EXPORT_SYMBOL(__dev_get_by_index);
  964
  965/**
  966 *	dev_get_by_index_rcu - find a device by its ifindex
  967 *	@net: the applicable net namespace
  968 *	@ifindex: index of device
  969 *
  970 *	Search for an interface by index. Returns %NULL if the device
  971 *	is not found or a pointer to the device. The device has not
  972 *	had its reference counter increased so the caller must be careful
  973 *	about locking. The caller must hold RCU lock.
  974 */
  975
  976struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
  977{
  978	struct net_device *dev;
  979	struct hlist_head *head = dev_index_hash(net, ifindex);
  980
  981	hlist_for_each_entry_rcu(dev, head, index_hlist)
  982		if (dev->ifindex == ifindex)
  983			return dev;
  984
  985	return NULL;
  986}
  987EXPORT_SYMBOL(dev_get_by_index_rcu);
  988
  989/* Deprecated for new users, call netdev_get_by_index() instead */
  990struct net_device *dev_get_by_index(struct net *net, int ifindex)
  991{
  992	struct net_device *dev;
  993
  994	rcu_read_lock();
  995	dev = dev_get_by_index_rcu(net, ifindex);
  996	dev_hold(dev);
  997	rcu_read_unlock();
  998	return dev;
  999}
 1000EXPORT_SYMBOL(dev_get_by_index);
 1001
 1002/**
 1003 *	netdev_get_by_index() - find a device by its ifindex
 1004 *	@net: the applicable net namespace
 1005 *	@ifindex: index of device
 1006 *	@tracker: tracking object for the acquired reference
 1007 *	@gfp: allocation flags for the tracker
 1008 *
 1009 *	Search for an interface by index. Returns NULL if the device
 1010 *	is not found or a pointer to the device. The device returned has
 1011 *	had a reference added and the pointer is safe until the user calls
 1012 *	netdev_put() to indicate they have finished with it.
 1013 */
 1014struct net_device *netdev_get_by_index(struct net *net, int ifindex,
 1015				       netdevice_tracker *tracker, gfp_t gfp)
 1016{
 1017	struct net_device *dev;
 1018
 1019	dev = dev_get_by_index(net, ifindex);
 1020	if (dev)
 1021		netdev_tracker_alloc(dev, tracker, gfp);
 1022	return dev;
 1023}
 1024EXPORT_SYMBOL(netdev_get_by_index);
 1025
 1026/**
 1027 *	dev_get_by_napi_id - find a device by napi_id
 1028 *	@napi_id: ID of the NAPI struct
 1029 *
 1030 *	Search for an interface by NAPI ID. Returns %NULL if the device
 1031 *	is not found or a pointer to the device. The device has not had
 1032 *	its reference counter increased so the caller must be careful
 1033 *	about locking. The caller must hold RCU lock.
 1034 */
 1035struct net_device *dev_get_by_napi_id(unsigned int napi_id)
 1036{
 1037	struct napi_struct *napi;
 1038
 1039	WARN_ON_ONCE(!rcu_read_lock_held());
 1040
 1041	if (!napi_id_valid(napi_id))
 1042		return NULL;
 1043
 1044	napi = napi_by_id(napi_id);
 1045
 1046	return napi ? napi->dev : NULL;
 1047}
 1048
 1049/* Release the held reference on the net_device, and if the net_device
 1050 * is still registered try to lock the instance lock. If device is being
 1051 * unregistered NULL will be returned (but the reference has been released,
 1052 * either way!)
 1053 *
 1054 * This helper is intended for locking net_device after it has been looked up
 1055 * using a lockless lookup helper. Lock prevents the instance from going away.
 1056 */
 1057struct net_device *__netdev_put_lock(struct net_device *dev, struct net *net)
 1058{
 1059	netdev_lock(dev);
 1060	if (dev->reg_state > NETREG_REGISTERED ||
 1061	    dev->moving_ns || !net_eq(dev_net(dev), net)) {
 1062		netdev_unlock(dev);
 1063		dev_put(dev);
 1064		return NULL;
 1065	}
 1066	dev_put(dev);
 1067	return dev;
 1068}
 1069
 1070static struct net_device *
 1071__netdev_put_lock_ops_compat(struct net_device *dev, struct net *net)
 1072{
 1073	netdev_lock_ops_compat(dev);
 1074	if (dev->reg_state > NETREG_REGISTERED ||
 1075	    dev->moving_ns || !net_eq(dev_net(dev), net)) {
 1076		netdev_unlock_ops_compat(dev);
 1077		dev_put(dev);
 1078		return NULL;
 1079	}
 1080	dev_put(dev);
 1081	return dev;
 1082}
 1083
 1084/**
 1085 *	netdev_get_by_index_lock() - find a device by its ifindex
 1086 *	@net: the applicable net namespace
 1087 *	@ifindex: index of device
 1088 *
 1089 *	Search for an interface by index. If a valid device
 1090 *	with @ifindex is found it will be returned with netdev->lock held.
 1091 *	netdev_unlock() must be called to release it.
 1092 *
 1093 *	Return: pointer to a device with lock held, NULL if not found.
 1094 */
 1095struct net_device *netdev_get_by_index_lock(struct net *net, int ifindex)
 1096{
 1097	struct net_device *dev;
 1098
 1099	dev = dev_get_by_index(net, ifindex);
 1100	if (!dev)
 1101		return NULL;
 1102
 1103	return __netdev_put_lock(dev, net);
 1104}
 1105
 1106struct net_device *
 1107netdev_get_by_index_lock_ops_compat(struct net *net, int ifindex)
 1108{
 1109	struct net_device *dev;
 1110
 1111	dev = dev_get_by_index(net, ifindex);
 1112	if (!dev)
 1113		return NULL;
 1114
 1115	return __netdev_put_lock_ops_compat(dev, net);
 1116}
 1117
 1118struct net_device *
 1119netdev_xa_find_lock(struct net *net, struct net_device *dev,
 1120		    unsigned long *index)
 1121{
 1122	if (dev)
 1123		netdev_unlock(dev);
 1124
 1125	do {
 1126		rcu_read_lock();
 1127		dev = xa_find(&net->dev_by_index, index, ULONG_MAX, XA_PRESENT);
 1128		if (!dev) {
 1129			rcu_read_unlock();
 1130			return NULL;
 1131		}
 1132		dev_hold(dev);
 1133		rcu_read_unlock();
 1134
 1135		dev = __netdev_put_lock(dev, net);
 1136		if (dev)
 1137			return dev;
 1138
 1139		(*index)++;
 1140	} while (true);
 1141}
 1142
 1143struct net_device *
 1144netdev_xa_find_lock_ops_compat(struct net *net, struct net_device *dev,
 1145			       unsigned long *index)
 1146{
 1147	if (dev)
 1148		netdev_unlock_ops_compat(dev);
 1149
 1150	do {
 1151		rcu_read_lock();
 1152		dev = xa_find(&net->dev_by_index, index, ULONG_MAX, XA_PRESENT);
 1153		if (!dev) {
 1154			rcu_read_unlock();
 1155			return NULL;
 1156		}
 1157		dev_hold(dev);
 1158		rcu_read_unlock();
 1159
 1160		dev = __netdev_put_lock_ops_compat(dev, net);
 1161		if (dev)
 1162			return dev;
 1163
 1164		(*index)++;
 1165	} while (true);
 1166}
 1167
 1168static DEFINE_SEQLOCK(netdev_rename_lock);
 1169
 1170void netdev_copy_name(struct net_device *dev, char *name)
 1171{
 1172	unsigned int seq;
 1173
 1174	do {
 1175		seq = read_seqbegin(&netdev_rename_lock);
 1176		strscpy(name, dev->name, IFNAMSIZ);
 1177	} while (read_seqretry(&netdev_rename_lock, seq));
 1178}
 1179EXPORT_IPV6_MOD_GPL(netdev_copy_name);
 1180
 1181/**
 1182 *	netdev_get_name - get a netdevice name, knowing its ifindex.
 1183 *	@net: network namespace
 1184 *	@name: a pointer to the buffer where the name will be stored.
 1185 *	@ifindex: the ifindex of the interface to get the name from.
 1186 */
 1187int netdev_get_name(struct net *net, char *name, int ifindex)
 1188{
 1189	struct net_device *dev;
 1190	int ret;
 1191
 1192	rcu_read_lock();
 1193
 1194	dev = dev_get_by_index_rcu(net, ifindex);
 1195	if (!dev) {
 1196		ret = -ENODEV;
 1197		goto out;
 1198	}
 1199
 1200	netdev_copy_name(dev, name);
 1201
 1202	ret = 0;
 1203out:
 1204	rcu_read_unlock();
 1205	return ret;
 1206}
 1207
 1208static bool dev_addr_cmp(struct net_device *dev, unsigned short type,
 1209			 const char *ha)
 1210{
 1211	return dev->type == type && !memcmp(dev->dev_addr, ha, dev->addr_len);
 1212}
 1213
 1214/**
 1215 *	dev_getbyhwaddr_rcu - find a device by its hardware address
 1216 *	@net: the applicable net namespace
 1217 *	@type: media type of device
 1218 *	@ha: hardware address
 1219 *
 1220 *	Search for an interface by MAC address. Returns NULL if the device
 1221 *	is not found or a pointer to the device.
 1222 *	The caller must hold RCU.
 1223 *	The returned device has not had its ref count increased
 1224 *	and the caller must therefore be careful about locking
 1225 *
 1226 */
 1227
 1228struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
 1229				       const char *ha)
 1230{
 1231	struct net_device *dev;
 1232
 1233	for_each_netdev_rcu(net, dev)
 1234		if (dev_addr_cmp(dev, type, ha))
 1235			return dev;
 1236
 1237	return NULL;
 1238}
 1239EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
 1240
 1241/**
 1242 * dev_getbyhwaddr() - find a device by its hardware address
 1243 * @net: the applicable net namespace
 1244 * @type: media type of device
 1245 * @ha: hardware address
 1246 *
 1247 * Similar to dev_getbyhwaddr_rcu(), but the owner needs to hold
 1248 * rtnl_lock.
 1249 *
 1250 * Context: rtnl_lock() must be held.
 1251 * Return: pointer to the net_device, or NULL if not found
 1252 */
 1253struct net_device *dev_getbyhwaddr(struct net *net, unsigned short type,
 1254				   const char *ha)
 1255{
 1256	struct net_device *dev;
 1257
 1258	ASSERT_RTNL();
 1259	for_each_netdev(net, dev)
 1260		if (dev_addr_cmp(dev, type, ha))
 1261			return dev;
 1262
 1263	return NULL;
 1264}
 1265EXPORT_SYMBOL(dev_getbyhwaddr);
 1266
 1267struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
 1268{
 1269	struct net_device *dev, *ret = NULL;
 1270
 1271	rcu_read_lock();
 1272	for_each_netdev_rcu(net, dev)
 1273		if (dev->type == type) {
 1274			dev_hold(dev);
 1275			ret = dev;
 1276			break;
 1277		}
 1278	rcu_read_unlock();
 1279	return ret;
 1280}
 1281EXPORT_SYMBOL(dev_getfirstbyhwtype);
 1282
 1283/**
 1284 * netdev_get_by_flags_rcu - find any device with given flags
 1285 * @net: the applicable net namespace
 1286 * @tracker: tracking object for the acquired reference
 1287 * @if_flags: IFF_* values
 1288 * @mask: bitmask of bits in if_flags to check
 1289 *
 1290 * Search for any interface with the given flags.
 1291 *
 1292 * Context: rcu_read_lock() must be held.
 1293 * Returns: NULL if a device is not found or a pointer to the device.
 1294 */
 1295struct net_device *netdev_get_by_flags_rcu(struct net *net, netdevice_tracker *tracker,
 1296					   unsigned short if_flags, unsigned short mask)
 1297{
 1298	struct net_device *dev;
 1299
 1300	for_each_netdev_rcu(net, dev) {
 1301		if (((READ_ONCE(dev->flags) ^ if_flags) & mask) == 0) {
 1302			netdev_hold(dev, tracker, GFP_ATOMIC);
 1303			return dev;
 1304		}
 1305	}
 1306
 1307	return NULL;
 1308}
 1309EXPORT_IPV6_MOD(netdev_get_by_flags_rcu);
 1310
 1311/**
 1312 *	dev_valid_name - check if name is okay for network device
 1313 *	@name: name string
 1314 *
 1315 *	Network device names need to be valid file names to
 1316 *	allow sysfs to work.  We also disallow any kind of
 1317 *	whitespace.
 1318 */
 1319bool dev_valid_name(const char *name)
 1320{
 1321	if (*name == '\0')
 1322		return false;
 1323	if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
 1324		return false;
 1325	if (!strcmp(name, ".") || !strcmp(name, ".."))
 1326		return false;
 1327
 1328	while (*name) {
 1329		if (*name == '/' || *name == ':' || isspace(*name))
 1330			return false;
 1331		name++;
 1332	}
 1333	return true;
 1334}
 1335EXPORT_SYMBOL(dev_valid_name);
 1336
 1337/**
 1338 *	__dev_alloc_name - allocate a name for a device
 1339 *	@net: network namespace to allocate the device name in
 1340 *	@name: name format string
 1341 *	@res: result name string
 1342 *
 1343 *	Passed a format string - eg "lt%d" it will try and find a suitable
 1344 *	id. It scans list of devices to build up a free map, then chooses
 1345 *	the first empty slot. The caller must hold the dev_base or rtnl lock
 1346 *	while allocating the name and adding the device in order to avoid
 1347 *	duplicates.
 1348 *	Limited to bits_per_byte * page size devices (ie 32K on most platforms).
 1349 *	Returns the number of the unit assigned or a negative errno code.
 1350 */
 1351
 1352static int __dev_alloc_name(struct net *net, const char *name, char *res)
 1353{
 1354	int i = 0;
 1355	const char *p;
 1356	const int max_netdevices = 8*PAGE_SIZE;
 1357	unsigned long *inuse;
 1358	struct net_device *d;
 1359	char buf[IFNAMSIZ];
 1360
 1361	/* Verify the string as this thing may have come from the user.
 1362	 * There must be one "%d" and no other "%" characters.
 1363	 */
 1364	p = strchr(name, '%');
 1365	if (!p || p[1] != 'd' || strchr(p + 2, '%'))
 1366		return -EINVAL;
 1367
 1368	/* Use one page as a bit array of possible slots */
 1369	inuse = bitmap_zalloc(max_netdevices, GFP_ATOMIC);
 1370	if (!inuse)
 1371		return -ENOMEM;
 1372
 1373	for_each_netdev(net, d) {
 1374		struct netdev_name_node *name_node;
 1375
 1376		netdev_for_each_altname(d, name_node) {
 1377			if (!sscanf(name_node->name, name, &i))
 1378				continue;
 1379			if (i < 0 || i >= max_netdevices)
 1380				continue;
 1381
 1382			/* avoid cases where sscanf is not exact inverse of printf */
 1383			snprintf(buf, IFNAMSIZ, name, i);
 1384			if (!strncmp(buf, name_node->name, IFNAMSIZ))
 1385				__set_bit(i, inuse);
 1386		}
 1387		if (!sscanf(d->name, name, &i))
 1388			continue;
 1389		if (i < 0 || i >= max_netdevices)
 1390			continue;
 1391
 1392		/* avoid cases where sscanf is not exact inverse of printf */
 1393		snprintf(buf, IFNAMSIZ, name, i);
 1394		if (!strncmp(buf, d->name, IFNAMSIZ))
 1395			__set_bit(i, inuse);
 1396	}
 1397
 1398	i = find_first_zero_bit(inuse, max_netdevices);
 1399	bitmap_free(inuse);
 1400	if (i == max_netdevices)
 1401		return -ENFILE;
 1402
 1403	/* 'res' and 'name' could overlap, use 'buf' as an intermediate buffer */
 1404	strscpy(buf, name, IFNAMSIZ);
 1405	snprintf(res, IFNAMSIZ, buf, i);
 1406	return i;
 1407}
 1408
 1409/* Returns negative errno or allocated unit id (see __dev_alloc_name()) */
 1410static int dev_prep_valid_name(struct net *net, struct net_device *dev,
 1411			       const char *want_name, char *out_name,
 1412			       int dup_errno)
 1413{
 1414	if (!dev_valid_name(want_name))
 1415		return -EINVAL;
 1416
 1417	if (strchr(want_name, '%'))
 1418		return __dev_alloc_name(net, want_name, out_name);
 1419
 1420	if (netdev_name_in_use(net, want_name))
 1421		return -dup_errno;
 1422	if (out_name != want_name)
 1423		strscpy(out_name, want_name, IFNAMSIZ);
 1424	return 0;
 1425}
 1426
 1427/**
 1428 *	dev_alloc_name - allocate a name for a device
 1429 *	@dev: device
 1430 *	@name: name format string
 1431 *
 1432 *	Passed a format string - eg "lt%d" it will try and find a suitable
 1433 *	id. It scans list of devices to build up a free map, then chooses
 1434 *	the first empty slot. The caller must hold the dev_base or rtnl lock
 1435 *	while allocating the name and adding the device in order to avoid
 1436 *	duplicates.
 1437 *	Limited to bits_per_byte * page size devices (ie 32K on most platforms).
 1438 *	Returns the number of the unit assigned or a negative errno code.
 1439 */
 1440
 1441int dev_alloc_name(struct net_device *dev, const char *name)
 1442{
 1443	return dev_prep_valid_name(dev_net(dev), dev, name, dev->name, ENFILE);
 1444}
 1445EXPORT_SYMBOL(dev_alloc_name);
 1446
 1447static int dev_get_valid_name(struct net *net, struct net_device *dev,
 1448			      const char *name)
 1449{
 1450	int ret;
 1451
 1452	ret = dev_prep_valid_name(net, dev, name, dev->name, EEXIST);
 1453	return ret < 0 ? ret : 0;
 1454}
 1455
 1456int netif_change_name(struct net_device *dev, const char *newname)
 1457{
 1458	struct net *net = dev_net(dev);
 1459	unsigned char old_assign_type;
 1460	char oldname[IFNAMSIZ];
 1461	int err = 0;
 1462	int ret;
 1463
 1464	ASSERT_RTNL_NET(net);
 1465
 1466	if (!strncmp(newname, dev->name, IFNAMSIZ))
 1467		return 0;
 1468
 1469	memcpy(oldname, dev->name, IFNAMSIZ);
 1470
 1471	write_seqlock_bh(&netdev_rename_lock);
 1472	err = dev_get_valid_name(net, dev, newname);
 1473	write_sequnlock_bh(&netdev_rename_lock);
 1474
 1475	if (err < 0)
 1476		return err;
 1477
 1478	if (oldname[0] && !strchr(oldname, '%'))
 1479		netdev_info(dev, "renamed from %s%s\n", oldname,
 1480			    dev->flags & IFF_UP ? " (while UP)" : "");
 1481
 1482	old_assign_type = dev->name_assign_type;
 1483	WRITE_ONCE(dev->name_assign_type, NET_NAME_RENAMED);
 1484
 1485rollback:
 1486	ret = device_rename(&dev->dev, dev->name);
 1487	if (ret) {
 1488		write_seqlock_bh(&netdev_rename_lock);
 1489		memcpy(dev->name, oldname, IFNAMSIZ);
 1490		write_sequnlock_bh(&netdev_rename_lock);
 1491		WRITE_ONCE(dev->name_assign_type, old_assign_type);
 1492		return ret;
 1493	}
 1494
 1495	netdev_adjacent_rename_links(dev, oldname);
 1496
 1497	netdev_name_node_del(dev->name_node);
 1498
 1499	synchronize_net();
 1500
 1501	netdev_name_node_add(net, dev->name_node);
 1502
 1503	ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
 1504	ret = notifier_to_errno(ret);
 1505
 1506	if (ret) {
 1507		/* err >= 0 after dev_alloc_name() or stores the first errno */
 1508		if (err >= 0) {
 1509			err = ret;
 1510			write_seqlock_bh(&netdev_rename_lock);
 1511			memcpy(dev->name, oldname, IFNAMSIZ);
 1512			write_sequnlock_bh(&netdev_rename_lock);
 1513			memcpy(oldname, newname, IFNAMSIZ);
 1514			WRITE_ONCE(dev->name_assign_type, old_assign_type);
 1515			old_assign_type = NET_NAME_RENAMED;
 1516			goto rollback;
 1517		} else {
 1518			netdev_err(dev, "name change rollback failed: %d\n",
 1519				   ret);
 1520		}
 1521	}
 1522
 1523	return err;
 1524}
 1525
 1526int netif_set_alias(struct net_device *dev, const char *alias, size_t len)
 1527{
 1528	struct dev_ifalias *new_alias = NULL;
 1529
 1530	if (len >= IFALIASZ)
 1531		return -EINVAL;
 1532
 1533	if (len) {
 1534		new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
 1535		if (!new_alias)
 1536			return -ENOMEM;
 1537
 1538		memcpy(new_alias->ifalias, alias, len);
 1539		new_alias->ifalias[len] = 0;
 1540	}
 1541
 1542	mutex_lock(&ifalias_mutex);
 1543	new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
 1544					mutex_is_locked(&ifalias_mutex));
 1545	mutex_unlock(&ifalias_mutex);
 1546
 1547	if (new_alias)
 1548		kfree_rcu(new_alias, rcuhead);
 1549
 1550	return len;
 1551}
 1552
 1553/**
 1554 *	dev_get_alias - get ifalias of a device
 1555 *	@dev: device
 1556 *	@name: buffer to store name of ifalias
 1557 *	@len: size of buffer
 1558 *
 1559 *	get ifalias for a device.  Caller must make sure dev cannot go
 1560 *	away,  e.g. rcu read lock or own a reference count to device.
 1561 */
 1562int dev_get_alias(const struct net_device *dev, char *name, size_t len)
 1563{
 1564	const struct dev_ifalias *alias;
 1565	int ret = 0;
 1566
 1567	rcu_read_lock();
 1568	alias = rcu_dereference(dev->ifalias);
 1569	if (alias)
 1570		ret = snprintf(name, len, "%s", alias->ifalias);
 1571	rcu_read_unlock();
 1572
 1573	return ret;
 1574}
 1575
 1576/**
 1577 *	netdev_features_change - device changes features
 1578 *	@dev: device to cause notification
 1579 *
 1580 *	Called to indicate a device has changed features.
 1581 */
 1582void netdev_features_change(struct net_device *dev)
 1583{
 1584	call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
 1585}
 1586EXPORT_SYMBOL(netdev_features_change);
 1587
 1588void netif_state_change(struct net_device *dev)
 1589{
 1590	netdev_ops_assert_locked_or_invisible(dev);
 1591
 1592	if (dev->flags & IFF_UP) {
 1593		struct netdev_notifier_change_info change_info = {
 1594			.info.dev = dev,
 1595		};
 1596
 1597		call_netdevice_notifiers_info(NETDEV_CHANGE,
 1598					      &change_info.info);
 1599		rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL, 0, NULL);
 1600	}
 1601}
 1602
 1603/**
 1604 * __netdev_notify_peers - notify network peers about existence of @dev,
 1605 * to be called when rtnl lock is already held.
 1606 * @dev: network device
 1607 *
 1608 * Generate traffic such that interested network peers are aware of
 1609 * @dev, such as by generating a gratuitous ARP. This may be used when
 1610 * a device wants to inform the rest of the network about some sort of
 1611 * reconfiguration such as a failover event or virtual machine
 1612 * migration.
 1613 */
 1614void __netdev_notify_peers(struct net_device *dev)
 1615{
 1616	ASSERT_RTNL();
 1617	call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
 1618	call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
 1619}
 1620EXPORT_SYMBOL(__netdev_notify_peers);
 1621
 1622/**
 1623 * netdev_notify_peers - notify network peers about existence of @dev
 1624 * @dev: network device
 1625 *
 1626 * Generate traffic such that interested network peers are aware of
 1627 * @dev, such as by generating a gratuitous ARP. This may be used when
 1628 * a device wants to inform the rest of the network about some sort of
 1629 * reconfiguration such as a failover event or virtual machine
 1630 * migration.
 1631 */
 1632void netdev_notify_peers(struct net_device *dev)
 1633{
 1634	rtnl_lock();
 1635	__netdev_notify_peers(dev);
 1636	rtnl_unlock();
 1637}
 1638EXPORT_SYMBOL(netdev_notify_peers);
 1639
 1640static int napi_threaded_poll(void *data);
 1641
 1642static int napi_kthread_create(struct napi_struct *n)
 1643{
 1644	int err = 0;
 1645
 1646	/* Create and wake up the kthread once to put it in
 1647	 * TASK_INTERRUPTIBLE mode to avoid the blocked task
 1648	 * warning and work with loadavg.
 1649	 */
 1650	n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d",
 1651				n->dev->name, n->napi_id);
 1652	if (IS_ERR(n->thread)) {
 1653		err = PTR_ERR(n->thread);
 1654		pr_err("kthread_run failed with err %d\n", err);
 1655		n->thread = NULL;
 1656	}
 1657
 1658	return err;
 1659}
 1660
 1661static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
 1662{
 1663	const struct net_device_ops *ops = dev->netdev_ops;
 1664	int ret;
 1665
 1666	ASSERT_RTNL();
 1667	dev_addr_check(dev);
 1668
 1669	if (!netif_device_present(dev)) {
 1670		/* may be detached because parent is runtime-suspended */
 1671		if (dev->dev.parent)
 1672			pm_runtime_resume(dev->dev.parent);
 1673		if (!netif_device_present(dev))
 1674			return -ENODEV;
 1675	}
 1676
 1677	/* Block netpoll from trying to do any rx path servicing.
 1678	 * If we don't do this there is a chance ndo_poll_controller
 1679	 * or ndo_poll may be running while we open the device
 1680	 */
 1681	netpoll_poll_disable(dev);
 1682
 1683	ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
 1684	ret = notifier_to_errno(ret);
 1685	if (ret)
 1686		return ret;
 1687
 1688	set_bit(__LINK_STATE_START, &dev->state);
 1689
 1690	netdev_ops_assert_locked(dev);
 1691
 1692	if (ops->ndo_validate_addr)
 1693		ret = ops->ndo_validate_addr(dev);
 1694
 1695	if (!ret && ops->ndo_open)
 1696		ret = ops->ndo_open(dev);
 1697
 1698	netpoll_poll_enable(dev);
 1699
 1700	if (ret)
 1701		clear_bit(__LINK_STATE_START, &dev->state);
 1702	else {
 1703		netif_set_up(dev, true);
 1704		dev_set_rx_mode(dev);
 1705		dev_activate(dev);
 1706		add_device_randomness(dev->dev_addr, dev->addr_len);
 1707	}
 1708
 1709	return ret;
 1710}
 1711
 1712int netif_open(struct net_device *dev, struct netlink_ext_ack *extack)
 1713{
 1714	int ret;
 1715
 1716	if (dev->flags & IFF_UP)
 1717		return 0;
 1718
 1719	ret = __dev_open(dev, extack);
 1720	if (ret < 0)
 1721		return ret;
 1722
 1723	rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
 1724	call_netdevice_notifiers(NETDEV_UP, dev);
 1725
 1726	return ret;
 1727}
 1728
 1729static void __dev_close_many(struct list_head *head)
 1730{
 1731	struct net_device *dev;
 1732
 1733	ASSERT_RTNL();
 1734	might_sleep();
 1735
 1736	list_for_each_entry(dev, head, close_list) {
 1737		/* Temporarily disable netpoll until the interface is down */
 1738		netpoll_poll_disable(dev);
 1739
 1740		call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
 1741
 1742		clear_bit(__LINK_STATE_START, &dev->state);
 1743
 1744		/* Synchronize to scheduled poll. We cannot touch poll list, it
 1745		 * can be even on different cpu. So just clear netif_running().
 1746		 *
 1747		 * dev->stop() will invoke napi_disable() on all of it's
 1748		 * napi_struct instances on this device.
 1749		 */
 1750		smp_mb__after_atomic(); /* Commit netif_running(). */
 1751	}
 1752
 1753	dev_deactivate_many(head);
 1754
 1755	list_for_each_entry(dev, head, close_list) {
 1756		const struct net_device_ops *ops = dev->netdev_ops;
 1757
 1758		/*
 1759		 *	Call the device specific close. This cannot fail.
 1760		 *	Only if device is UP
 1761		 *
 1762		 *	We allow it to be called even after a DETACH hot-plug
 1763		 *	event.
 1764		 */
 1765
 1766		netdev_ops_assert_locked(dev);
 1767
 1768		if (ops->ndo_stop)
 1769			ops->ndo_stop(dev);
 1770
 1771		netif_set_up(dev, false);
 1772		netpoll_poll_enable(dev);
 1773	}
 1774}
 1775
 1776static void __dev_close(struct net_device *dev)
 1777{
 1778	LIST_HEAD(single);
 1779
 1780	list_add(&dev->close_list, &single);
 1781	__dev_close_many(&single);
 1782	list_del(&single);
 1783}
 1784
 1785void netif_close_many(struct list_head *head, bool unlink)
 1786{
 1787	struct net_device *dev, *tmp;
 1788
 1789	/* Remove the devices that don't need to be closed */
 1790	list_for_each_entry_safe(dev, tmp, head, close_list)
 1791		if (!(dev->flags & IFF_UP))
 1792			list_del_init(&dev->close_list);
 1793
 1794	__dev_close_many(head);
 1795
 1796	list_for_each_entry_safe(dev, tmp, head, close_list) {
 1797		rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
 1798		call_netdevice_notifiers(NETDEV_DOWN, dev);
 1799		if (unlink)
 1800			list_del_init(&dev->close_list);
 1801	}
 1802}
 1803EXPORT_SYMBOL_NS_GPL(netif_close_many, "NETDEV_INTERNAL");
 1804
 1805void netif_close(struct net_device *dev)
 1806{
 1807	if (dev->flags & IFF_UP) {
 1808		LIST_HEAD(single);
 1809
 1810		list_add(&dev->close_list, &single);
 1811		netif_close_many(&single, true);
 1812		list_del(&single);
 1813	}
 1814}
 1815EXPORT_SYMBOL(netif_close);
 1816
 1817void netif_disable_lro(struct net_device *dev)
 1818{
 1819	struct net_device *lower_dev;
 1820	struct list_head *iter;
 1821
 1822	dev->wanted_features &= ~NETIF_F_LRO;
 1823	netdev_update_features(dev);
 1824
 1825	if (unlikely(dev->features & NETIF_F_LRO))
 1826		netdev_WARN(dev, "failed to disable LRO!\n");
 1827
 1828	netdev_for_each_lower_dev(dev, lower_dev, iter) {
 1829		netdev_lock_ops(lower_dev);
 1830		netif_disable_lro(lower_dev);
 1831		netdev_unlock_ops(lower_dev);
 1832	}
 1833}
 1834EXPORT_IPV6_MOD(netif_disable_lro);
 1835
 1836/**
 1837 *	dev_disable_gro_hw - disable HW Generic Receive Offload on a device
 1838 *	@dev: device
 1839 *
 1840 *	Disable HW Generic Receive Offload (GRO_HW) on a net device.  Must be
 1841 *	called under RTNL.  This is needed if Generic XDP is installed on
 1842 *	the device.
 1843 */
 1844static void dev_disable_gro_hw(struct net_device *dev)
 1845{
 1846	dev->wanted_features &= ~NETIF_F_GRO_HW;
 1847	netdev_update_features(dev);
 1848
 1849	if (unlikely(dev->features & NETIF_F_GRO_HW))
 1850		netdev_WARN(dev, "failed to disable GRO_HW!\n");
 1851}
 1852
 1853const char *netdev_cmd_to_name(enum netdev_cmd cmd)
 1854{
 1855#define N(val) 						\
 1856	case NETDEV_##val:				\
 1857		return "NETDEV_" __stringify(val);
 1858	switch (cmd) {
 1859	N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
 1860	N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
 1861	N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
 1862	N(POST_INIT) N(PRE_UNINIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN)
 1863	N(CHANGEUPPER) N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA)
 1864	N(BONDING_INFO) N(PRECHANGEUPPER) N(CHANGELOWERSTATE)
 1865	N(UDP_TUNNEL_PUSH_INFO) N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
 1866	N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
 1867	N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
 1868	N(PRE_CHANGEADDR) N(OFFLOAD_XSTATS_ENABLE) N(OFFLOAD_XSTATS_DISABLE)
 1869	N(OFFLOAD_XSTATS_REPORT_USED) N(OFFLOAD_XSTATS_REPORT_DELTA)
 1870	N(XDP_FEAT_CHANGE)
 1871	}
 1872#undef N
 1873	return "UNKNOWN_NETDEV_EVENT";
 1874}
 1875EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
 1876
 1877static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
 1878				   struct net_device *dev)
 1879{
 1880	struct netdev_notifier_info info = {
 1881		.dev = dev,
 1882	};
 1883
 1884	return nb->notifier_call(nb, val, &info);
 1885}
 1886
 1887static int call_netdevice_register_notifiers(struct notifier_block *nb,
 1888					     struct net_device *dev)
 1889{
 1890	int err;
 1891
 1892	err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
 1893	err = notifier_to_errno(err);
 1894	if (err)
 1895		return err;
 1896
 1897	if (!(dev->flags & IFF_UP))
 1898		return 0;
 1899
 1900	call_netdevice_notifier(nb, NETDEV_UP, dev);
 1901	return 0;
 1902}
 1903
 1904static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
 1905						struct net_device *dev)
 1906{
 1907	if (dev->flags & IFF_UP) {
 1908		call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
 1909					dev);
 1910		call_netdevice_notifier(nb, NETDEV_DOWN, dev);
 1911	}
 1912	call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
 1913}
 1914
 1915static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
 1916						 struct net *net)
 1917{
 1918	struct net_device *dev;
 1919	int err;
 1920
 1921	for_each_netdev(net, dev) {
 1922		netdev_lock_ops(dev);
 1923		err = call_netdevice_register_notifiers(nb, dev);
 1924		netdev_unlock_ops(dev);
 1925		if (err)
 1926			goto rollback;
 1927	}
 1928	return 0;
 1929
 1930rollback:
 1931	for_each_netdev_continue_reverse(net, dev)
 1932		call_netdevice_unregister_notifiers(nb, dev);
 1933	return err;
 1934}
 1935
 1936static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
 1937						    struct net *net)
 1938{
 1939	struct net_device *dev;
 1940
 1941	for_each_netdev(net, dev)
 1942		call_netdevice_unregister_notifiers(nb, dev);
 1943}
 1944
 1945static int dev_boot_phase = 1;
 1946
 1947/**
 1948 * register_netdevice_notifier - register a network notifier block
 1949 * @nb: notifier
 1950 *
 1951 * Register a notifier to be called when network device events occur.
 1952 * The notifier passed is linked into the kernel structures and must
 1953 * not be reused until it has been unregistered. A negative errno code
 1954 * is returned on a failure.
 1955 *
 1956 * When registered all registration and up events are replayed
 1957 * to the new notifier to allow device to have a race free
 1958 * view of the network device list.
 1959 */
 1960
 1961int register_netdevice_notifier(struct notifier_block *nb)
 1962{
 1963	struct net *net;
 1964	int err;
 1965
 1966	/* Close race with setup_net() and cleanup_net() */
 1967	down_write(&pernet_ops_rwsem);
 1968
 1969	/* When RTNL is removed, we need protection for netdev_chain. */
 1970	rtnl_lock();
 1971
 1972	err = raw_notifier_chain_register(&netdev_chain, nb);
 1973	if (err)
 1974		goto unlock;
 1975	if (dev_boot_phase)
 1976		goto unlock;
 1977	for_each_net(net) {
 1978		__rtnl_net_lock(net);
 1979		err = call_netdevice_register_net_notifiers(nb, net);
 1980		__rtnl_net_unlock(net);
 1981		if (err)
 1982			goto rollback;
 1983	}
 1984
 1985unlock:
 1986	rtnl_unlock();
 1987	up_write(&pernet_ops_rwsem);
 1988	return err;
 1989
 1990rollback:
 1991	for_each_net_continue_reverse(net) {
 1992		__rtnl_net_lock(net);
 1993		call_netdevice_unregister_net_notifiers(nb, net);
 1994		__rtnl_net_unlock(net);
 1995	}
 1996
 1997	raw_notifier_chain_unregister(&netdev_chain, nb);
 1998	goto unlock;
 1999}
 2000EXPORT_SYMBOL(register_netdevice_notifier);
 2001
 2002/**
 2003 * unregister_netdevice_notifier - unregister a network notifier block
 2004 * @nb: notifier
 2005 *
 2006 * Unregister a notifier previously registered by
 2007 * register_netdevice_notifier(). The notifier is unlinked into the
 2008 * kernel structures and may then be reused. A negative errno code
 2009 * is returned on a failure.
 2010 *
 2011 * After unregistering unregister and down device events are synthesized
 2012 * for all devices on the device list to the removed notifier to remove
 2013 * the need for special case cleanup code.
 2014 */
 2015
 2016int unregister_netdevice_notifier(struct notifier_block *nb)
 2017{
 2018	struct net *net;
 2019	int err;
 2020
 2021	/* Close race with setup_net() and cleanup_net() */
 2022	down_write(&pernet_ops_rwsem);
 2023	rtnl_lock();
 2024	err = raw_notifier_chain_unregister(&netdev_chain, nb);
 2025	if (err)
 2026		goto unlock;
 2027
 2028	for_each_net(net) {
 2029		__rtnl_net_lock(net);
 2030		call_netdevice_unregister_net_notifiers(nb, net);
 2031		__rtnl_net_unlock(net);
 2032	}
 2033
 2034unlock:
 2035	rtnl_unlock();
 2036	up_write(&pernet_ops_rwsem);
 2037	return err;
 2038}
 2039EXPORT_SYMBOL(unregister_netdevice_notifier);
 2040
 2041static int __register_netdevice_notifier_net(struct net *net,
 2042					     struct notifier_block *nb,
 2043					     bool ignore_call_fail)
 2044{
 2045	int err;
 2046
 2047	err = raw_notifier_chain_register(&net->netdev_chain, nb);
 2048	if (err)
 2049		return err;
 2050	if (dev_boot_phase)
 2051		return 0;
 2052
 2053	err = call_netdevice_register_net_notifiers(nb, net);
 2054	if (err && !ignore_call_fail)
 2055		goto chain_unregister;
 2056
 2057	return 0;
 2058
 2059chain_unregister:
 2060	raw_notifier_chain_unregister(&net->netdev_chain, nb);
 2061	return err;
 2062}
 2063
 2064static int __unregister_netdevice_notifier_net(struct net *net,
 2065					       struct notifier_block *nb)
 2066{
 2067	int err;
 2068
 2069	err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
 2070	if (err)
 2071		return err;
 2072
 2073	call_netdevice_unregister_net_notifiers(nb, net);
 2074	return 0;
 2075}
 2076
 2077/**
 2078 * register_netdevice_notifier_net - register a per-netns network notifier block
 2079 * @net: network namespace
 2080 * @nb: notifier
 2081 *
 2082 * Register a notifier to be called when network device events occur.
 2083 * The notifier passed is linked into the kernel structures and must
 2084 * not be reused until it has been unregistered. A negative errno code
 2085 * is returned on a failure.
 2086 *
 2087 * When registered all registration and up events are replayed
 2088 * to the new notifier to allow device to have a race free
 2089 * view of the network device list.
 2090 */
 2091
 2092int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
 2093{
 2094	int err;
 2095
 2096	rtnl_net_lock(net);
 2097	err = __register_netdevice_notifier_net(net, nb, false);
 2098	rtnl_net_unlock(net);
 2099
 2100	return err;
 2101}
 2102EXPORT_SYMBOL(register_netdevice_notifier_net);
 2103
 2104/**
 2105 * unregister_netdevice_notifier_net - unregister a per-netns
 2106 *                                     network notifier block
 2107 * @net: network namespace
 2108 * @nb: notifier
 2109 *
 2110 * Unregister a notifier previously registered by
 2111 * register_netdevice_notifier_net(). The notifier is unlinked from the
 2112 * kernel structures and may then be reused. A negative errno code
 2113 * is returned on a failure.
 2114 *
 2115 * After unregistering unregister and down device events are synthesized
 2116 * for all devices on the device list to the removed notifier to remove
 2117 * the need for special case cleanup code.
 2118 */
 2119
 2120int unregister_netdevice_notifier_net(struct net *net,
 2121				      struct notifier_block *nb)
 2122{
 2123	int err;
 2124
 2125	rtnl_net_lock(net);
 2126	err = __unregister_netdevice_notifier_net(net, nb);
 2127	rtnl_net_unlock(net);
 2128
 2129	return err;
 2130}
 2131EXPORT_SYMBOL(unregister_netdevice_notifier_net);
 2132
 2133static void __move_netdevice_notifier_net(struct net *src_net,
 2134					  struct net *dst_net,
 2135					  struct notifier_block *nb)
 2136{
 2137	__unregister_netdevice_notifier_net(src_net, nb);
 2138	__register_netdevice_notifier_net(dst_net, nb, true);
 2139}
 2140
 2141static void rtnl_net_dev_lock(struct net_device *dev)
 2142{
 2143	bool again;
 2144
 2145	do {
 2146		struct net *net;
 2147
 2148		again = false;
 2149
 2150		/* netns might be being dismantled. */
 2151		rcu_read_lock();
 2152		net = dev_net_rcu(dev);
 2153		net_passive_inc(net);
 2154		rcu_read_unlock();
 2155
 2156		rtnl_net_lock(net);
 2157
 2158#ifdef CONFIG_NET_NS
 2159		/* dev might have been moved to another netns. */
 2160		if (!net_eq(net, rcu_access_pointer(dev->nd_net.net))) {
 2161			rtnl_net_unlock(net);
 2162			net_passive_dec(net);
 2163			again = true;
 2164		}
 2165#endif
 2166	} while (again);
 2167}
 2168
 2169static void rtnl_net_dev_unlock(struct net_device *dev)
 2170{
 2171	struct net *net = dev_net(dev);
 2172
 2173	rtnl_net_unlock(net);
 2174	net_passive_dec(net);
 2175}
 2176
 2177int register_netdevice_notifier_dev_net(struct net_device *dev,
 2178					struct notifier_block *nb,
 2179					struct netdev_net_notifier *nn)
 2180{
 2181	int err;
 2182
 2183	rtnl_net_dev_lock(dev);
 2184	err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
 2185	if (!err) {
 2186		nn->nb = nb;
 2187		list_add(&nn->list, &dev->net_notifier_list);
 2188	}
 2189	rtnl_net_dev_unlock(dev);
 2190
 2191	return err;
 2192}
 2193EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
 2194
 2195int unregister_netdevice_notifier_dev_net(struct net_device *dev,
 2196					  struct notifier_block *nb,
 2197					  struct netdev_net_notifier *nn)
 2198{
 2199	int err;
 2200
 2201	rtnl_net_dev_lock(dev);
 2202	list_del(&nn->list);
 2203	err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
 2204	rtnl_net_dev_unlock(dev);
 2205
 2206	return err;
 2207}
 2208EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
 2209
 2210static void move_netdevice_notifiers_dev_net(struct net_device *dev,
 2211					     struct net *net)
 2212{
 2213	struct netdev_net_notifier *nn;
 2214
 2215	list_for_each_entry(nn, &dev->net_notifier_list, list)
 2216		__move_netdevice_notifier_net(dev_net(dev), net, nn->nb);
 2217}
 2218
 2219/**
 2220 *	call_netdevice_notifiers_info - call all network notifier blocks
 2221 *	@val: value passed unmodified to notifier function
 2222 *	@info: notifier information data
 2223 *
 2224 *	Call all network notifier blocks.  Parameters and return value
 2225 *	are as for raw_notifier_call_chain().
 2226 */
 2227
 2228int call_netdevice_notifiers_info(unsigned long val,
 2229				  struct netdev_notifier_info *info)
 2230{
 2231	struct net *net = dev_net(info->dev);
 2232	int ret;
 2233
 2234	ASSERT_RTNL();
 2235
 2236	/* Run per-netns notifier block chain first, then run the global one.
 2237	 * Hopefully, one day, the global one is going to be removed after
 2238	 * all notifier block registrators get converted to be per-netns.
 2239	 */
 2240	ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
 2241	if (ret & NOTIFY_STOP_MASK)
 2242		return ret;
 2243	return raw_notifier_call_chain(&netdev_chain, val, info);
 2244}
 2245
 2246/**
 2247 *	call_netdevice_notifiers_info_robust - call per-netns notifier blocks
 2248 *	                                       for and rollback on error
 2249 *	@val_up: value passed unmodified to notifier function
 2250 *	@val_down: value passed unmodified to the notifier function when
 2251 *	           recovering from an error on @val_up
 2252 *	@info: notifier information data
 2253 *
 2254 *	Call all per-netns network notifier blocks, but not notifier blocks on
 2255 *	the global notifier chain. Parameters and return value are as for
 2256 *	raw_notifier_call_chain_robust().
 2257 */
 2258
 2259static int
 2260call_netdevice_notifiers_info_robust(unsigned long val_up,
 2261				     unsigned long val_down,
 2262				     struct netdev_notifier_info *info)
 2263{
 2264	struct net *net = dev_net(info->dev);
 2265
 2266	ASSERT_RTNL();
 2267
 2268	return raw_notifier_call_chain_robust(&net->netdev_chain,
 2269					      val_up, val_down, info);
 2270}
 2271
 2272static int call_netdevice_notifiers_extack(unsigned long val,
 2273					   struct net_device *dev,
 2274					   struct netlink_ext_ack *extack)
 2275{
 2276	struct netdev_notifier_info info = {
 2277		.dev = dev,
 2278		.extack = extack,
 2279	};
 2280
 2281	return call_netdevice_notifiers_info(val, &info);
 2282}
 2283
 2284/**
 2285 *	call_netdevice_notifiers - call all network notifier blocks
 2286 *      @val: value passed unmodified to notifier function
 2287 *      @dev: net_device pointer passed unmodified to notifier function
 2288 *
 2289 *	Call all network notifier blocks.  Parameters and return value
 2290 *	are as for raw_notifier_call_chain().
 2291 */
 2292
 2293int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
 2294{
 2295	return call_netdevice_notifiers_extack(val, dev, NULL);
 2296}
 2297EXPORT_SYMBOL(call_netdevice_notifiers);
 2298
 2299/**
 2300 *	call_netdevice_notifiers_mtu - call all network notifier blocks
 2301 *	@val: value passed unmodified to notifier function
 2302 *	@dev: net_device pointer passed unmodified to notifier function
 2303 *	@arg: additional u32 argument passed to the notifier function
 2304 *
 2305 *	Call all network notifier blocks.  Parameters and return value
 2306 *	are as for raw_notifier_call_chain().
 2307 */
 2308static int call_netdevice_notifiers_mtu(unsigned long val,
 2309					struct net_device *dev, u32 arg)
 2310{
 2311	struct netdev_notifier_info_ext info = {
 2312		.info.dev = dev,
 2313		.ext.mtu = arg,
 2314	};
 2315
 2316	BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
 2317
 2318	return call_netdevice_notifiers_info(val, &info.info);
 2319}
 2320
 2321#ifdef CONFIG_NET_INGRESS
 2322static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
 2323
 2324void net_inc_ingress_queue(void)
 2325{
 2326	static_branch_inc(&ingress_needed_key);
 2327}
 2328EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
 2329
 2330void net_dec_ingress_queue(void)
 2331{
 2332	static_branch_dec(&ingress_needed_key);
 2333}
 2334EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
 2335#endif
 2336
 2337#ifdef CONFIG_NET_EGRESS
 2338static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
 2339
 2340void net_inc_egress_queue(void)
 2341{
 2342	static_branch_inc(&egress_needed_key);
 2343}
 2344EXPORT_SYMBOL_GPL(net_inc_egress_queue);
 2345
 2346void net_dec_egress_queue(void)
 2347{
 2348	static_branch_dec(&egress_needed_key);
 2349}
 2350EXPORT_SYMBOL_GPL(net_dec_egress_queue);
 2351#endif
 2352
 2353#ifdef CONFIG_NET_CLS_ACT
 2354DEFINE_STATIC_KEY_FALSE(tcf_sw_enabled_key);
 2355EXPORT_SYMBOL(tcf_sw_enabled_key);
 2356#endif
 2357
 2358DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
 2359EXPORT_SYMBOL(netstamp_needed_key);
 2360#ifdef CONFIG_JUMP_LABEL
 2361static atomic_t netstamp_needed_deferred;
 2362static atomic_t netstamp_wanted;
 2363static void netstamp_clear(struct work_struct *work)
 2364{
 2365	int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
 2366	int wanted;
 2367
 2368	wanted = atomic_add_return(deferred, &netstamp_wanted);
 2369	if (wanted > 0)
 2370		static_branch_enable(&netstamp_needed_key);
 2371	else
 2372		static_branch_disable(&netstamp_needed_key);
 2373}
 2374static DECLARE_WORK(netstamp_work, netstamp_clear);
 2375#endif
 2376
 2377void net_enable_timestamp(void)
 2378{
 2379#ifdef CONFIG_JUMP_LABEL
 2380	int wanted = atomic_read(&netstamp_wanted);
 2381
 2382	while (wanted > 0) {
 2383		if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted + 1))
 2384			return;
 2385	}
 2386	atomic_inc(&netstamp_needed_deferred);
 2387	schedule_work(&netstamp_work);
 2388#else
 2389	static_branch_inc(&netstamp_needed_key);
 2390#endif
 2391}
 2392EXPORT_SYMBOL(net_enable_timestamp);
 2393
 2394void net_disable_timestamp(void)
 2395{
 2396#ifdef CONFIG_JUMP_LABEL
 2397	int wanted = atomic_read(&netstamp_wanted);
 2398
 2399	while (wanted > 1) {
 2400		if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted - 1))
 2401			return;
 2402	}
 2403	atomic_dec(&netstamp_needed_deferred);
 2404	schedule_work(&netstamp_work);
 2405#else
 2406	static_branch_dec(&netstamp_needed_key);
 2407#endif
 2408}
 2409EXPORT_SYMBOL(net_disable_timestamp);
 2410
 2411static inline void net_timestamp_set(struct sk_buff *skb)
 2412{
 2413	skb->tstamp = 0;
 2414	skb->tstamp_type = SKB_CLOCK_REALTIME;
 2415	if (static_branch_unlikely(&netstamp_needed_key))
 2416		skb->tstamp = ktime_get_real();
 2417}
 2418
 2419#define net_timestamp_check(COND, SKB)				\
 2420	if (static_branch_unlikely(&netstamp_needed_key)) {	\
 2421		if ((COND) && !(SKB)->tstamp)			\
 2422			(SKB)->tstamp = ktime_get_real();	\
 2423	}							\
 2424
 2425bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
 2426{
 2427	return __is_skb_forwardable(dev, skb, true);
 2428}
 2429EXPORT_SYMBOL_GPL(is_skb_forwardable);
 2430
 2431static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb,
 2432			      bool check_mtu)
 2433{
 2434	int ret = ____dev_forward_skb(dev, skb, check_mtu);
 2435
 2436	if (likely(!ret)) {
 2437		skb->protocol = eth_type_trans(skb, dev);
 2438		skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
 2439	}
 2440
 2441	return ret;
 2442}
 2443
 2444int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
 2445{
 2446	return __dev_forward_skb2(dev, skb, true);
 2447}
 2448EXPORT_SYMBOL_GPL(__dev_forward_skb);
 2449
 2450/**
 2451 * dev_forward_skb - loopback an skb to another netif
 2452 *
 2453 * @dev: destination network device
 2454 * @skb: buffer to forward
 2455 *
 2456 * return values:
 2457 *	NET_RX_SUCCESS	(no congestion)
 2458 *	NET_RX_DROP     (packet was dropped, but freed)
 2459 *
 2460 * dev_forward_skb can be used for injecting an skb from the
 2461 * start_xmit function of one device into the receive queue
 2462 * of another device.
 2463 *
 2464 * The receiving device may be in another namespace, so
 2465 * we have to clear all information in the skb that could
 2466 * impact namespace isolation.
 2467 */
 2468int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
 2469{
 2470	return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
 2471}
 2472EXPORT_SYMBOL_GPL(dev_forward_skb);
 2473
 2474int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb)
 2475{
 2476	return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb);
 2477}
 2478
 2479static int deliver_skb(struct sk_buff *skb,
 2480		       struct packet_type *pt_prev,
 2481		       struct net_device *orig_dev)
 2482{
 2483	if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
 2484		return -ENOMEM;
 2485	refcount_inc(&skb->users);
 2486	return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
 2487}
 2488
 2489static inline void deliver_ptype_list_skb(struct sk_buff *skb,
 2490					  struct packet_type **pt,
 2491					  struct net_device *orig_dev,
 2492					  __be16 type,
 2493					  struct list_head *ptype_list)
 2494{
 2495	struct packet_type *ptype, *pt_prev = *pt;
 2496
 2497	list_for_each_entry_rcu(ptype, ptype_list, list) {
 2498		if (ptype->type != type)
 2499			continue;
 2500		if (unlikely(pt_prev))
 2501			deliver_skb(skb, pt_prev, orig_dev);
 2502		pt_prev = ptype;
 2503	}
 2504	*pt = pt_prev;
 2505}
 2506
 2507static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
 2508{
 2509	if (!ptype->af_packet_priv || !skb->sk)
 2510		return false;
 2511
 2512	if (ptype->id_match)
 2513		return ptype->id_match(ptype, skb->sk);
 2514	else if ((struct sock *)ptype->af_packet_priv == skb->sk)
 2515		return true;
 2516
 2517	return false;
 2518}
 2519
 2520/**
 2521 * dev_nit_active_rcu - return true if any network interface taps are in use
 2522 *
 2523 * The caller must hold the RCU lock
 2524 *
 2525 * @dev: network device to check for the presence of taps
 2526 */
 2527bool dev_nit_active_rcu(const struct net_device *dev)
 2528{
 2529	/* Callers may hold either RCU or RCU BH lock */
 2530	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
 2531
 2532	return !list_empty(&dev_net(dev)->ptype_all) ||
 2533	       !list_empty(&dev->ptype_all);
 2534}
 2535EXPORT_SYMBOL_GPL(dev_nit_active_rcu);
 2536
 2537/*
 2538 *	Support routine. Sends outgoing frames to any network
 2539 *	taps currently in use.
 2540 */
 2541
 2542void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
 2543{
 2544	struct packet_type *ptype, *pt_prev = NULL;
 2545	struct list_head *ptype_list;
 2546	struct sk_buff *skb2 = NULL;
 2547
 2548	rcu_read_lock();
 2549	ptype_list = &dev_net_rcu(dev)->ptype_all;
 2550again:
 2551	list_for_each_entry_rcu(ptype, ptype_list, list) {
 2552		if (READ_ONCE(ptype->ignore_outgoing))
 2553			continue;
 2554
 2555		/* Never send packets back to the socket
 2556		 * they originated from - MvS (miquels@drinkel.ow.org)
 2557		 */
 2558		if (skb_loop_sk(ptype, skb))
 2559			continue;
 2560
 2561		if (unlikely(pt_prev)) {
 2562			deliver_skb(skb2, pt_prev, skb->dev);
 2563			pt_prev = ptype;
 2564			continue;
 2565		}
 2566
 2567		/* need to clone skb, done only once */
 2568		skb2 = skb_clone(skb, GFP_ATOMIC);
 2569		if (!skb2)
 2570			goto out_unlock;
 2571
 2572		net_timestamp_set(skb2);
 2573
 2574		/* skb->nh should be correctly
 2575		 * set by sender, so that the second statement is
 2576		 * just protection against buggy protocols.
 2577		 */
 2578		skb_reset_mac_header(skb2);
 2579
 2580		if (skb_network_header(skb2) < skb2->data ||
 2581		    skb_network_header(skb2) > skb_tail_pointer(skb2)) {
 2582			net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
 2583					     ntohs(skb2->protocol),
 2584					     dev->name);
 2585			skb_reset_network_header(skb2);
 2586		}
 2587
 2588		skb2->transport_header = skb2->network_header;
 2589		skb2->pkt_type = PACKET_OUTGOING;
 2590		pt_prev = ptype;
 2591	}
 2592
 2593	if (ptype_list != &dev->ptype_all) {
 2594		ptype_list = &dev->ptype_all;
 2595		goto again;
 2596	}
 2597out_unlock:
 2598	if (pt_prev) {
 2599		if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
 2600			pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
 2601		else
 2602			kfree_skb(skb2);
 2603	}
 2604	rcu_read_unlock();
 2605}
 2606EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
 2607
 2608/**
 2609 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
 2610 * @dev: Network device
 2611 * @txq: number of queues available
 2612 *
 2613 * If real_num_tx_queues is changed the tc mappings may no longer be
 2614 * valid. To resolve this verify the tc mapping remains valid and if
 2615 * not NULL the mapping. With no priorities mapping to this
 2616 * offset/count pair it will no longer be used. In the worst case TC0
 2617 * is invalid nothing can be done so disable priority mappings. If is
 2618 * expected that drivers will fix this mapping if they can before
 2619 * calling netif_set_real_num_tx_queues.
 2620 */
 2621static void netif_setup_tc(struct net_device *dev, unsigned int txq)
 2622{
 2623	int i;
 2624	struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
 2625
 2626	/* If TC0 is invalidated disable TC mapping */
 2627	if (tc->offset + tc->count > txq) {
 2628		netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
 2629		dev->num_tc = 0;
 2630		return;
 2631	}
 2632
 2633	/* Invalidated prio to tc mappings set to TC0 */
 2634	for (i = 1; i < TC_BITMASK + 1; i++) {
 2635		int q = netdev_get_prio_tc_map(dev, i);
 2636
 2637		tc = &dev->tc_to_txq[q];
 2638		if (tc->offset + tc->count > txq) {
 2639			netdev_warn(dev, "Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
 2640				    i, q);
 2641			netdev_set_prio_tc_map(dev, i, 0);
 2642		}
 2643	}
 2644}
 2645
 2646int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
 2647{
 2648	if (dev->num_tc) {
 2649		struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
 2650		int i;
 2651
 2652		/* walk through the TCs and see if it falls into any of them */
 2653		for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
 2654			if ((txq - tc->offset) < tc->count)
 2655				return i;
 2656		}
 2657
 2658		/* didn't find it, just return -1 to indicate no match */
 2659		return -1;
 2660	}
 2661
 2662	return 0;
 2663}
 2664EXPORT_SYMBOL(netdev_txq_to_tc);
 2665
 2666#ifdef CONFIG_XPS
 2667static struct static_key xps_needed __read_mostly;
 2668static struct static_key xps_rxqs_needed __read_mostly;
 2669static DEFINE_MUTEX(xps_map_mutex);
 2670#define xmap_dereference(P)		\
 2671	rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
 2672
 2673static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
 2674			     struct xps_dev_maps *old_maps, int tci, u16 index)
 2675{
 2676	struct xps_map *map = NULL;
 2677	int pos;
 2678
 2679	map = xmap_dereference(dev_maps->attr_map[tci]);
 2680	if (!map)
 2681		return false;
 2682
 2683	for (pos = map->len; pos--;) {
 2684		if (map->queues[pos] != index)
 2685			continue;
 2686
 2687		if (map->len > 1) {
 2688			map->queues[pos] = map->queues[--map->len];
 2689			break;
 2690		}
 2691
 2692		if (old_maps)
 2693			RCU_INIT_POINTER(old_maps->attr_map[tci], NULL);
 2694		RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
 2695		kfree_rcu(map, rcu);
 2696		return false;
 2697	}
 2698
 2699	return true;
 2700}
 2701
 2702static bool remove_xps_queue_cpu(struct net_device *dev,
 2703				 struct xps_dev_maps *dev_maps,
 2704				 int cpu, u16 offset, u16 count)
 2705{
 2706	int num_tc = dev_maps->num_tc;
 2707	bool active = false;
 2708	int tci;
 2709
 2710	for (tci = cpu * num_tc; num_tc--; tci++) {
 2711		int i, j;
 2712
 2713		for (i = count, j = offset; i--; j++) {
 2714			if (!remove_xps_queue(dev_maps, NULL, tci, j))
 2715				break;
 2716		}
 2717
 2718		active |= i < 0;
 2719	}
 2720
 2721	return active;
 2722}
 2723
 2724static void reset_xps_maps(struct net_device *dev,
 2725			   struct xps_dev_maps *dev_maps,
 2726			   enum xps_map_type type)
 2727{
 2728	static_key_slow_dec_cpuslocked(&xps_needed);
 2729	if (type == XPS_RXQS)
 2730		static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
 2731
 2732	RCU_INIT_POINTER(dev->xps_maps[type], NULL);
 2733
 2734	kfree_rcu(dev_maps, rcu);
 2735}
 2736
 2737static void clean_xps_maps(struct net_device *dev, enum xps_map_type type,
 2738			   u16 offset, u16 count)
 2739{
 2740	struct xps_dev_maps *dev_maps;
 2741	bool active = false;
 2742	int i, j;
 2743
 2744	dev_maps = xmap_dereference(dev->xps_maps[type]);
 2745	if (!dev_maps)
 2746		return;
 2747
 2748	for (j = 0; j < dev_maps->nr_ids; j++)
 2749		active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count);
 2750	if (!active)
 2751		reset_xps_maps(dev, dev_maps, type);
 2752
 2753	if (type == XPS_CPUS) {
 2754		for (i = offset + (count - 1); count--; i--)
 2755			netdev_queue_numa_node_write(
 2756				netdev_get_tx_queue(dev, i), NUMA_NO_NODE);
 2757	}
 2758}
 2759
 2760static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
 2761				   u16 count)
 2762{
 2763	if (!static_key_false(&xps_needed))
 2764		return;
 2765
 2766	cpus_read_lock();
 2767	mutex_lock(&xps_map_mutex);
 2768
 2769	if (static_key_false(&xps_rxqs_needed))
 2770		clean_xps_maps(dev, XPS_RXQS, offset, count);
 2771
 2772	clean_xps_maps(dev, XPS_CPUS, offset, count);
 2773
 2774	mutex_unlock(&xps_map_mutex);
 2775	cpus_read_unlock();
 2776}
 2777
 2778static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
 2779{
 2780	netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
 2781}
 2782
 2783static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
 2784				      u16 index, bool is_rxqs_map)
 2785{
 2786	struct xps_map *new_map;
 2787	int alloc_len = XPS_MIN_MAP_ALLOC;
 2788	int i, pos;
 2789
 2790	for (pos = 0; map && pos < map->len; pos++) {
 2791		if (map->queues[pos] != index)
 2792			continue;
 2793		return map;
 2794	}
 2795
 2796	/* Need to add tx-queue to this CPU's/rx-queue's existing map */
 2797	if (map) {
 2798		if (pos < map->alloc_len)
 2799			return map;
 2800
 2801		alloc_len = map->alloc_len * 2;
 2802	}
 2803
 2804	/* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
 2805	 *  map
 2806	 */
 2807	if (is_rxqs_map)
 2808		new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
 2809	else
 2810		new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
 2811				       cpu_to_node(attr_index));
 2812	if (!new_map)
 2813		return NULL;
 2814
 2815	for (i = 0; i < pos; i++)
 2816		new_map->queues[i] = map->queues[i];
 2817	new_map->alloc_len = alloc_len;
 2818	new_map->len = pos;
 2819
 2820	return new_map;
 2821}
 2822
 2823/* Copy xps maps at a given index */
 2824static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps,
 2825			      struct xps_dev_maps *new_dev_maps, int index,
 2826			      int tc, bool skip_tc)
 2827{
 2828	int i, tci = index * dev_maps->num_tc;
 2829	struct xps_map *map;
 2830
 2831	/* copy maps belonging to foreign traffic classes */
 2832	for (i = 0; i < dev_maps->num_tc; i++, tci++) {
 2833		if (i == tc && skip_tc)
 2834			continue;
 2835
 2836		/* fill in the new device map from the old device map */
 2837		map = xmap_dereference(dev_maps->attr_map[tci]);
 2838		RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
 2839	}
 2840}
 2841
 2842/* Must be called under cpus_read_lock */
 2843int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
 2844			  u16 index, enum xps_map_type type)
 2845{
 2846	struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL;
 2847	const unsigned long *online_mask = NULL;
 2848	bool active = false, copy = false;
 2849	int i, j, tci, numa_node_id = -2;
 2850	int maps_sz, num_tc = 1, tc = 0;
 2851	struct xps_map *map, *new_map;
 2852	unsigned int nr_ids;
 2853
 2854	WARN_ON_ONCE(index >= dev->num_tx_queues);
 2855
 2856	if (dev->num_tc) {
 2857		/* Do not allow XPS on subordinate device directly */
 2858		num_tc = dev->num_tc;
 2859		if (num_tc < 0)
 2860			return -EINVAL;
 2861
 2862		/* If queue belongs to subordinate dev use its map */
 2863		dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
 2864
 2865		tc = netdev_txq_to_tc(dev, index);
 2866		if (tc < 0)
 2867			return -EINVAL;
 2868	}
 2869
 2870	mutex_lock(&xps_map_mutex);
 2871
 2872	dev_maps = xmap_dereference(dev->xps_maps[type]);
 2873	if (type == XPS_RXQS) {
 2874		maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
 2875		nr_ids = dev->num_rx_queues;
 2876	} else {
 2877		maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
 2878		if (num_possible_cpus() > 1)
 2879			online_mask = cpumask_bits(cpu_online_mask);
 2880		nr_ids = nr_cpu_ids;
 2881	}
 2882
 2883	if (maps_sz < L1_CACHE_BYTES)
 2884		maps_sz = L1_CACHE_BYTES;
 2885
 2886	/* The old dev_maps could be larger or smaller than the one we're
 2887	 * setting up now, as dev->num_tc or nr_ids could have been updated in
 2888	 * between. We could try to be smart, but let's be safe instead and only
 2889	 * copy foreign traffic classes if the two map sizes match.
 2890	 */
 2891	if (dev_maps &&
 2892	    dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids)
 2893		copy = true;
 2894
 2895	/* allocate memory for queue storage */
 2896	for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
 2897	     j < nr_ids;) {
 2898		if (!new_dev_maps) {
 2899			new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
 2900			if (!new_dev_maps) {
 2901				mutex_unlock(&xps_map_mutex);
 2902				return -ENOMEM;
 2903			}
 2904
 2905			new_dev_maps->nr_ids = nr_ids;
 2906			new_dev_maps->num_tc = num_tc;
 2907		}
 2908
 2909		tci = j * num_tc + tc;
 2910		map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL;
 2911
 2912		map = expand_xps_map(map, j, index, type == XPS_RXQS);
 2913		if (!map)
 2914			goto error;
 2915
 2916		RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
 2917	}
 2918
 2919	if (!new_dev_maps)
 2920		goto out_no_new_maps;
 2921
 2922	if (!dev_maps) {
 2923		/* Increment static keys at most once per type */
 2924		static_key_slow_inc_cpuslocked(&xps_needed);
 2925		if (type == XPS_RXQS)
 2926			static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
 2927	}
 2928
 2929	for (j = 0; j < nr_ids; j++) {
 2930		bool skip_tc = false;
 2931
 2932		tci = j * num_tc + tc;
 2933		if (netif_attr_test_mask(j, mask, nr_ids) &&
 2934		    netif_attr_test_online(j, online_mask, nr_ids)) {
 2935			/* add tx-queue to CPU/rx-queue maps */
 2936			int pos = 0;
 2937
 2938			skip_tc = true;
 2939
 2940			map = xmap_dereference(new_dev_maps->attr_map[tci]);
 2941			while ((pos < map->len) && (map->queues[pos] != index))
 2942				pos++;
 2943
 2944			if (pos == map->len)
 2945				map->queues[map->len++] = index;
 2946#ifdef CONFIG_NUMA
 2947			if (type == XPS_CPUS) {
 2948				if (numa_node_id == -2)
 2949					numa_node_id = cpu_to_node(j);
 2950				else if (numa_node_id != cpu_to_node(j))
 2951					numa_node_id = -1;
 2952			}
 2953#endif
 2954		}
 2955
 2956		if (copy)
 2957			xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc,
 2958					  skip_tc);
 2959	}
 2960
 2961	rcu_assign_pointer(dev->xps_maps[type], new_dev_maps);
 2962
 2963	/* Cleanup old maps */
 2964	if (!dev_maps)
 2965		goto out_no_old_maps;
 2966
 2967	for (j = 0; j < dev_maps->nr_ids; j++) {
 2968		for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
 2969			map = xmap_dereference(dev_maps->attr_map[tci]);
 2970			if (!map)
 2971				continue;
 2972
 2973			if (copy) {
 2974				new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
 2975				if (map == new_map)
 2976					continue;
 2977			}
 2978
 2979			RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
 2980			kfree_rcu(map, rcu);
 2981		}
 2982	}
 2983
 2984	old_dev_maps = dev_maps;
 2985
 2986out_no_old_maps:
 2987	dev_maps = new_dev_maps;
 2988	active = true;
 2989
 2990out_no_new_maps:
 2991	if (type == XPS_CPUS)
 2992		/* update Tx queue numa node */
 2993		netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
 2994					     (numa_node_id >= 0) ?
 2995					     numa_node_id : NUMA_NO_NODE);
 2996
 2997	if (!dev_maps)
 2998		goto out_no_maps;
 2999
 3000	/* removes tx-queue from unused CPUs/rx-queues */
 3001	for (j = 0; j < dev_maps->nr_ids; j++) {
 3002		tci = j * dev_maps->num_tc;
 3003
 3004		for (i = 0; i < dev_maps->num_tc; i++, tci++) {
 3005			if (i == tc &&
 3006			    netif_attr_test_mask(j, mask, dev_maps->nr_ids) &&
 3007			    netif_attr_test_online(j, online_mask, dev_maps->nr_ids))
 3008				continue;
 3009
 3010			active |= remove_xps_queue(dev_maps,
 3011						   copy ? old_dev_maps : NULL,
 3012						   tci, index);
 3013		}
 3014	}
 3015
 3016	if (old_dev_maps)
 3017		kfree_rcu(old_dev_maps, rcu);
 3018
 3019	/* free map if not active */
 3020	if (!active)
 3021		reset_xps_maps(dev, dev_maps, type);
 3022
 3023out_no_maps:
 3024	mutex_unlock(&xps_map_mutex);
 3025
 3026	return 0;
 3027error:
 3028	/* remove any maps that we added */
 3029	for (j = 0; j < nr_ids; j++) {
 3030		for (i = num_tc, tci = j * num_tc; i--; tci++) {
 3031			new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
 3032			map = copy ?
 3033			      xmap_dereference(dev_maps->attr_map[tci]) :
 3034			      NULL;
 3035			if (new_map && new_map != map)
 3036				kfree(new_map);
 3037		}
 3038	}
 3039
 3040	mutex_unlock(&xps_map_mutex);
 3041
 3042	kfree(new_dev_maps);
 3043	return -ENOMEM;
 3044}
 3045EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
 3046
 3047int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
 3048			u16 index)
 3049{
 3050	int ret;
 3051
 3052	cpus_read_lock();
 3053	ret =  __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS);
 3054	cpus_read_unlock();
 3055
 3056	return ret;
 3057}
 3058EXPORT_SYMBOL(netif_set_xps_queue);
 3059
 3060#endif
 3061static void netdev_unbind_all_sb_channels(struct net_device *dev)
 3062{
 3063	struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
 3064
 3065	/* Unbind any subordinate channels */
 3066	while (txq-- != &dev->_tx[0]) {
 3067		if (txq->sb_dev)
 3068			netdev_unbind_sb_channel(dev, txq->sb_dev);
 3069	}
 3070}
 3071
 3072void netdev_reset_tc(struct net_device *dev)
 3073{
 3074#ifdef CONFIG_XPS
 3075	netif_reset_xps_queues_gt(dev, 0);
 3076#endif
 3077	netdev_unbind_all_sb_channels(dev);
 3078
 3079	/* Reset TC configuration of device */
 3080	dev->num_tc = 0;
 3081	memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
 3082	memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
 3083}
 3084EXPORT_SYMBOL(netdev_reset_tc);
 3085
 3086int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
 3087{
 3088	if (tc >= dev->num_tc)
 3089		return -EINVAL;
 3090
 3091#ifdef CONFIG_XPS
 3092	netif_reset_xps_queues(dev, offset, count);
 3093#endif
 3094	dev->tc_to_txq[tc].count = count;
 3095	dev->tc_to_txq[tc].offset = offset;
 3096	return 0;
 3097}
 3098EXPORT_SYMBOL(netdev_set_tc_queue);
 3099
 3100int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
 3101{
 3102	if (num_tc > TC_MAX_QUEUE)
 3103		return -EINVAL;
 3104
 3105#ifdef CONFIG_XPS
 3106	netif_reset_xps_queues_gt(dev, 0);
 3107#endif
 3108	netdev_unbind_all_sb_channels(dev);
 3109
 3110	dev->num_tc = num_tc;
 3111	return 0;
 3112}
 3113EXPORT_SYMBOL(netdev_set_num_tc);
 3114
 3115void netdev_unbind_sb_channel(struct net_device *dev,
 3116			      struct net_device *sb_dev)
 3117{
 3118	struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
 3119
 3120#ifdef CONFIG_XPS
 3121	netif_reset_xps_queues_gt(sb_dev, 0);
 3122#endif
 3123	memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
 3124	memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
 3125
 3126	while (txq-- != &dev->_tx[0]) {
 3127		if (txq->sb_dev == sb_dev)
 3128			txq->sb_dev = NULL;
 3129	}
 3130}
 3131EXPORT_SYMBOL(netdev_unbind_sb_channel);
 3132
 3133int netdev_bind_sb_channel_queue(struct net_device *dev,
 3134				 struct net_device *sb_dev,
 3135				 u8 tc, u16 count, u16 offset)
 3136{
 3137	/* Make certain the sb_dev and dev are already configured */
 3138	if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
 3139		return -EINVAL;
 3140
 3141	/* We cannot hand out queues we don't have */
 3142	if ((offset + count) > dev->real_num_tx_queues)
 3143		return -EINVAL;
 3144
 3145	/* Record the mapping */
 3146	sb_dev->tc_to_txq[tc].count = count;
 3147	sb_dev->tc_to_txq[tc].offset = offset;
 3148
 3149	/* Provide a way for Tx queue to find the tc_to_txq map or
 3150	 * XPS map for itself.
 3151	 */
 3152	while (count--)
 3153		netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
 3154
 3155	return 0;
 3156}
 3157EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
 3158
 3159int netdev_set_sb_channel(struct net_device *dev, u16 channel)
 3160{
 3161	/* Do not use a multiqueue device to represent a subordinate channel */
 3162	if (netif_is_multiqueue(dev))
 3163		return -ENODEV;
 3164
 3165	/* We allow channels 1 - 32767 to be used for subordinate channels.
 3166	 * Channel 0 is meant to be "native" mode and used only to represent
 3167	 * the main root device. We allow writing 0 to reset the device back
 3168	 * to normal mode after being used as a subordinate channel.
 3169	 */
 3170	if (channel > S16_MAX)
 3171		return -EINVAL;
 3172
 3173	dev->num_tc = -channel;
 3174
 3175	return 0;
 3176}
 3177EXPORT_SYMBOL(netdev_set_sb_channel);
 3178
 3179/*
 3180 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
 3181 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
 3182 */
 3183int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
 3184{
 3185	bool disabling;
 3186	int rc;
 3187
 3188	disabling = txq < dev->real_num_tx_queues;
 3189
 3190	if (txq < 1 || txq > dev->num_tx_queues)
 3191		return -EINVAL;
 3192
 3193	if (dev->reg_state == NETREG_REGISTERED ||
 3194	    dev->reg_state == NETREG_UNREGISTERING) {
 3195		netdev_ops_assert_locked(dev);
 3196
 3197		rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
 3198						  txq);
 3199		if (rc)
 3200			return rc;
 3201
 3202		if (dev->num_tc)
 3203			netif_setup_tc(dev, txq);
 3204
 3205		net_shaper_set_real_num_tx_queues(dev, txq);
 3206
 3207		dev_qdisc_change_real_num_tx(dev, txq);
 3208
 3209		dev->real_num_tx_queues = txq;
 3210
 3211		if (disabling) {
 3212			synchronize_net();
 3213			qdisc_reset_all_tx_gt(dev, txq);
 3214#ifdef CONFIG_XPS
 3215			netif_reset_xps_queues_gt(dev, txq);
 3216#endif
 3217		}
 3218	} else {
 3219		dev->real_num_tx_queues = txq;
 3220	}
 3221
 3222	return 0;
 3223}
 3224EXPORT_SYMBOL(netif_set_real_num_tx_queues);
 3225
 3226/**
 3227 *	netif_set_real_num_rx_queues - set actual number of RX queues used
 3228 *	@dev: Network device
 3229 *	@rxq: Actual number of RX queues
 3230 *
 3231 *	This must be called either with the rtnl_lock held or before
 3232 *	registration of the net device.  Returns 0 on success, or a
 3233 *	negative error code.  If called before registration, it always
 3234 *	succeeds.
 3235 */
 3236int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
 3237{
 3238	int rc;
 3239
 3240	if (rxq < 1 || rxq > dev->num_rx_queues)
 3241		return -EINVAL;
 3242
 3243	if (dev->reg_state == NETREG_REGISTERED) {
 3244		netdev_ops_assert_locked(dev);
 3245
 3246		rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
 3247						  rxq);
 3248		if (rc)
 3249			return rc;
 3250	}
 3251
 3252	dev->real_num_rx_queues = rxq;
 3253	return 0;
 3254}
 3255EXPORT_SYMBOL(netif_set_real_num_rx_queues);
 3256
 3257/**
 3258 *	netif_set_real_num_queues - set actual number of RX and TX queues used
 3259 *	@dev: Network device
 3260 *	@txq: Actual number of TX queues
 3261 *	@rxq: Actual number of RX queues
 3262 *
 3263 *	Set the real number of both TX and RX queues.
 3264 *	Does nothing if the number of queues is already correct.
 3265 */
 3266int netif_set_real_num_queues(struct net_device *dev,
 3267			      unsigned int txq, unsigned int rxq)
 3268{
 3269	unsigned int old_rxq = dev->real_num_rx_queues;
 3270	int err;
 3271
 3272	if (txq < 1 || txq > dev->num_tx_queues ||
 3273	    rxq < 1 || rxq > dev->num_rx_queues)
 3274		return -EINVAL;
 3275
 3276	/* Start from increases, so the error path only does decreases -
 3277	 * decreases can't fail.
 3278	 */
 3279	if (rxq > dev->real_num_rx_queues) {
 3280		err = netif_set_real_num_rx_queues(dev, rxq);
 3281		if (err)
 3282			return err;
 3283	}
 3284	if (txq > dev->real_num_tx_queues) {
 3285		err = netif_set_real_num_tx_queues(dev, txq);
 3286		if (err)
 3287			goto undo_rx;
 3288	}
 3289	if (rxq < dev->real_num_rx_queues)
 3290		WARN_ON(netif_set_real_num_rx_queues(dev, rxq));
 3291	if (txq < dev->real_num_tx_queues)
 3292		WARN_ON(netif_set_real_num_tx_queues(dev, txq));
 3293
 3294	return 0;
 3295undo_rx:
 3296	WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq));
 3297	return err;
 3298}
 3299EXPORT_SYMBOL(netif_set_real_num_queues);
 3300
 3301/**
 3302 * netif_set_tso_max_size() - set the max size of TSO frames supported
 3303 * @dev:	netdev to update
 3304 * @size:	max skb->len of a TSO frame
 3305 *
 3306 * Set the limit on the size of TSO super-frames the device can handle.
 3307 * Unless explicitly set the stack will assume the value of
 3308 * %GSO_LEGACY_MAX_SIZE.
 3309 */
 3310void netif_set_tso_max_size(struct net_device *dev, unsigned int size)
 3311{
 3312	dev->tso_max_size = min(GSO_MAX_SIZE, size);
 3313	if (size < READ_ONCE(dev->gso_max_size))
 3314		netif_set_gso_max_size(dev, size);
 3315	if (size < READ_ONCE(dev->gso_ipv4_max_size))
 3316		netif_set_gso_ipv4_max_size(dev, size);
 3317}
 3318EXPORT_SYMBOL(netif_set_tso_max_size);
 3319
 3320/**
 3321 * netif_set_tso_max_segs() - set the max number of segs supported for TSO
 3322 * @dev:	netdev to update
 3323 * @segs:	max number of TCP segments
 3324 *
 3325 * Set the limit on the number of TCP segments the device can generate from
 3326 * a single TSO super-frame.
 3327 * Unless explicitly set the stack will assume the value of %GSO_MAX_SEGS.
 3328 */
 3329void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs)
 3330{
 3331	dev->tso_max_segs = segs;
 3332	if (segs < READ_ONCE(dev->gso_max_segs))
 3333		netif_set_gso_max_segs(dev, segs);
 3334}
 3335EXPORT_SYMBOL(netif_set_tso_max_segs);
 3336
 3337/**
 3338 * netif_inherit_tso_max() - copy all TSO limits from a lower device to an upper
 3339 * @to:		netdev to update
 3340 * @from:	netdev from which to copy the limits
 3341 */
 3342void netif_inherit_tso_max(struct net_device *to, const struct net_device *from)
 3343{
 3344	netif_set_tso_max_size(to, from->tso_max_size);
 3345	netif_set_tso_max_segs(to, from->tso_max_segs);
 3346}
 3347EXPORT_SYMBOL(netif_inherit_tso_max);
 3348
 3349/**
 3350 * netif_get_num_default_rss_queues - default number of RSS queues
 3351 *
 3352 * Default value is the number of physical cores if there are only 1 or 2, or
 3353 * divided by 2 if there are more.
 3354 */
 3355int netif_get_num_default_rss_queues(void)
 3356{
 3357	cpumask_var_t cpus;
 3358	int cpu, count = 0;
 3359
 3360	if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL)))
 3361		return 1;
 3362
 3363	cpumask_copy(cpus, cpu_online_mask);
 3364	for_each_cpu(cpu, cpus) {
 3365		++count;
 3366		cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu));
 3367	}
 3368	free_cpumask_var(cpus);
 3369
 3370	return count > 2 ? DIV_ROUND_UP(count, 2) : count;
 3371}
 3372EXPORT_SYMBOL(netif_get_num_default_rss_queues);
 3373
 3374static void __netif_reschedule(struct Qdisc *q)
 3375{
 3376	struct softnet_data *sd;
 3377	unsigned long flags;
 3378
 3379	local_irq_save(flags);
 3380	sd = this_cpu_ptr(&softnet_data);
 3381	q->next_sched = NULL;
 3382	*sd->output_queue_tailp = q;
 3383	sd->output_queue_tailp = &q->next_sched;
 3384	raise_softirq_irqoff(NET_TX_SOFTIRQ);
 3385	local_irq_restore(flags);
 3386}
 3387
 3388void __netif_schedule(struct Qdisc *q)
 3389{
 3390	/* If q->defer_list is not empty, at least one thread is
 3391	 * in __dev_xmit_skb() before llist_del_all(&q->defer_list).
 3392	 * This thread will attempt to run the queue.
 3393	 */
 3394	if (!llist_empty(&q->defer_list))
 3395		return;
 3396
 3397	if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
 3398		__netif_reschedule(q);
 3399}
 3400EXPORT_SYMBOL(__netif_schedule);
 3401
 3402struct dev_kfree_skb_cb {
 3403	enum skb_drop_reason reason;
 3404};
 3405
 3406static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
 3407{
 3408	return (struct dev_kfree_skb_cb *)skb->cb;
 3409}
 3410
 3411void netif_schedule_queue(struct netdev_queue *txq)
 3412{
 3413	rcu_read_lock();
 3414	if (!netif_xmit_stopped(txq)) {
 3415		struct Qdisc *q = rcu_dereference(txq->qdisc);
 3416
 3417		__netif_schedule(q);
 3418	}
 3419	rcu_read_unlock();
 3420}
 3421EXPORT_SYMBOL(netif_schedule_queue);
 3422
 3423void netif_tx_wake_queue(struct netdev_queue *dev_queue)
 3424{
 3425	if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
 3426		struct Qdisc *q;
 3427
 3428		rcu_read_lock();
 3429		q = rcu_dereference(dev_queue->qdisc);
 3430		__netif_schedule(q);
 3431		rcu_read_unlock();
 3432	}
 3433}
 3434EXPORT_SYMBOL(netif_tx_wake_queue);
 3435
 3436void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason)
 3437{
 3438	unsigned long flags;
 3439
 3440	if (unlikely(!skb))
 3441		return;
 3442
 3443	if (likely(refcount_read(&skb->users) == 1)) {
 3444		smp_rmb();
 3445		refcount_set(&skb->users, 0);
 3446	} else if (likely(!refcount_dec_and_test(&skb->users))) {
 3447		return;
 3448	}
 3449	get_kfree_skb_cb(skb)->reason = reason;
 3450	local_irq_save(flags);
 3451	skb->next = __this_cpu_read(softnet_data.completion_queue);
 3452	__this_cpu_write(softnet_data.completion_queue, skb);
 3453	raise_softirq_irqoff(NET_TX_SOFTIRQ);
 3454	local_irq_restore(flags);
 3455}
 3456EXPORT_SYMBOL(dev_kfree_skb_irq_reason);
 3457
 3458void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason)
 3459{
 3460	if (in_hardirq() || irqs_disabled())
 3461		dev_kfree_skb_irq_reason(skb, reason);
 3462	else
 3463		kfree_skb_reason(skb, reason);
 3464}
 3465EXPORT_SYMBOL(dev_kfree_skb_any_reason);
 3466
 3467
 3468/**
 3469 * netif_device_detach - mark device as removed
 3470 * @dev: network device
 3471 *
 3472 * Mark device as removed from system and therefore no longer available.
 3473 */
 3474void netif_device_detach(struct net_device *dev)
 3475{
 3476	if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
 3477	    netif_running(dev)) {
 3478		netif_tx_stop_all_queues(dev);
 3479	}
 3480}
 3481EXPORT_SYMBOL(netif_device_detach);
 3482
 3483/**
 3484 * netif_device_attach - mark device as attached
 3485 * @dev: network device
 3486 *
 3487 * Mark device as attached from system and restart if needed.
 3488 */
 3489void netif_device_attach(struct net_device *dev)
 3490{
 3491	if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
 3492	    netif_running(dev)) {
 3493		netif_tx_wake_all_queues(dev);
 3494		netdev_watchdog_up(dev);
 3495	}
 3496}
 3497EXPORT_SYMBOL(netif_device_attach);
 3498
 3499/*
 3500 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
 3501 * to be used as a distribution range.
 3502 */
 3503static u16 skb_tx_hash(const struct net_device *dev,
 3504		       const struct net_device *sb_dev,
 3505		       struct sk_buff *skb)
 3506{
 3507	u32 hash;
 3508	u16 qoffset = 0;
 3509	u16 qcount = dev->real_num_tx_queues;
 3510
 3511	if (dev->num_tc) {
 3512		u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
 3513
 3514		qoffset = sb_dev->tc_to_txq[tc].offset;
 3515		qcount = sb_dev->tc_to_txq[tc].count;
 3516		if (unlikely(!qcount)) {
 3517			net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
 3518					     sb_dev->name, qoffset, tc);
 3519			qoffset = 0;
 3520			qcount = dev->real_num_tx_queues;
 3521		}
 3522	}
 3523
 3524	if (skb_rx_queue_recorded(skb)) {
 3525		DEBUG_NET_WARN_ON_ONCE(qcount == 0);
 3526		hash = skb_get_rx_queue(skb);
 3527		if (hash >= qoffset)
 3528			hash -= qoffset;
 3529		while (unlikely(hash >= qcount))
 3530			hash -= qcount;
 3531		return hash + qoffset;
 3532	}
 3533
 3534	return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
 3535}
 3536
 3537void skb_warn_bad_offload(const struct sk_buff *skb)
 3538{
 3539	static const netdev_features_t null_features;
 3540	struct net_device *dev = skb->dev;
 3541	const char *name = "";
 3542
 3543	if (!net_ratelimit())
 3544		return;
 3545
 3546	if (dev) {
 3547		if (dev->dev.parent)
 3548			name = dev_driver_string(dev->dev.parent);
 3549		else
 3550			name = netdev_name(dev);
 3551	}
 3552	skb_dump(KERN_WARNING, skb, false);
 3553	WARN(1, "%s: caps=(%pNF, %pNF)\n",
 3554	     name, dev ? &dev->features : &null_features,
 3555	     skb->sk ? &skb->sk->sk_route_caps : &null_features);
 3556}
 3557
 3558/*
 3559 * Invalidate hardware checksum when packet is to be mangled, and
 3560 * complete checksum manually on outgoing path.
 3561 */
 3562int skb_checksum_help(struct sk_buff *skb)
 3563{
 3564	__wsum csum;
 3565	int ret = 0, offset;
 3566
 3567	if (skb->ip_summed == CHECKSUM_COMPLETE)
 3568		goto out_set_summed;
 3569
 3570	if (unlikely(skb_is_gso(skb))) {
 3571		skb_warn_bad_offload(skb);
 3572		return -EINVAL;
 3573	}
 3574
 3575	if (!skb_frags_readable(skb)) {
 3576		return -EFAULT;
 3577	}
 3578
 3579	/* Before computing a checksum, we should make sure no frag could
 3580	 * be modified by an external entity : checksum could be wrong.
 3581	 */
 3582	if (skb_has_shared_frag(skb)) {
 3583		ret = __skb_linearize(skb);
 3584		if (ret)
 3585			goto out;
 3586	}
 3587
 3588	offset = skb_checksum_start_offset(skb);
 3589	ret = -EINVAL;
 3590	if (unlikely(offset >= skb_headlen(skb))) {
 3591		DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
 3592		WARN_ONCE(true, "offset (%d) >= skb_headlen() (%u)\n",
 3593			  offset, skb_headlen(skb));
 3594		goto out;
 3595	}
 3596	csum = skb_checksum(skb, offset, skb->len - offset, 0);
 3597
 3598	offset += skb->csum_offset;
 3599	if (unlikely(offset + sizeof(__sum16) > skb_headlen(skb))) {
 3600		DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
 3601		WARN_ONCE(true, "offset+2 (%zu) > skb_headlen() (%u)\n",
 3602			  offset + sizeof(__sum16), skb_headlen(skb));
 3603		goto out;
 3604	}
 3605	ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
 3606	if (ret)
 3607		goto out;
 3608
 3609	*(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
 3610out_set_summed:
 3611	skb->ip_summed = CHECKSUM_NONE;
 3612out:
 3613	return ret;
 3614}
 3615EXPORT_SYMBOL(skb_checksum_help);
 3616
 3617#ifdef CONFIG_NET_CRC32C
 3618int skb_crc32c_csum_help(struct sk_buff *skb)
 3619{
 3620	u32 crc;
 3621	int ret = 0, offset, start;
 3622
 3623	if (skb->ip_summed != CHECKSUM_PARTIAL)
 3624		goto out;
 3625
 3626	if (unlikely(skb_is_gso(skb)))
 3627		goto out;
 3628
 3629	/* Before computing a checksum, we should make sure no frag could
 3630	 * be modified by an external entity : checksum could be wrong.
 3631	 */
 3632	if (unlikely(skb_has_shared_frag(skb))) {
 3633		ret = __skb_linearize(skb);
 3634		if (ret)
 3635			goto out;
 3636	}
 3637	start = skb_checksum_start_offset(skb);
 3638	offset = start + offsetof(struct sctphdr, checksum);
 3639	if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
 3640		ret = -EINVAL;
 3641		goto out;
 3642	}
 3643
 3644	ret = skb_ensure_writable(skb, offset + sizeof(__le32));
 3645	if (ret)
 3646		goto out;
 3647
 3648	crc = ~skb_crc32c(skb, start, skb->len - start, ~0);
 3649	*(__le32 *)(skb->data + offset) = cpu_to_le32(crc);
 3650	skb_reset_csum_not_inet(skb);
 3651out:
 3652	return ret;
 3653}
 3654EXPORT_SYMBOL(skb_crc32c_csum_help);
 3655#endif /* CONFIG_NET_CRC32C */
 3656
 3657__be16 skb_network_protocol(struct sk_buff *skb, int *depth)
 3658{
 3659	__be16 type = skb->protocol;
 3660
 3661	/* Tunnel gso handlers can set protocol to ethernet. */
 3662	if (type == htons(ETH_P_TEB)) {
 3663		struct ethhdr *eth;
 3664
 3665		if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
 3666			return 0;
 3667
 3668		eth = (struct ethhdr *)skb->data;
 3669		type = eth->h_proto;
 3670	}
 3671
 3672	return vlan_get_protocol_and_depth(skb, type, depth);
 3673}
 3674
 3675
 3676/* Take action when hardware reception checksum errors are detected. */
 3677#ifdef CONFIG_BUG
 3678static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
 3679{
 3680	netdev_err(dev, "hw csum failure\n");
 3681	skb_dump(KERN_ERR, skb, true);
 3682	dump_stack();
 3683}
 3684
 3685void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
 3686{
 3687	DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb);
 3688}
 3689EXPORT_SYMBOL(netdev_rx_csum_fault);
 3690#endif
 3691
 3692/* XXX: check that highmem exists at all on the given machine. */
 3693static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
 3694{
 3695#ifdef CONFIG_HIGHMEM
 3696	int i;
 3697
 3698	if (!(dev->features & NETIF_F_HIGHDMA)) {
 3699		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
 3700			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
 3701			struct page *page = skb_frag_page(frag);
 3702
 3703			if (page && PageHighMem(page))
 3704				return 1;
 3705		}
 3706	}
 3707#endif
 3708	return 0;
 3709}
 3710
 3711/* If MPLS offload request, verify we are testing hardware MPLS features
 3712 * instead of standard features for the netdev.
 3713 */
 3714#if IS_ENABLED(CONFIG_NET_MPLS_GSO)
 3715static netdev_features_t net_mpls_features(struct sk_buff *skb,
 3716					   netdev_features_t features,
 3717					   __be16 type)
 3718{
 3719	if (eth_p_mpls(type))
 3720		features &= skb->dev->mpls_features;
 3721
 3722	return features;
 3723}
 3724#else
 3725static netdev_features_t net_mpls_features(struct sk_buff *skb,
 3726					   netdev_features_t features,
 3727					   __be16 type)
 3728{
 3729	return features;
 3730}
 3731#endif
 3732
 3733static netdev_features_t harmonize_features(struct sk_buff *skb,
 3734	netdev_features_t features)
 3735{
 3736	__be16 type;
 3737
 3738	type = skb_network_protocol(skb, NULL);
 3739	features = net_mpls_features(skb, features, type);
 3740
 3741	if (skb->ip_summed != CHECKSUM_NONE &&
 3742	    !can_checksum_protocol(features, type)) {
 3743		features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
 3744	}
 3745	if (illegal_highdma(skb->dev, skb))
 3746		features &= ~NETIF_F_SG;
 3747
 3748	return features;
 3749}
 3750
 3751netdev_features_t passthru_features_check(struct sk_buff *skb,
 3752					  struct net_device *dev,
 3753					  netdev_features_t features)
 3754{
 3755	return features;
 3756}
 3757EXPORT_SYMBOL(passthru_features_check);
 3758
 3759static netdev_features_t dflt_features_check(struct sk_buff *skb,
 3760					     struct net_device *dev,
 3761					     netdev_features_t features)
 3762{
 3763	return vlan_features_check(skb, features);
 3764}
 3765
 3766static bool skb_gso_has_extension_hdr(const struct sk_buff *skb)
 3767{
 3768	if (!skb->encapsulation)
 3769		return ((skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6 ||
 3770			 (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4 &&
 3771			  vlan_get_protocol(skb) == htons(ETH_P_IPV6))) &&
 3772			skb_transport_header_was_set(skb) &&
 3773			skb_network_header_len(skb) != sizeof(struct ipv6hdr));
 3774	else
 3775		return (!skb_inner_network_header_was_set(skb) ||
 3776			((skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6 ||
 3777			  (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4 &&
 3778			   inner_ip_hdr(skb)->version == 6)) &&
 3779			 skb_inner_network_header_len(skb) != sizeof(struct ipv6hdr)));
 3780}
 3781
 3782static netdev_features_t gso_features_check(const struct sk_buff *skb,
 3783					    struct net_device *dev,
 3784					    netdev_features_t features)
 3785{
 3786	u16 gso_segs = skb_shinfo(skb)->gso_segs;
 3787
 3788	if (gso_segs > READ_ONCE(dev->gso_max_segs))
 3789		return features & ~NETIF_F_GSO_MASK;
 3790
 3791	if (unlikely(skb->len >= netif_get_gso_max_size(dev, skb)))
 3792		return features & ~NETIF_F_GSO_MASK;
 3793
 3794	if (!skb_shinfo(skb)->gso_type) {
 3795		skb_warn_bad_offload(skb);
 3796		return features & ~NETIF_F_GSO_MASK;
 3797	}
 3798
 3799	/* Support for GSO partial features requires software
 3800	 * intervention before we can actually process the packets
 3801	 * so we need to strip support for any partial features now
 3802	 * and we can pull them back in after we have partially
 3803	 * segmented the frame.
 3804	 */
 3805	if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
 3806		features &= ~dev->gso_partial_features;
 3807
 3808	/* Make sure to clear the IPv4 ID mangling feature if the IPv4 header
 3809	 * has the potential to be fragmented so that TSO does not generate
 3810	 * segments with the same ID. For encapsulated packets, the ID mangling
 3811	 * feature is guaranteed not to use the same ID for the outer IPv4
 3812	 * headers of the generated segments if the headers have the potential
 3813	 * to be fragmented, so there is no need to clear the IPv4 ID mangling
 3814	 * feature (see the section about NETIF_F_TSO_MANGLEID in
 3815	 * segmentation-offloads.rst).
 3816	 */
 3817	if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
 3818		const struct iphdr *iph;
 3819		struct iphdr _iph;
 3820		int nhoff = skb->encapsulation ?
 3821			    skb_inner_network_offset(skb) :
 3822			    skb_network_offset(skb);
 3823
 3824		iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
 3825
 3826		if (!iph || !(iph->frag_off & htons(IP_DF)))
 3827			features &= ~dev->mangleid_features;
 3828	}
 3829
 3830	/* NETIF_F_IPV6_CSUM does not support IPv6 extension headers,
 3831	 * so neither does TSO that depends on it.
 3832	 */
 3833	if (features & NETIF_F_IPV6_CSUM &&
 3834	    skb_gso_has_extension_hdr(skb) &&
 3835	    !ipv6_has_hopopt_jumbo(skb))
 3836		features &= ~(NETIF_F_IPV6_CSUM | NETIF_F_TSO6 | NETIF_F_GSO_UDP_L4);
 3837
 3838	return features;
 3839}
 3840
 3841netdev_features_t netif_skb_features(struct sk_buff *skb)
 3842{
 3843	struct net_device *dev = skb->dev;
 3844	netdev_features_t features = dev->features;
 3845
 3846	if (skb_is_gso(skb))
 3847		features = gso_features_check(skb, dev, features);
 3848
 3849	/* If encapsulation offload request, verify we are testing
 3850	 * hardware encapsulation features instead of standard
 3851	 * features for the netdev
 3852	 */
 3853	if (skb->encapsulation)
 3854		features &= dev->hw_enc_features;
 3855
 3856	if (skb_vlan_tagged(skb))
 3857		features = netdev_intersect_features(features,
 3858						     dev->vlan_features |
 3859						     NETIF_F_HW_VLAN_CTAG_TX |
 3860						     NETIF_F_HW_VLAN_STAG_TX);
 3861
 3862	if (dev->netdev_ops->ndo_features_check)
 3863		features &= dev->netdev_ops->ndo_features_check(skb, dev,
 3864								features);
 3865	else
 3866		features &= dflt_features_check(skb, dev, features);
 3867
 3868	return harmonize_features(skb, features);
 3869}
 3870EXPORT_SYMBOL(netif_skb_features);
 3871
 3872static int xmit_one(struct sk_buff *skb, struct net_device *dev,
 3873		    struct netdev_queue *txq, bool more)
 3874{
 3875	unsigned int len;
 3876	int rc;
 3877
 3878	if (dev_nit_active_rcu(dev))
 3879		dev_queue_xmit_nit(skb, dev);
 3880
 3881	len = skb->len;
 3882	trace_net_dev_start_xmit(skb, dev);
 3883	rc = netdev_start_xmit(skb, dev, txq, more);
 3884	trace_net_dev_xmit(skb, rc, dev, len);
 3885
 3886	return rc;
 3887}
 3888
 3889struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
 3890				    struct netdev_queue *txq, int *ret)
 3891{
 3892	struct sk_buff *skb = first;
 3893	int rc = NETDEV_TX_OK;
 3894
 3895	while (skb) {
 3896		struct sk_buff *next = skb->next;
 3897
 3898		skb_mark_not_on_list(skb);
 3899		rc = xmit_one(skb, dev, txq, next != NULL);
 3900		if (unlikely(!dev_xmit_complete(rc))) {
 3901			skb->next = next;
 3902			goto out;
 3903		}
 3904
 3905		skb = next;
 3906		if (netif_tx_queue_stopped(txq) && skb) {
 3907			rc = NETDEV_TX_BUSY;
 3908			break;
 3909		}
 3910	}
 3911
 3912out:
 3913	*ret = rc;
 3914	return skb;
 3915}
 3916
 3917static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
 3918					  netdev_features_t features)
 3919{
 3920	if (skb_vlan_tag_present(skb) &&
 3921	    !vlan_hw_offload_capable(features, skb->vlan_proto))
 3922		skb = __vlan_hwaccel_push_inside(skb);
 3923	return skb;
 3924}
 3925
 3926int skb_csum_hwoffload_help(struct sk_buff *skb,
 3927			    const netdev_features_t features)
 3928{
 3929	if (unlikely(skb_csum_is_sctp(skb)))
 3930		return !!(features & NETIF_F_SCTP_CRC) ? 0 :
 3931			skb_crc32c_csum_help(skb);
 3932
 3933	if (features & NETIF_F_HW_CSUM)
 3934		return 0;
 3935
 3936	if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
 3937		if (vlan_get_protocol(skb) == htons(ETH_P_IPV6) &&
 3938		    skb_network_header_len(skb) != sizeof(struct ipv6hdr) &&
 3939		    !ipv6_has_hopopt_jumbo(skb))
 3940			goto sw_checksum;
 3941
 3942		switch (skb->csum_offset) {
 3943		case offsetof(struct tcphdr, check):
 3944		case offsetof(struct udphdr, check):
 3945			return 0;
 3946		}
 3947	}
 3948
 3949sw_checksum:
 3950	return skb_checksum_help(skb);
 3951}
 3952EXPORT_SYMBOL(skb_csum_hwoffload_help);
 3953
 3954/* Checks if this SKB belongs to an HW offloaded socket
 3955 * and whether any SW fallbacks are required based on dev.
 3956 * Check decrypted mark in case skb_orphan() cleared socket.
 3957 */
 3958static struct sk_buff *sk_validate_xmit_skb(struct sk_buff *skb,
 3959					    struct net_device *dev)
 3960{
 3961#ifdef CONFIG_SOCK_VALIDATE_XMIT
 3962	struct sk_buff *(*sk_validate)(struct sock *sk, struct net_device *dev,
 3963				       struct sk_buff *skb);
 3964	struct sock *sk = skb->sk;
 3965
 3966	sk_validate = NULL;
 3967	if (sk) {
 3968		if (sk_fullsock(sk))
 3969			sk_validate = sk->sk_validate_xmit_skb;
 3970		else if (sk_is_inet(sk) && sk->sk_state == TCP_TIME_WAIT)
 3971			sk_validate = inet_twsk(sk)->tw_validate_xmit_skb;
 3972	}
 3973
 3974	if (sk_validate) {
 3975		skb = sk_validate(sk, dev, skb);
 3976	} else if (unlikely(skb_is_decrypted(skb))) {
 3977		pr_warn_ratelimited("unencrypted skb with no associated socket - dropping\n");
 3978		kfree_skb(skb);
 3979		skb = NULL;
 3980	}
 3981#endif
 3982
 3983	return skb;
 3984}
 3985
 3986static struct sk_buff *validate_xmit_unreadable_skb(struct sk_buff *skb,
 3987						    struct net_device *dev)
 3988{
 3989	struct skb_shared_info *shinfo;
 3990	struct net_iov *niov;
 3991
 3992	if (likely(skb_frags_readable(skb)))
 3993		goto out;
 3994
 3995	if (!dev->netmem_tx)
 3996		goto out_free;
 3997
 3998	shinfo = skb_shinfo(skb);
 3999
 4000	if (shinfo->nr_frags > 0) {
 4001		niov = netmem_to_net_iov(skb_frag_netmem(&shinfo->frags[0]));
 4002		if (net_is_devmem_iov(niov) &&
 4003		    READ_ONCE(net_devmem_iov_binding(niov)->dev) != dev)
 4004			goto out_free;
 4005	}
 4006
 4007out:
 4008	return skb;
 4009
 4010out_free:
 4011	kfree_skb(skb);
 4012	return NULL;
 4013}
 4014
 4015static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
 4016{
 4017	netdev_features_t features;
 4018
 4019	skb = validate_xmit_unreadable_skb(skb, dev);
 4020	if (unlikely(!skb))
 4021		goto out_null;
 4022
 4023	features = netif_skb_features(skb);
 4024	skb = validate_xmit_vlan(skb, features);
 4025	if (unlikely(!skb))
 4026		goto out_null;
 4027
 4028	skb = sk_validate_xmit_skb(skb, dev);
 4029	if (unlikely(!skb))
 4030		goto out_null;
 4031
 4032	if (netif_needs_gso(skb, features)) {
 4033		struct sk_buff *segs;
 4034
 4035		segs = skb_gso_segment(skb, features);
 4036		if (IS_ERR(segs)) {
 4037			goto out_kfree_skb;
 4038		} else if (segs) {
 4039			consume_skb(skb);
 4040			skb = segs;
 4041		}
 4042	} else {
 4043		if (skb_needs_linearize(skb, features) &&
 4044		    __skb_linearize(skb))
 4045			goto out_kfree_skb;
 4046
 4047		/* If packet is not checksummed and device does not
 4048		 * support checksumming for this protocol, complete
 4049		 * checksumming here.
 4050		 */
 4051		if (skb->ip_summed == CHECKSUM_PARTIAL) {
 4052			if (skb->encapsulation)
 4053				skb_set_inner_transport_header(skb,
 4054							       skb_checksum_start_offset(skb));
 4055			else
 4056				skb_set_transport_header(skb,
 4057							 skb_checksum_start_offset(skb));
 4058			if (skb_csum_hwoffload_help(skb, features))
 4059				goto out_kfree_skb;
 4060		}
 4061	}
 4062
 4063	skb = validate_xmit_xfrm(skb, features, again);
 4064
 4065	return skb;
 4066
 4067out_kfree_skb:
 4068	kfree_skb(skb);
 4069out_null:
 4070	dev_core_stats_tx_dropped_inc(dev);
 4071	return NULL;
 4072}
 4073
 4074struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
 4075{
 4076	struct sk_buff *next, *head = NULL, *tail;
 4077
 4078	for (; skb != NULL; skb = next) {
 4079		next = skb->next;
 4080		skb_mark_not_on_list(skb);
 4081
 4082		/* in case skb won't be segmented, point to itself */
 4083		skb->prev = skb;
 4084
 4085		skb = validate_xmit_skb(skb, dev, again);
 4086		if (!skb)
 4087			continue;
 4088
 4089		if (!head)
 4090			head = skb;
 4091		else
 4092			tail->next = skb;
 4093		/* If skb was segmented, skb->prev points to
 4094		 * the last segment. If not, it still contains skb.
 4095		 */
 4096		tail = skb->prev;
 4097	}
 4098	return head;
 4099}
 4100EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
 4101
 4102static void qdisc_pkt_len_segs_init(struct sk_buff *skb)
 4103{
 4104	struct skb_shared_info *shinfo = skb_shinfo(skb);
 4105	u16 gso_segs;
 4106
 4107	qdisc_skb_cb(skb)->pkt_len = skb->len;
 4108	if (!shinfo->gso_size) {
 4109		qdisc_skb_cb(skb)->pkt_segs = 1;
 4110		return;
 4111	}
 4112
 4113	qdisc_skb_cb(skb)->pkt_segs = gso_segs = shinfo->gso_segs;
 4114
 4115	/* To get more precise estimation of bytes sent on wire,
 4116	 * we add to pkt_len the headers size of all segments
 4117	 */
 4118	if (skb_transport_header_was_set(skb)) {
 4119		unsigned int hdr_len;
 4120
 4121		/* mac layer + network layer */
 4122		if (!skb->encapsulation)
 4123			hdr_len = skb_transport_offset(skb);
 4124		else
 4125			hdr_len = skb_inner_transport_offset(skb);
 4126
 4127		/* + transport layer */
 4128		if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
 4129			const struct tcphdr *th;
 4130			struct tcphdr _tcphdr;
 4131
 4132			th = skb_header_pointer(skb, hdr_len,
 4133						sizeof(_tcphdr), &_tcphdr);
 4134			if (likely(th))
 4135				hdr_len += __tcp_hdrlen(th);
 4136		} else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
 4137			struct udphdr _udphdr;
 4138
 4139			if (skb_header_pointer(skb, hdr_len,
 4140					       sizeof(_udphdr), &_udphdr))
 4141				hdr_len += sizeof(struct udphdr);
 4142		}
 4143
 4144		if (unlikely(shinfo->gso_type & SKB_GSO_DODGY)) {
 4145			int payload = skb->len - hdr_len;
 4146
 4147			/* Malicious packet. */
 4148			if (payload <= 0)
 4149				return;
 4150			gso_segs = DIV_ROUND_UP(payload, shinfo->gso_size);
 4151			shinfo->gso_segs = gso_segs;
 4152			qdisc_skb_cb(skb)->pkt_segs = gso_segs;
 4153		}
 4154		qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
 4155	}
 4156}
 4157
 4158static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q,
 4159			     struct sk_buff **to_free,
 4160			     struct netdev_queue *txq)
 4161{
 4162	int rc;
 4163
 4164	rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK;
 4165	if (rc == NET_XMIT_SUCCESS)
 4166		trace_qdisc_enqueue(q, txq, skb);
 4167	return rc;
 4168}
 4169
 4170static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
 4171				 struct net_device *dev,
 4172				 struct netdev_queue *txq)
 4173{
 4174	struct sk_buff *next, *to_free = NULL, *to_free2 = NULL;
 4175	spinlock_t *root_lock = qdisc_lock(q);
 4176	struct llist_node *ll_list, *first_n;
 4177	unsigned long defer_count = 0;
 4178	int rc;
 4179
 4180	qdisc_calculate_pkt_len(skb, q);
 4181
 4182	tcf_set_drop_reason(skb, SKB_DROP_REASON_QDISC_DROP);
 4183
 4184	if (q->flags & TCQ_F_NOLOCK) {
 4185		if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) &&
 4186		    qdisc_run_begin(q)) {
 4187			/* Retest nolock_qdisc_is_empty() within the protection
 4188			 * of q->seqlock to protect from racing with requeuing.
 4189			 */
 4190			if (unlikely(!nolock_qdisc_is_empty(q))) {
 4191				rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
 4192				__qdisc_run(q);
 4193				to_free2 = qdisc_run_end(q);
 4194
 4195				goto free_skbs;
 4196			}
 4197
 4198			qdisc_bstats_cpu_update(q, skb);
 4199			if (sch_direct_xmit(skb, q, dev, txq, NULL, true) &&
 4200			    !nolock_qdisc_is_empty(q))
 4201				__qdisc_run(q);
 4202
 4203			to_free2 = qdisc_run_end(q);
 4204			rc = NET_XMIT_SUCCESS;
 4205			goto free_skbs;
 4206		}
 4207
 4208		rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
 4209		to_free2 = qdisc_run(q);
 4210		goto free_skbs;
 4211	}
 4212
 4213	/* Open code llist_add(&skb->ll_node, &q->defer_list) + queue limit.
 4214	 * In the try_cmpxchg() loop, we want to increment q->defer_count
 4215	 * at most once to limit the number of skbs in defer_list.
 4216	 * We perform the defer_count increment only if the list is not empty,
 4217	 * because some arches have slow atomic_long_inc_return().
 4218	 */
 4219	first_n = READ_ONCE(q->defer_list.first);
 4220	do {
 4221		if (first_n && !defer_count) {
 4222			defer_count = atomic_long_inc_return(&q->defer_count);
 4223			if (unlikely(defer_count > READ_ONCE(net_hotdata.qdisc_max_burst))) {
 4224				kfree_skb_reason(skb, SKB_DROP_REASON_QDISC_BURST_DROP);
 4225				return NET_XMIT_DROP;
 4226			}
 4227		}
 4228		skb->ll_node.next = first_n;
 4229	} while (!try_cmpxchg(&q->defer_list.first, &first_n, &skb->ll_node));
 4230
 4231	/* If defer_list was not empty, we know the cpu which queued
 4232	 * the first skb will process the whole list for us.
 4233	 */
 4234	if (first_n)
 4235		return NET_XMIT_SUCCESS;
 4236
 4237	spin_lock(root_lock);
 4238
 4239	ll_list = llist_del_all(&q->defer_list);
 4240	/* There is a small race because we clear defer_count not atomically
 4241	 * with the prior llist_del_all(). This means defer_list could grow
 4242	 * over qdisc_max_burst.
 4243	 */
 4244	atomic_long_set(&q->defer_count, 0);
 4245
 4246	ll_list = llist_reverse_order(ll_list);
 4247
 4248	if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
 4249		llist_for_each_entry_safe(skb, next, ll_list, ll_node)
 4250			__qdisc_drop(skb, &to_free);
 4251		rc = NET_XMIT_DROP;
 4252		goto unlock;
 4253	}
 4254	if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
 4255	    !llist_next(ll_list) && qdisc_run_begin(q)) {
 4256		/*
 4257		 * This is a work-conserving queue; there are no old skbs
 4258		 * waiting to be sent out; and the qdisc is not running -
 4259		 * xmit the skb directly.
 4260		 */
 4261
 4262		DEBUG_NET_WARN_ON_ONCE(skb != llist_entry(ll_list,
 4263							  struct sk_buff,
 4264							  ll_node));
 4265		qdisc_bstats_update(q, skb);
 4266		if (sch_direct_xmit(skb, q, dev, txq, root_lock, true))
 4267			__qdisc_run(q);
 4268		to_free2 = qdisc_run_end(q);
 4269		rc = NET_XMIT_SUCCESS;
 4270	} else {
 4271		int count = 0;
 4272
 4273		llist_for_each_entry_safe(skb, next, ll_list, ll_node) {
 4274			if (next) {
 4275				prefetch(next);
 4276				prefetch(&next->priority);
 4277				skb_mark_not_on_list(skb);
 4278			}
 4279			rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
 4280			count++;
 4281		}
 4282		to_free2 = qdisc_run(q);
 4283		if (count != 1)
 4284			rc = NET_XMIT_SUCCESS;
 4285	}
 4286unlock:
 4287	spin_unlock(root_lock);
 4288
 4289free_skbs:
 4290	tcf_kfree_skb_list(to_free);
 4291	tcf_kfree_skb_list(to_free2);
 4292	return rc;
 4293}
 4294
 4295#if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
 4296static void skb_update_prio(struct sk_buff *skb)
 4297{
 4298	const struct netprio_map *map;
 4299	const struct sock *sk;
 4300	unsigned int prioidx;
 4301
 4302	if (skb->priority)
 4303		return;
 4304	map = rcu_dereference_bh(skb->dev->priomap);
 4305	if (!map)
 4306		return;
 4307	sk = skb_to_full_sk(skb);
 4308	if (!sk)
 4309		return;
 4310
 4311	prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
 4312
 4313	if (prioidx < map->priomap_len)
 4314		skb->priority = map->priomap[prioidx];
 4315}
 4316#else
 4317#define skb_update_prio(skb)
 4318#endif
 4319
 4320/**
 4321 *	dev_loopback_xmit - loop back @skb
 4322 *	@net: network namespace this loopback is happening in
 4323 *	@sk:  sk needed to be a netfilter okfn
 4324 *	@skb: buffer to transmit
 4325 */
 4326int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
 4327{
 4328	skb_reset_mac_header(skb);
 4329	__skb_pull(skb, skb_network_offset(skb));
 4330	skb->pkt_type = PACKET_LOOPBACK;
 4331	if (skb->ip_summed == CHECKSUM_NONE)
 4332		skb->ip_summed = CHECKSUM_UNNECESSARY;
 4333	DEBUG_NET_WARN_ON_ONCE(!skb_dst(skb));
 4334	skb_dst_force(skb);
 4335	netif_rx(skb);
 4336	return 0;
 4337}
 4338EXPORT_SYMBOL(dev_loopback_xmit);
 4339
 4340#ifdef CONFIG_NET_EGRESS
 4341static struct netdev_queue *
 4342netdev_tx_queue_mapping(struct net_device *dev, struct sk_buff *skb)
 4343{
 4344	int qm = skb_get_queue_mapping(skb);
 4345
 4346	return netdev_get_tx_queue(dev, netdev_cap_txqueue(dev, qm));
 4347}
 4348
 4349#ifndef CONFIG_PREEMPT_RT
 4350static bool netdev_xmit_txqueue_skipped(void)
 4351{
 4352	return __this_cpu_read(softnet_data.xmit.skip_txqueue);
 4353}
 4354
 4355void netdev_xmit_skip_txqueue(bool skip)
 4356{
 4357	__this_cpu_write(softnet_data.xmit.skip_txqueue, skip);
 4358}
 4359EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
 4360
 4361#else
 4362static bool netdev_xmit_txqueue_skipped(void)
 4363{
 4364	return current->net_xmit.skip_txqueue;
 4365}
 4366
 4367void netdev_xmit_skip_txqueue(bool skip)
 4368{
 4369	current->net_xmit.skip_txqueue = skip;
 4370}
 4371EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
 4372#endif
 4373#endif /* CONFIG_NET_EGRESS */
 4374
 4375#ifdef CONFIG_NET_XGRESS
 4376static int tc_run(struct tcx_entry *entry, struct sk_buff *skb,
 4377		  enum skb_drop_reason *drop_reason)
 4378{
 4379	int ret = TC_ACT_UNSPEC;
 4380#ifdef CONFIG_NET_CLS_ACT
 4381	struct mini_Qdisc *miniq = rcu_dereference_bh(entry->miniq);
 4382	struct tcf_result res;
 4383
 4384	if (!miniq)
 4385		return ret;
 4386
 4387	/* Global bypass */
 4388	if (!static_branch_likely(&tcf_sw_enabled_key))
 4389		return ret;
 4390
 4391	/* Block-wise bypass */
 4392	if (tcf_block_bypass_sw(miniq->block))
 4393		return ret;
 4394
 4395	tc_skb_cb(skb)->mru = 0;
 4396	qdisc_skb_cb(skb)->post_ct = false;
 4397	tcf_set_drop_reason(skb, *drop_reason);
 4398
 4399	mini_qdisc_bstats_cpu_update(miniq, skb);
 4400	ret = tcf_classify(skb, miniq->block, miniq->filter_list, &res, false);
 4401	/* Only tcf related quirks below. */
 4402	switch (ret) {
 4403	case TC_ACT_SHOT:
 4404		*drop_reason = tcf_get_drop_reason(skb);
 4405		mini_qdisc_qstats_cpu_drop(miniq);
 4406		break;
 4407	case TC_ACT_OK:
 4408	case TC_ACT_RECLASSIFY:
 4409		skb->tc_index = TC_H_MIN(res.classid);
 4410		break;
 4411	}
 4412#endif /* CONFIG_NET_CLS_ACT */
 4413	return ret;
 4414}
 4415
 4416static DEFINE_STATIC_KEY_FALSE(tcx_needed_key);
 4417
 4418void tcx_inc(void)
 4419{
 4420	static_branch_inc(&tcx_needed_key);
 4421}
 4422
 4423void tcx_dec(void)
 4424{
 4425	static_branch_dec(&tcx_needed_key);
 4426}
 4427
 4428static __always_inline enum tcx_action_base
 4429tcx_run(const struct bpf_mprog_entry *entry, struct sk_buff *skb,
 4430	const bool needs_mac)
 4431{
 4432	const struct bpf_mprog_fp *fp;
 4433	const struct bpf_prog *prog;
 4434	int ret = TCX_NEXT;
 4435
 4436	if (needs_mac)
 4437		__skb_push(skb, skb->mac_len);
 4438	bpf_mprog_foreach_prog(entry, fp, prog) {
 4439		bpf_compute_data_pointers(skb);
 4440		ret = bpf_prog_run(prog, skb);
 4441		if (ret != TCX_NEXT)
 4442			break;
 4443	}
 4444	if (needs_mac)
 4445		__skb_pull(skb, skb->mac_len);
 4446	return tcx_action_code(skb, ret);
 4447}
 4448
 4449static __always_inline struct sk_buff *
 4450sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
 4451		   struct net_device *orig_dev, bool *another)
 4452{
 4453	struct bpf_mprog_entry *entry = rcu_dereference_bh(skb->dev->tcx_ingress);
 4454	enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_INGRESS;
 4455	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
 4456	int sch_ret;
 4457
 4458	if (!entry)
 4459		return skb;
 4460
 4461	bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
 4462	if (unlikely(*pt_prev)) {
 4463		*ret = deliver_skb(skb, *pt_prev, orig_dev);
 4464		*pt_prev = NULL;
 4465	}
 4466
 4467	qdisc_pkt_len_segs_init(skb);
 4468	tcx_set_ingress(skb, true);
 4469
 4470	if (static_branch_unlikely(&tcx_needed_key)) {
 4471		sch_ret = tcx_run(entry, skb, true);
 4472		if (sch_ret != TC_ACT_UNSPEC)
 4473			goto ingress_verdict;
 4474	}
 4475	sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason);
 4476ingress_verdict:
 4477	switch (sch_ret) {
 4478	case TC_ACT_REDIRECT:
 4479		/* skb_mac_header check was done by BPF, so we can safely
 4480		 * push the L2 header back before redirecting to another
 4481		 * netdev.
 4482		 */
 4483		__skb_push(skb, skb->mac_len);
 4484		if (skb_do_redirect(skb) == -EAGAIN) {
 4485			__skb_pull(skb, skb->mac_len);
 4486			*another = true;
 4487			break;
 4488		}
 4489		*ret = NET_RX_SUCCESS;
 4490		bpf_net_ctx_clear(bpf_net_ctx);
 4491		return NULL;
 4492	case TC_ACT_SHOT:
 4493		kfree_skb_reason(skb, drop_reason);
 4494		*ret = NET_RX_DROP;
 4495		bpf_net_ctx_clear(bpf_net_ctx);
 4496		return NULL;
 4497	/* used by tc_run */
 4498	case TC_ACT_STOLEN:
 4499	case TC_ACT_QUEUED:
 4500	case TC_ACT_TRAP:
 4501		consume_skb(skb);
 4502		fallthrough;
 4503	case TC_ACT_CONSUMED:
 4504		*ret = NET_RX_SUCCESS;
 4505		bpf_net_ctx_clear(bpf_net_ctx);
 4506		return NULL;
 4507	}
 4508	bpf_net_ctx_clear(bpf_net_ctx);
 4509
 4510	return skb;
 4511}
 4512
 4513static __always_inline struct sk_buff *
 4514sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
 4515{
 4516	struct bpf_mprog_entry *entry = rcu_dereference_bh(dev->tcx_egress);
 4517	enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_EGRESS;
 4518	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
 4519	int sch_ret;
 4520
 4521	if (!entry)
 4522		return skb;
 4523
 4524	bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
 4525
 4526	/* qdisc_skb_cb(skb)->pkt_len & tcx_set_ingress() was
 4527	 * already set by the caller.
 4528	 */
 4529	if (static_branch_unlikely(&tcx_needed_key)) {
 4530		sch_ret = tcx_run(entry, skb, false);
 4531		if (sch_ret != TC_ACT_UNSPEC)
 4532			goto egress_verdict;
 4533	}
 4534	sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason);
 4535egress_verdict:
 4536	switch (sch_ret) {
 4537	case TC_ACT_REDIRECT:
 4538		/* No need to push/pop skb's mac_header here on egress! */
 4539		skb_do_redirect(skb);
 4540		*ret = NET_XMIT_SUCCESS;
 4541		bpf_net_ctx_clear(bpf_net_ctx);
 4542		return NULL;
 4543	case TC_ACT_SHOT:
 4544		kfree_skb_reason(skb, drop_reason);
 4545		*ret = NET_XMIT_DROP;
 4546		bpf_net_ctx_clear(bpf_net_ctx);
 4547		return NULL;
 4548	/* used by tc_run */
 4549	case TC_ACT_STOLEN:
 4550	case TC_ACT_QUEUED:
 4551	case TC_ACT_TRAP:
 4552		consume_skb(skb);
 4553		fallthrough;
 4554	case TC_ACT_CONSUMED:
 4555		*ret = NET_XMIT_SUCCESS;
 4556		bpf_net_ctx_clear(bpf_net_ctx);
 4557		return NULL;
 4558	}
 4559	bpf_net_ctx_clear(bpf_net_ctx);
 4560
 4561	return skb;
 4562}
 4563#else
 4564static __always_inline struct sk_buff *
 4565sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
 4566		   struct net_device *orig_dev, bool *another)
 4567{
 4568	return skb;
 4569}
 4570
 4571static __always_inline struct sk_buff *
 4572sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
 4573{
 4574	return skb;
 4575}
 4576#endif /* CONFIG_NET_XGRESS */
 4577
 4578#ifdef CONFIG_XPS
 4579static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
 4580			       struct xps_dev_maps *dev_maps, unsigned int tci)
 4581{
 4582	int tc = netdev_get_prio_tc_map(dev, skb->priority);
 4583	struct xps_map *map;
 4584	int queue_index = -1;
 4585
 4586	if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids)
 4587		return queue_index;
 4588
 4589	tci *= dev_maps->num_tc;
 4590	tci += tc;
 4591
 4592	map = rcu_dereference(dev_maps->attr_map[tci]);
 4593	if (map) {
 4594		if (map->len == 1)
 4595			queue_index = map->queues[0];
 4596		else
 4597			queue_index = map->queues[reciprocal_scale(
 4598						skb_get_hash(skb), map->len)];
 4599		if (unlikely(queue_index >= dev->real_num_tx_queues))
 4600			queue_index = -1;
 4601	}
 4602	return queue_index;
 4603}
 4604#endif
 4605
 4606static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
 4607			 struct sk_buff *skb)
 4608{
 4609#ifdef CONFIG_XPS
 4610	struct xps_dev_maps *dev_maps;
 4611	struct sock *sk = skb->sk;
 4612	int queue_index = -1;
 4613
 4614	if (!static_key_false(&xps_needed))
 4615		return -1;
 4616
 4617	rcu_read_lock();
 4618	if (!static_key_false(&xps_rxqs_needed))
 4619		goto get_cpus_map;
 4620
 4621	dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]);
 4622	if (dev_maps) {
 4623		int tci = sk_rx_queue_get(sk);
 4624
 4625		if (tci >= 0)
 4626			queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
 4627							  tci);
 4628	}
 4629
 4630get_cpus_map:
 4631	if (queue_index < 0) {
 4632		dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]);
 4633		if (dev_maps) {
 4634			unsigned int tci = skb->sender_cpu - 1;
 4635
 4636			queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
 4637							  tci);
 4638		}
 4639	}
 4640	rcu_read_unlock();
 4641
 4642	return queue_index;
 4643#else
 4644	return -1;
 4645#endif
 4646}
 4647
 4648u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
 4649		     struct net_device *sb_dev)
 4650{
 4651	return 0;
 4652}
 4653EXPORT_SYMBOL(dev_pick_tx_zero);
 4654
 4655int sk_tx_queue_get(const struct sock *sk)
 4656{
 4657	int resel, val;
 4658
 4659	if (!sk)
 4660		return -1;
 4661	/* Paired with WRITE_ONCE() in sk_tx_queue_clear()
 4662	 * and sk_tx_queue_set().
 4663	 */
 4664	val = READ_ONCE(sk->sk_tx_queue_mapping);
 4665
 4666	if (val == NO_QUEUE_MAPPING)
 4667		return -1;
 4668
 4669	if (!sk_fullsock(sk))
 4670		return val;
 4671
 4672	resel = READ_ONCE(sock_net(sk)->core.sysctl_txq_reselection);
 4673	if (resel && time_is_before_jiffies(
 4674			READ_ONCE(sk->sk_tx_queue_mapping_jiffies) + resel))
 4675		return -1;
 4676
 4677	return val;
 4678}
 4679EXPORT_SYMBOL(sk_tx_queue_get);
 4680
 4681u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
 4682		     struct net_device *sb_dev)
 4683{
 4684	struct sock *sk = skb->sk;
 4685	int queue_index = sk_tx_queue_get(sk);
 4686
 4687	sb_dev = sb_dev ? : dev;
 4688
 4689	if (queue_index < 0 || skb->ooo_okay ||
 4690	    queue_index >= dev->real_num_tx_queues) {
 4691		int new_index = get_xps_queue(dev, sb_dev, skb);
 4692
 4693		if (new_index < 0)
 4694			new_index = skb_tx_hash(dev, sb_dev, skb);
 4695
 4696		if (sk && sk_fullsock(sk) &&
 4697		    rcu_access_pointer(sk->sk_dst_cache))
 4698			sk_tx_queue_set(sk, new_index);
 4699
 4700		queue_index = new_index;
 4701	}
 4702
 4703	return queue_index;
 4704}
 4705EXPORT_SYMBOL(netdev_pick_tx);
 4706
 4707struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
 4708					 struct sk_buff *skb,
 4709					 struct net_device *sb_dev)
 4710{
 4711	int queue_index = 0;
 4712
 4713#ifdef CONFIG_XPS
 4714	u32 sender_cpu = skb->sender_cpu - 1;
 4715
 4716	if (sender_cpu >= (u32)NR_CPUS)
 4717		skb->sender_cpu = raw_smp_processor_id() + 1;
 4718#endif
 4719
 4720	if (dev->real_num_tx_queues != 1) {
 4721		const struct net_device_ops *ops = dev->netdev_ops;
 4722
 4723		if (ops->ndo_select_queue)
 4724			queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
 4725		else
 4726			queue_index = netdev_pick_tx(dev, skb, sb_dev);
 4727
 4728		queue_index = netdev_cap_txqueue(dev, queue_index);
 4729	}
 4730
 4731	skb_set_queue_mapping(skb, queue_index);
 4732	return netdev_get_tx_queue(dev, queue_index);
 4733}
 4734
 4735/**
 4736 * __dev_queue_xmit() - transmit a buffer
 4737 * @skb:	buffer to transmit
 4738 * @sb_dev:	suboordinate device used for L2 forwarding offload
 4739 *
 4740 * Queue a buffer for transmission to a network device. The caller must
 4741 * have set the device and priority and built the buffer before calling
 4742 * this function. The function can be called from an interrupt.
 4743 *
 4744 * When calling this method, interrupts MUST be enabled. This is because
 4745 * the BH enable code must have IRQs enabled so that it will not deadlock.
 4746 *
 4747 * Regardless of the return value, the skb is consumed, so it is currently
 4748 * difficult to retry a send to this method. (You can bump the ref count
 4749 * before sending to hold a reference for retry if you are careful.)
 4750 *
 4751 * Return:
 4752 * * 0				- buffer successfully transmitted
 4753 * * positive qdisc return code	- NET_XMIT_DROP etc.
 4754 * * negative errno		- other errors
 4755 */
 4756int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
 4757{
 4758	struct net_device *dev = skb->dev;
 4759	struct netdev_queue *txq = NULL;
 4760	struct Qdisc *q;
 4761	int rc = -ENOMEM;
 4762	bool again = false;
 4763
 4764	skb_reset_mac_header(skb);
 4765	skb_assert_len(skb);
 4766
 4767	if (unlikely(skb_shinfo(skb)->tx_flags &
 4768		     (SKBTX_SCHED_TSTAMP | SKBTX_BPF)))
 4769		__skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED);
 4770
 4771	/* Disable soft irqs for various locks below. Also
 4772	 * stops preemption for RCU.
 4773	 */
 4774	rcu_read_lock_bh();
 4775
 4776	skb_update_prio(skb);
 4777
 4778	qdisc_pkt_len_segs_init(skb);
 4779	tcx_set_ingress(skb, false);
 4780#ifdef CONFIG_NET_EGRESS
 4781	if (static_branch_unlikely(&egress_needed_key)) {
 4782		if (nf_hook_egress_active()) {
 4783			skb = nf_hook_egress(skb, &rc, dev);
 4784			if (!skb)
 4785				goto out;
 4786		}
 4787
 4788		netdev_xmit_skip_txqueue(false);
 4789
 4790		nf_skip_egress(skb, true);
 4791		skb = sch_handle_egress(skb, &rc, dev);
 4792		if (!skb)
 4793			goto out;
 4794		nf_skip_egress(skb, false);
 4795
 4796		if (netdev_xmit_txqueue_skipped())
 4797			txq = netdev_tx_queue_mapping(dev, skb);
 4798	}
 4799#endif
 4800	/* If device/qdisc don't need skb->dst, release it right now while
 4801	 * its hot in this cpu cache.
 4802	 */
 4803	if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
 4804		skb_dst_drop(skb);
 4805	else
 4806		skb_dst_force(skb);
 4807
 4808	if (!txq)
 4809		txq = netdev_core_pick_tx(dev, skb, sb_dev);
 4810
 4811	q = rcu_dereference_bh(txq->qdisc);
 4812
 4813	trace_net_dev_queue(skb);
 4814	if (q->enqueue) {
 4815		rc = __dev_xmit_skb(skb, q, dev, txq);
 4816		goto out;
 4817	}
 4818
 4819	/* The device has no queue. Common case for software devices:
 4820	 * loopback, all the sorts of tunnels...
 4821
 4822	 * Really, it is unlikely that netif_tx_lock protection is necessary
 4823	 * here.  (f.e. loopback and IP tunnels are clean ignoring statistics
 4824	 * counters.)
 4825	 * However, it is possible, that they rely on protection
 4826	 * made by us here.
 4827
 4828	 * Check this and shot the lock. It is not prone from deadlocks.
 4829	 *Either shot noqueue qdisc, it is even simpler 8)
 4830	 */
 4831	if (dev->flags & IFF_UP) {
 4832		int cpu = smp_processor_id(); /* ok because BHs are off */
 4833
 4834		if (!netif_tx_owned(txq, cpu)) {
 4835			bool is_list = false;
 4836
 4837			if (dev_xmit_recursion())
 4838				goto recursion_alert;
 4839
 4840			skb = validate_xmit_skb(skb, dev, &again);
 4841			if (!skb)
 4842				goto out;
 4843
 4844			HARD_TX_LOCK(dev, txq, cpu);
 4845
 4846			if (!netif_xmit_stopped(txq)) {
 4847				is_list = !!skb->next;
 4848
 4849				dev_xmit_recursion_inc();
 4850				skb = dev_hard_start_xmit(skb, dev, txq, &rc);
 4851				dev_xmit_recursion_dec();
 4852
 4853				/* GSO segments a single SKB into
 4854				 * a list of frames. TCP expects error
 4855				 * to mean none of the data was sent.
 4856				 */
 4857				if (is_list)
 4858					rc = NETDEV_TX_OK;
 4859			}
 4860			HARD_TX_UNLOCK(dev, txq);
 4861			if (!skb) /* xmit completed */
 4862				goto out;
 4863
 4864			net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
 4865					     dev->name);
 4866			/* NETDEV_TX_BUSY or queue was stopped */
 4867			if (!is_list)
 4868				rc = -ENETDOWN;
 4869		} else {
 4870			/* Recursion is detected! It is possible,
 4871			 * unfortunately
 4872			 */
 4873recursion_alert:
 4874			net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
 4875					     dev->name);
 4876			rc = -ENETDOWN;
 4877		}
 4878	}
 4879
 4880	rcu_read_unlock_bh();
 4881
 4882	dev_core_stats_tx_dropped_inc(dev);
 4883	kfree_skb_list(skb);
 4884	return rc;
 4885out:
 4886	rcu_read_unlock_bh();
 4887	return rc;
 4888}
 4889EXPORT_SYMBOL(__dev_queue_xmit);
 4890
 4891int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
 4892{
 4893	struct net_device *dev = skb->dev;
 4894	struct sk_buff *orig_skb = skb;
 4895	struct netdev_queue *txq;
 4896	int ret = NETDEV_TX_BUSY;
 4897	bool again = false;
 4898
 4899	if (unlikely(!netif_running(dev) ||
 4900		     !netif_carrier_ok(dev)))
 4901		goto drop;
 4902
 4903	skb = validate_xmit_skb_list(skb, dev, &again);
 4904	if (skb != orig_skb)
 4905		goto drop;
 4906
 4907	skb_set_queue_mapping(skb, queue_id);
 4908	txq = skb_get_tx_queue(dev, skb);
 4909
 4910	local_bh_disable();
 4911
 4912	dev_xmit_recursion_inc();
 4913	HARD_TX_LOCK(dev, txq, smp_processor_id());
 4914	if (!netif_xmit_frozen_or_drv_stopped(txq))
 4915		ret = netdev_start_xmit(skb, dev, txq, false);
 4916	HARD_TX_UNLOCK(dev, txq);
 4917	dev_xmit_recursion_dec();
 4918
 4919	local_bh_enable();
 4920	return ret;
 4921drop:
 4922	dev_core_stats_tx_dropped_inc(dev);
 4923	kfree_skb_list(skb);
 4924	return NET_XMIT_DROP;
 4925}
 4926EXPORT_SYMBOL(__dev_direct_xmit);
 4927
 4928/*************************************************************************
 4929 *			Receiver routines
 4930 *************************************************************************/
 4931static DEFINE_PER_CPU(struct task_struct *, backlog_napi);
 4932
 4933int weight_p __read_mostly = 64;           /* old backlog weight */
 4934int dev_weight_rx_bias __read_mostly = 1;  /* bias for backlog weight */
 4935int dev_weight_tx_bias __read_mostly = 1;  /* bias for output_queue quota */
 4936
 4937/* Called with irq disabled */
 4938static inline void ____napi_schedule(struct softnet_data *sd,
 4939				     struct napi_struct *napi)
 4940{
 4941	struct task_struct *thread;
 4942
 4943	lockdep_assert_irqs_disabled();
 4944
 4945	if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
 4946		/* Paired with smp_mb__before_atomic() in
 4947		 * napi_enable()/netif_set_threaded().
 4948		 * Use READ_ONCE() to guarantee a complete
 4949		 * read on napi->thread. Only call
 4950		 * wake_up_process() when it's not NULL.
 4951		 */
 4952		thread = READ_ONCE(napi->thread);
 4953		if (thread) {
 4954			if (use_backlog_threads() && thread == raw_cpu_read(backlog_napi))
 4955				goto use_local_napi;
 4956
 4957			set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
 4958			wake_up_process(thread);
 4959			return;
 4960		}
 4961	}
 4962
 4963use_local_napi:
 4964	DEBUG_NET_WARN_ON_ONCE(!list_empty(&napi->poll_list));
 4965	list_add_tail(&napi->poll_list, &sd->poll_list);
 4966	WRITE_ONCE(napi->list_owner, smp_processor_id());
 4967	/* If not called from net_rx_action()
 4968	 * we have to raise NET_RX_SOFTIRQ.
 4969	 */
 4970	if (!sd->in_net_rx_action)
 4971		raise_softirq_irqoff(NET_RX_SOFTIRQ);
 4972}
 4973
 4974#ifdef CONFIG_RPS
 4975
 4976struct static_key_false rps_needed __read_mostly;
 4977EXPORT_SYMBOL(rps_needed);
 4978struct static_key_false rfs_needed __read_mostly;
 4979EXPORT_SYMBOL(rfs_needed);
 4980
 4981static u32 rfs_slot(u32 hash, const struct rps_dev_flow_table *flow_table)
 4982{
 4983	return hash_32(hash, flow_table->log);
 4984}
 4985
 4986#ifdef CONFIG_RFS_ACCEL
 4987/**
 4988 * rps_flow_is_active - check whether the flow is recently active.
 4989 * @rflow: Specific flow to check activity.
 4990 * @flow_table: per-queue flowtable that @rflow belongs to.
 4991 * @cpu: CPU saved in @rflow.
 4992 *
 4993 * If the CPU has processed many packets since the flow's last activity
 4994 * (beyond 10 times the table size), the flow is considered stale.
 4995 *
 4996 * Return: true if flow was recently active.
 4997 */
 4998static bool rps_flow_is_active(struct rps_dev_flow *rflow,
 4999			       struct rps_dev_flow_table *flow_table,
 5000			       unsigned int cpu)
 5001{
 5002	unsigned int flow_last_active;
 5003	unsigned int sd_input_head;
 5004
 5005	if (cpu >= nr_cpu_ids)
 5006		return false;
 5007
 5008	sd_input_head = READ_ONCE(per_cpu(softnet_data, cpu).input_queue_head);
 5009	flow_last_active = READ_ONCE(rflow->last_qtail);
 5010
 5011	return (int)(sd_input_head - flow_last_active) <
 5012		(int)(10 << flow_table->log);
 5013}
 5014#endif
 5015
 5016static struct rps_dev_flow *
 5017set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
 5018	    struct rps_dev_flow *rflow, u16 next_cpu, u32 hash)
 5019{
 5020	if (next_cpu < nr_cpu_ids) {
 5021		u32 head;
 5022#ifdef CONFIG_RFS_ACCEL
 5023		struct netdev_rx_queue *rxqueue;
 5024		struct rps_dev_flow_table *flow_table;
 5025		struct rps_dev_flow *old_rflow;
 5026		struct rps_dev_flow *tmp_rflow;
 5027		unsigned int tmp_cpu;
 5028		u16 rxq_index;
 5029		u32 flow_id;
 5030		int rc;
 5031
 5032		/* Should we steer this flow to a different hardware queue? */
 5033		if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
 5034		    !(dev->features & NETIF_F_NTUPLE))
 5035			goto out;
 5036		rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
 5037		if (rxq_index == skb_get_rx_queue(skb))
 5038			goto out;
 5039
 5040		rxqueue = dev->_rx + rxq_index;
 5041		flow_table = rcu_dereference(rxqueue->rps_flow_table);
 5042		if (!flow_table)
 5043			goto out;
 5044
 5045		flow_id = rfs_slot(hash, flow_table);
 5046		tmp_rflow = &flow_table->flows[flow_id];
 5047		tmp_cpu = READ_ONCE(tmp_rflow->cpu);
 5048
 5049		if (READ_ONCE(tmp_rflow->filter) != RPS_NO_FILTER) {
 5050			if (rps_flow_is_active(tmp_rflow, flow_table,
 5051					       tmp_cpu)) {
 5052				if (hash != READ_ONCE(tmp_rflow->hash) ||
 5053				    next_cpu == tmp_cpu)
 5054					goto out;
 5055			}
 5056		}
 5057
 5058		rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
 5059							rxq_index, flow_id);
 5060		if (rc < 0)
 5061			goto out;
 5062
 5063		old_rflow = rflow;
 5064		rflow = tmp_rflow;
 5065		WRITE_ONCE(rflow->filter, rc);
 5066		WRITE_ONCE(rflow->hash, hash);
 5067
 5068		if (old_rflow->filter == rc)
 5069			WRITE_ONCE(old_rflow->filter, RPS_NO_FILTER);
 5070	out:
 5071#endif
 5072		head = READ_ONCE(per_cpu(softnet_data, next_cpu).input_queue_head);
 5073		rps_input_queue_tail_save(&rflow->last_qtail, head);
 5074	}
 5075
 5076	WRITE_ONCE(rflow->cpu, next_cpu);
 5077	return rflow;
 5078}
 5079
 5080/*
 5081 * get_rps_cpu is called from netif_receive_skb and returns the target
 5082 * CPU from the RPS map of the receiving queue for a given skb.
 5083 * rcu_read_lock must be held on entry.
 5084 */
 5085static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
 5086		       struct rps_dev_flow **rflowp)
 5087{
 5088	const struct rps_sock_flow_table *sock_flow_table;
 5089	struct netdev_rx_queue *rxqueue = dev->_rx;
 5090	struct rps_dev_flow_table *flow_table;
 5091	struct rps_map *map;
 5092	int cpu = -1;
 5093	u32 tcpu;
 5094	u32 hash;
 5095
 5096	if (skb_rx_queue_recorded(skb)) {
 5097		u16 index = skb_get_rx_queue(skb);
 5098
 5099		if (unlikely(index >= dev->real_num_rx_queues)) {
 5100			WARN_ONCE(dev->real_num_rx_queues > 1,
 5101				  "%s received packet on queue %u, but number "
 5102				  "of RX queues is %u\n",
 5103				  dev->name, index, dev->real_num_rx_queues);
 5104			goto done;
 5105		}
 5106		rxqueue += index;
 5107	}
 5108
 5109	/* Avoid computing hash if RFS/RPS is not active for this rxqueue */
 5110
 5111	flow_table = rcu_dereference(rxqueue->rps_flow_table);
 5112	map = rcu_dereference(rxqueue->rps_map);
 5113	if (!flow_table && !map)
 5114		goto done;
 5115
 5116	skb_reset_network_header(skb);
 5117	hash = skb_get_hash(skb);
 5118	if (!hash)
 5119		goto done;
 5120
 5121	sock_flow_table = rcu_dereference(net_hotdata.rps_sock_flow_table);
 5122	if (flow_table && sock_flow_table) {
 5123		struct rps_dev_flow *rflow;
 5124		u32 next_cpu;
 5125		u32 ident;
 5126
 5127		/* First check into global flow table if there is a match.
 5128		 * This READ_ONCE() pairs with WRITE_ONCE() from rps_record_sock_flow().
 5129		 */
 5130		ident = READ_ONCE(sock_flow_table->ents[hash & sock_flow_table->mask]);
 5131		if ((ident ^ hash) & ~net_hotdata.rps_cpu_mask)
 5132			goto try_rps;
 5133
 5134		next_cpu = ident & net_hotdata.rps_cpu_mask;
 5135
 5136		/* OK, now we know there is a match,
 5137		 * we can look at the local (per receive queue) flow table
 5138		 */
 5139		rflow = &flow_table->flows[rfs_slot(hash, flow_table)];
 5140		tcpu = rflow->cpu;
 5141
 5142		/*
 5143		 * If the desired CPU (where last recvmsg was done) is
 5144		 * different from current CPU (one in the rx-queue flow
 5145		 * table entry), switch if one of the following holds:
 5146		 *   - Current CPU is unset (>= nr_cpu_ids).
 5147		 *   - Current CPU is offline.
 5148		 *   - The current CPU's queue tail has advanced beyond the
 5149		 *     last packet that was enqueued using this table entry.
 5150		 *     This guarantees that all previous packets for the flow
 5151		 *     have been dequeued, thus preserving in order delivery.
 5152		 */
 5153		if (unlikely(tcpu != next_cpu) &&
 5154		    (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
 5155		     ((int)(READ_ONCE(per_cpu(softnet_data, tcpu).input_queue_head) -
 5156		      rflow->last_qtail)) >= 0)) {
 5157			tcpu = next_cpu;
 5158			rflow = set_rps_cpu(dev, skb, rflow, next_cpu, hash);
 5159		}
 5160
 5161		if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
 5162			*rflowp = rflow;
 5163			cpu = tcpu;
 5164			goto done;
 5165		}
 5166	}
 5167
 5168try_rps:
 5169
 5170	if (map) {
 5171		tcpu = map->cpus[reciprocal_scale(hash, map->len)];
 5172		if (cpu_online(tcpu)) {
 5173			cpu = tcpu;
 5174			goto done;
 5175		}
 5176	}
 5177
 5178done:
 5179	return cpu;
 5180}
 5181
 5182#ifdef CONFIG_RFS_ACCEL
 5183
 5184/**
 5185 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
 5186 * @dev: Device on which the filter was set
 5187 * @rxq_index: RX queue index
 5188 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
 5189 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
 5190 *
 5191 * Drivers that implement ndo_rx_flow_steer() should periodically call
 5192 * this function for each installed filter and remove the filters for
 5193 * which it returns %true.
 5194 */
 5195bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
 5196			 u32 flow_id, u16 filter_id)
 5197{
 5198	struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
 5199	struct rps_dev_flow_table *flow_table;
 5200	struct rps_dev_flow *rflow;
 5201	bool expire = true;
 5202
 5203	rcu_read_lock();
 5204	flow_table = rcu_dereference(rxqueue->rps_flow_table);
 5205	if (flow_table && flow_id < (1UL << flow_table->log)) {
 5206		unsigned int cpu;
 5207
 5208		rflow = &flow_table->flows[flow_id];
 5209		cpu = READ_ONCE(rflow->cpu);
 5210		if (READ_ONCE(rflow->filter) == filter_id &&
 5211		    rps_flow_is_active(rflow, flow_table, cpu))
 5212			expire = false;
 5213	}
 5214	rcu_read_unlock();
 5215	return expire;
 5216}
 5217EXPORT_SYMBOL(rps_may_expire_flow);
 5218
 5219#endif /* CONFIG_RFS_ACCEL */
 5220
 5221/* Called from hardirq (IPI) context */
 5222static void rps_trigger_softirq(void *data)
 5223{
 5224	struct softnet_data *sd = data;
 5225
 5226	____napi_schedule(sd, &sd->backlog);
 5227	/* Pairs with READ_ONCE() in softnet_seq_show() */
 5228	WRITE_ONCE(sd->received_rps, sd->received_rps + 1);
 5229}
 5230
 5231#endif /* CONFIG_RPS */
 5232
 5233/* Called from hardirq (IPI) context */
 5234static void trigger_rx_softirq(void *data)
 5235{
 5236	struct softnet_data *sd = data;
 5237
 5238	__raise_softirq_irqoff(NET_RX_SOFTIRQ);
 5239	smp_store_release(&sd->defer_ipi_scheduled, 0);
 5240}
 5241
 5242/*
 5243 * After we queued a packet into sd->input_pkt_queue,
 5244 * we need to make sure this queue is serviced soon.
 5245 *
 5246 * - If this is another cpu queue, link it to our rps_ipi_list,
 5247 *   and make sure we will process rps_ipi_list from net_rx_action().
 5248 *
 5249 * - If this is our own queue, NAPI schedule our backlog.
 5250 *   Note that this also raises NET_RX_SOFTIRQ.
 5251 */
 5252static void napi_schedule_rps(struct softnet_data *sd)
 5253{
 5254	struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
 5255
 5256#ifdef CONFIG_RPS
 5257	if (sd != mysd) {
 5258		if (use_backlog_threads()) {
 5259			__napi_schedule_irqoff(&sd->backlog);
 5260			return;
 5261		}
 5262
 5263		sd->rps_ipi_next = mysd->rps_ipi_list;
 5264		mysd->rps_ipi_list = sd;
 5265
 5266		/* If not called from net_rx_action() or napi_threaded_poll()
 5267		 * we have to raise NET_RX_SOFTIRQ.
 5268		 */
 5269		if (!mysd->in_net_rx_action && !mysd->in_napi_threaded_poll)
 5270			__raise_softirq_irqoff(NET_RX_SOFTIRQ);
 5271		return;
 5272	}
 5273#endif /* CONFIG_RPS */
 5274	__napi_schedule_irqoff(&mysd->backlog);
 5275}
 5276
 5277void kick_defer_list_purge(unsigned int cpu)
 5278{
 5279	struct softnet_data *sd = &per_cpu(softnet_data, cpu);
 5280	unsigned long flags;
 5281
 5282	if (use_backlog_threads()) {
 5283		backlog_lock_irq_save(sd, &flags);
 5284
 5285		if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state))
 5286			__napi_schedule_irqoff(&sd->backlog);
 5287
 5288		backlog_unlock_irq_restore(sd, &flags);
 5289
 5290	} else if (!cmpxchg(&sd->defer_ipi_scheduled, 0, 1)) {
 5291		smp_call_function_single_async(cpu, &sd->defer_csd);
 5292	}
 5293}
 5294
 5295#ifdef CONFIG_NET_FLOW_LIMIT
 5296int netdev_flow_limit_table_len __read_mostly = (1 << 12);
 5297#endif
 5298
 5299static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen,
 5300			   int max_backlog)
 5301{
 5302#ifdef CONFIG_NET_FLOW_LIMIT
 5303	unsigned int old_flow, new_flow;
 5304	const struct softnet_data *sd;
 5305	struct sd_flow_limit *fl;
 5306
 5307	if (likely(qlen < (max_backlog >> 1)))
 5308		return false;
 5309
 5310	sd = this_cpu_ptr(&softnet_data);
 5311
 5312	rcu_read_lock();
 5313	fl = rcu_dereference(sd->flow_limit);
 5314	if (fl) {
 5315		new_flow = hash_32(skb_get_hash(skb), fl->log_buckets);
 5316		old_flow = fl->history[fl->history_head];
 5317		fl->history[fl->history_head] = new_flow;
 5318
 5319		fl->history_head++;
 5320		fl->history_head &= FLOW_LIMIT_HISTORY - 1;
 5321
 5322		if (likely(fl->buckets[old_flow]))
 5323			fl->buckets[old_flow]--;
 5324
 5325		if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
 5326			/* Pairs with READ_ONCE() in softnet_seq_show() */
 5327			WRITE_ONCE(fl->count, fl->count + 1);
 5328			rcu_read_unlock();
 5329			return true;
 5330		}
 5331	}
 5332	rcu_read_unlock();
 5333#endif
 5334	return false;
 5335}
 5336
 5337/*
 5338 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
 5339 * queue (may be a remote CPU queue).
 5340 */
 5341static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
 5342			      unsigned int *qtail)
 5343{
 5344	enum skb_drop_reason reason;
 5345	struct softnet_data *sd;
 5346	unsigned long flags;
 5347	unsigned int qlen;
 5348	int max_backlog;
 5349	u32 tail;
 5350
 5351	reason = SKB_DROP_REASON_DEV_READY;
 5352	if (unlikely(!netif_running(skb->dev)))
 5353		goto bad_dev;
 5354
 5355	sd = &per_cpu(softnet_data, cpu);
 5356
 5357	qlen = skb_queue_len_lockless(&sd->input_pkt_queue);
 5358	max_backlog = READ_ONCE(net_hotdata.max_backlog);
 5359	if (unlikely(qlen > max_backlog) ||
 5360	    skb_flow_limit(skb, qlen, max_backlog))
 5361		goto cpu_backlog_drop;
 5362	backlog_lock_irq_save(sd, &flags);
 5363	qlen = skb_queue_len(&sd->input_pkt_queue);
 5364	if (likely(qlen <= max_backlog)) {
 5365		if (!qlen) {
 5366			/* Schedule NAPI for backlog device. We can use
 5367			 * non atomic operation as we own the queue lock.
 5368			 */
 5369			if (!__test_and_set_bit(NAPI_STATE_SCHED,
 5370						&sd->backlog.state))
 5371				napi_schedule_rps(sd);
 5372		}
 5373		__skb_queue_tail(&sd->input_pkt_queue, skb);
 5374		tail = rps_input_queue_tail_incr(sd);
 5375		backlog_unlock_irq_restore(sd, &flags);
 5376
 5377		/* save the tail outside of the critical section */
 5378		rps_input_queue_tail_save(qtail, tail);
 5379		return NET_RX_SUCCESS;
 5380	}
 5381
 5382	backlog_unlock_irq_restore(sd, &flags);
 5383
 5384cpu_backlog_drop:
 5385	reason = SKB_DROP_REASON_CPU_BACKLOG;
 5386	numa_drop_add(&sd->drop_counters, 1);
 5387bad_dev:
 5388	dev_core_stats_rx_dropped_inc(skb->dev);
 5389	kfree_skb_reason(skb, reason);
 5390	return NET_RX_DROP;
 5391}
 5392
 5393static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
 5394{
 5395	struct net_device *dev = skb->dev;
 5396	struct netdev_rx_queue *rxqueue;
 5397
 5398	rxqueue = dev->_rx;
 5399
 5400	if (skb_rx_queue_recorded(skb)) {
 5401		u16 index = skb_get_rx_queue(skb);
 5402
 5403		if (unlikely(index >= dev->real_num_rx_queues)) {
 5404			WARN_ONCE(dev->real_num_rx_queues > 1,
 5405				  "%s received packet on queue %u, but number "
 5406				  "of RX queues is %u\n",
 5407				  dev->name, index, dev->real_num_rx_queues);
 5408
 5409			return rxqueue; /* Return first rxqueue */
 5410		}
 5411		rxqueue += index;
 5412	}
 5413	return rxqueue;
 5414}
 5415
 5416u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp,
 5417			     const struct bpf_prog *xdp_prog)
 5418{
 5419	void *orig_data, *orig_data_end, *hard_start;
 5420	struct netdev_rx_queue *rxqueue;
 5421	bool orig_bcast, orig_host;
 5422	u32 mac_len, frame_sz;
 5423	__be16 orig_eth_type;
 5424	struct ethhdr *eth;
 5425	u32 metalen, act;
 5426	int off;
 5427
 5428	/* The XDP program wants to see the packet starting at the MAC
 5429	 * header.
 5430	 */
 5431	mac_len = skb->data - skb_mac_header(skb);
 5432	hard_start = skb->data - skb_headroom(skb);
 5433
 5434	/* SKB "head" area always have tailroom for skb_shared_info */
 5435	frame_sz = (void *)skb_end_pointer(skb) - hard_start;
 5436	frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
 5437
 5438	rxqueue = netif_get_rxqueue(skb);
 5439	xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq);
 5440	xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len,
 5441			 skb_headlen(skb) + mac_len, true);
 5442	if (skb_is_nonlinear(skb)) {
 5443		skb_shinfo(skb)->xdp_frags_size = skb->data_len;
 5444		xdp_buff_set_frags_flag(xdp);
 5445	} else {
 5446		xdp_buff_clear_frags_flag(xdp);
 5447	}
 5448
 5449	orig_data_end = xdp->data_end;
 5450	orig_data = xdp->data;
 5451	eth = (struct ethhdr *)xdp->data;
 5452	orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr);
 5453	orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
 5454	orig_eth_type = eth->h_proto;
 5455
 5456	act = bpf_prog_run_xdp(xdp_prog, xdp);
 5457
 5458	/* check if bpf_xdp_adjust_head was used */
 5459	off = xdp->data - orig_data;
 5460	if (off) {
 5461		if (off > 0)
 5462			__skb_pull(skb, off);
 5463		else if (off < 0)
 5464			__skb_push(skb, -off);
 5465
 5466		skb->mac_header += off;
 5467		skb_reset_network_header(skb);
 5468	}
 5469
 5470	/* check if bpf_xdp_adjust_tail was used */
 5471	off = xdp->data_end - orig_data_end;
 5472	if (off != 0) {
 5473		skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
 5474		skb->len += off; /* positive on grow, negative on shrink */
 5475	}
 5476
 5477	/* XDP frag metadata (e.g. nr_frags) are updated in eBPF helpers
 5478	 * (e.g. bpf_xdp_adjust_tail), we need to update data_len here.
 5479	 */
 5480	if (xdp_buff_has_frags(xdp))
 5481		skb->data_len = skb_shinfo(skb)->xdp_frags_size;
 5482	else
 5483		skb->data_len = 0;
 5484
 5485	/* check if XDP changed eth hdr such SKB needs update */
 5486	eth = (struct ethhdr *)xdp->data;
 5487	if ((orig_eth_type != eth->h_proto) ||
 5488	    (orig_host != ether_addr_equal_64bits(eth->h_dest,
 5489						  skb->dev->dev_addr)) ||
 5490	    (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
 5491		__skb_push(skb, ETH_HLEN);
 5492		skb->pkt_type = PACKET_HOST;
 5493		skb->protocol = eth_type_trans(skb, skb->dev);
 5494	}
 5495
 5496	/* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull
 5497	 * before calling us again on redirect path. We do not call do_redirect
 5498	 * as we leave that up to the caller.
 5499	 *
 5500	 * Caller is responsible for managing lifetime of skb (i.e. calling
 5501	 * kfree_skb in response to actions it cannot handle/XDP_DROP).
 5502	 */
 5503	switch (act) {
 5504	case XDP_REDIRECT:
 5505	case XDP_TX:
 5506		__skb_push(skb, mac_len);
 5507		break;
 5508	case XDP_PASS:
 5509		metalen = xdp->data - xdp->data_meta;
 5510		if (metalen)
 5511			skb_metadata_set(skb, metalen);
 5512		break;
 5513	}
 5514
 5515	return act;
 5516}
 5517
 5518static int
 5519netif_skb_check_for_xdp(struct sk_buff **pskb, const struct bpf_prog *prog)
 5520{
 5521	struct sk_buff *skb = *pskb;
 5522	int err, hroom, troom;
 5523
 5524	local_lock_nested_bh(&system_page_pool.bh_lock);
 5525	err = skb_cow_data_for_xdp(this_cpu_read(system_page_pool.pool), pskb, prog);
 5526	local_unlock_nested_bh(&system_page_pool.bh_lock);
 5527	if (!err)
 5528		return 0;
 5529
 5530	/* In case we have to go down the path and also linearize,
 5531	 * then lets do the pskb_expand_head() work just once here.
 5532	 */
 5533	hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
 5534	troom = skb->tail + skb->data_len - skb->end;
 5535	err = pskb_expand_head(skb,
 5536			       hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
 5537			       troom > 0 ? troom + 128 : 0, GFP_ATOMIC);
 5538	if (err)
 5539		return err;
 5540
 5541	return skb_linearize(skb);
 5542}
 5543
 5544static u32 netif_receive_generic_xdp(struct sk_buff **pskb,
 5545				     struct xdp_buff *xdp,
 5546				     const struct bpf_prog *xdp_prog)
 5547{
 5548	struct sk_buff *skb = *pskb;
 5549	u32 mac_len, act = XDP_DROP;
 5550
 5551	/* Reinjected packets coming from act_mirred or similar should
 5552	 * not get XDP generic processing.
 5553	 */
 5554	if (skb_is_redirected(skb))
 5555		return XDP_PASS;
 5556
 5557	/* XDP packets must have sufficient headroom of XDP_PACKET_HEADROOM
 5558	 * bytes. This is the guarantee that also native XDP provides,
 5559	 * thus we need to do it here as well.
 5560	 */
 5561	mac_len = skb->data - skb_mac_header(skb);
 5562	__skb_push(skb, mac_len);
 5563
 5564	if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
 5565	    skb_headroom(skb) < XDP_PACKET_HEADROOM) {
 5566		if (netif_skb_check_for_xdp(pskb, xdp_prog))
 5567			goto do_drop;
 5568	}
 5569
 5570	__skb_pull(*pskb, mac_len);
 5571
 5572	act = bpf_prog_run_generic_xdp(*pskb, xdp, xdp_prog);
 5573	switch (act) {
 5574	case XDP_REDIRECT:
 5575	case XDP_TX:
 5576	case XDP_PASS:
 5577		break;
 5578	default:
 5579		bpf_warn_invalid_xdp_action((*pskb)->dev, xdp_prog, act);
 5580		fallthrough;
 5581	case XDP_ABORTED:
 5582		trace_xdp_exception((*pskb)->dev, xdp_prog, act);
 5583		fallthrough;
 5584	case XDP_DROP:
 5585	do_drop:
 5586		kfree_skb(*pskb);
 5587		break;
 5588	}
 5589
 5590	return act;
 5591}
 5592
 5593/* When doing generic XDP we have to bypass the qdisc layer and the
 5594 * network taps in order to match in-driver-XDP behavior. This also means
 5595 * that XDP packets are able to starve other packets going through a qdisc,
 5596 * and DDOS attacks will be more effective. In-driver-XDP use dedicated TX
 5597 * queues, so they do not have this starvation issue.
 5598 */
 5599void generic_xdp_tx(struct sk_buff *skb, const struct bpf_prog *xdp_prog)
 5600{
 5601	struct net_device *dev = skb->dev;
 5602	struct netdev_queue *txq;
 5603	bool free_skb = true;
 5604	int cpu, rc;
 5605
 5606	txq = netdev_core_pick_tx(dev, skb, NULL);
 5607	cpu = smp_processor_id();
 5608	HARD_TX_LOCK(dev, txq, cpu);
 5609	if (!netif_xmit_frozen_or_drv_stopped(txq)) {
 5610		rc = netdev_start_xmit(skb, dev, txq, 0);
 5611		if (dev_xmit_complete(rc))
 5612			free_skb = false;
 5613	}
 5614	HARD_TX_UNLOCK(dev, txq);
 5615	if (free_skb) {
 5616		trace_xdp_exception(dev, xdp_prog, XDP_TX);
 5617		dev_core_stats_tx_dropped_inc(dev);
 5618		kfree_skb(skb);
 5619	}
 5620}
 5621
 5622static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
 5623
 5624int do_xdp_generic(const struct bpf_prog *xdp_prog, struct sk_buff **pskb)
 5625{
 5626	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
 5627
 5628	if (xdp_prog) {
 5629		struct xdp_buff xdp;
 5630		u32 act;
 5631		int err;
 5632
 5633		bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
 5634		act = netif_receive_generic_xdp(pskb, &xdp, xdp_prog);
 5635		if (act != XDP_PASS) {
 5636			switch (act) {
 5637			case XDP_REDIRECT:
 5638				err = xdp_do_generic_redirect((*pskb)->dev, *pskb,
 5639							      &xdp, xdp_prog);
 5640				if (err)
 5641					goto out_redir;
 5642				break;
 5643			case XDP_TX:
 5644				generic_xdp_tx(*pskb, xdp_prog);
 5645				break;
 5646			}
 5647			bpf_net_ctx_clear(bpf_net_ctx);
 5648			return XDP_DROP;
 5649		}
 5650		bpf_net_ctx_clear(bpf_net_ctx);
 5651	}
 5652	return XDP_PASS;
 5653out_redir:
 5654	bpf_net_ctx_clear(bpf_net_ctx);
 5655	kfree_skb_reason(*pskb, SKB_DROP_REASON_XDP);
 5656	return XDP_DROP;
 5657}
 5658EXPORT_SYMBOL_GPL(do_xdp_generic);
 5659
 5660static int netif_rx_internal(struct sk_buff *skb)
 5661{
 5662	int ret;
 5663
 5664	net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb);
 5665
 5666	trace_netif_rx(skb);
 5667
 5668#ifdef CONFIG_RPS
 5669	if (static_branch_unlikely(&rps_needed)) {
 5670		struct rps_dev_flow voidflow, *rflow = &voidflow;
 5671		int cpu;
 5672
 5673		rcu_read_lock();
 5674
 5675		cpu = get_rps_cpu(skb->dev, skb, &rflow);
 5676		if (cpu < 0)
 5677			cpu = smp_processor_id();
 5678
 5679		ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
 5680
 5681		rcu_read_unlock();
 5682	} else
 5683#endif
 5684	{
 5685		unsigned int qtail;
 5686
 5687		ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail);
 5688	}
 5689	return ret;
 5690}
 5691
 5692/**
 5693 *	__netif_rx	-	Slightly optimized version of netif_rx
 5694 *	@skb: buffer to post
 5695 *
 5696 *	This behaves as netif_rx except that it does not disable bottom halves.
 5697 *	As a result this function may only be invoked from the interrupt context
 5698 *	(either hard or soft interrupt).
 5699 */
 5700int __netif_rx(struct sk_buff *skb)
 5701{
 5702	int ret;
 5703
 5704	lockdep_assert_once(hardirq_count() | softirq_count());
 5705
 5706	trace_netif_rx_entry(skb);
 5707	ret = netif_rx_internal(skb);
 5708	trace_netif_rx_exit(ret);
 5709	return ret;
 5710}
 5711EXPORT_SYMBOL(__netif_rx);
 5712
 5713/**
 5714 *	netif_rx	-	post buffer to the network code
 5715 *	@skb: buffer to post
 5716 *
 5717 *	This function receives a packet from a device driver and queues it for
 5718 *	the upper (protocol) levels to process via the backlog NAPI device. It
 5719 *	always succeeds. The buffer may be dropped during processing for
 5720 *	congestion control or by the protocol layers.
 5721 *	The network buffer is passed via the backlog NAPI device. Modern NIC
 5722 *	driver should use NAPI and GRO.
 5723 *	This function can used from interrupt and from process context. The
 5724 *	caller from process context must not disable interrupts before invoking
 5725 *	this function.
 5726 *
 5727 *	return values:
 5728 *	NET_RX_SUCCESS	(no congestion)
 5729 *	NET_RX_DROP     (packet was dropped)
 5730 *
 5731 */
 5732int netif_rx(struct sk_buff *skb)
 5733{
 5734	bool need_bh_off = !(hardirq_count() | softirq_count());
 5735	int ret;
 5736
 5737	if (need_bh_off)
 5738		local_bh_disable();
 5739	trace_netif_rx_entry(skb);
 5740	ret = netif_rx_internal(skb);
 5741	trace_netif_rx_exit(ret);
 5742	if (need_bh_off)
 5743		local_bh_enable();
 5744	return ret;
 5745}
 5746EXPORT_SYMBOL(netif_rx);
 5747
 5748static __latent_entropy void net_tx_action(void)
 5749{
 5750	struct softnet_data *sd = this_cpu_ptr(&softnet_data);
 5751
 5752	if (sd->completion_queue) {
 5753		struct sk_buff *clist;
 5754
 5755		local_irq_disable();
 5756		clist = sd->completion_queue;
 5757		sd->completion_queue = NULL;
 5758		local_irq_enable();
 5759
 5760		while (clist) {
 5761			struct sk_buff *skb = clist;
 5762
 5763			clist = clist->next;
 5764
 5765			WARN_ON(refcount_read(&skb->users));
 5766			if (likely(get_kfree_skb_cb(skb)->reason == SKB_CONSUMED))
 5767				trace_consume_skb(skb, net_tx_action);
 5768			else
 5769				trace_kfree_skb(skb, net_tx_action,
 5770						get_kfree_skb_cb(skb)->reason, NULL);
 5771
 5772			if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
 5773				__kfree_skb(skb);
 5774			else
 5775				__napi_kfree_skb(skb,
 5776						 get_kfree_skb_cb(skb)->reason);
 5777		}
 5778	}
 5779
 5780	if (sd->output_queue) {
 5781		struct Qdisc *head;
 5782
 5783		local_irq_disable();
 5784		head = sd->output_queue;
 5785		sd->output_queue = NULL;
 5786		sd->output_queue_tailp = &sd->output_queue;
 5787		local_irq_enable();
 5788
 5789		rcu_read_lock();
 5790
 5791		while (head) {
 5792			spinlock_t *root_lock = NULL;
 5793			struct sk_buff *to_free;
 5794			struct Qdisc *q = head;
 5795
 5796			head = head->next_sched;
 5797
 5798			/* We need to make sure head->next_sched is read
 5799			 * before clearing __QDISC_STATE_SCHED
 5800			 */
 5801			smp_mb__before_atomic();
 5802
 5803			if (!(q->flags & TCQ_F_NOLOCK)) {
 5804				root_lock = qdisc_lock(q);
 5805				spin_lock(root_lock);
 5806			} else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
 5807						     &q->state))) {
 5808				/* There is a synchronize_net() between
 5809				 * STATE_DEACTIVATED flag being set and
 5810				 * qdisc_reset()/some_qdisc_is_busy() in
 5811				 * dev_deactivate(), so we can safely bail out
 5812				 * early here to avoid data race between
 5813				 * qdisc_deactivate() and some_qdisc_is_busy()
 5814				 * for lockless qdisc.
 5815				 */
 5816				clear_bit(__QDISC_STATE_SCHED, &q->state);
 5817				continue;
 5818			}
 5819
 5820			clear_bit(__QDISC_STATE_SCHED, &q->state);
 5821			to_free = qdisc_run(q);
 5822			if (root_lock)
 5823				spin_unlock(root_lock);
 5824			tcf_kfree_skb_list(to_free);
 5825		}
 5826
 5827		rcu_read_unlock();
 5828	}
 5829
 5830	xfrm_dev_backlog(sd);
 5831}
 5832
 5833#if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
 5834/* This hook is defined here for ATM LANE */
 5835int (*br_fdb_test_addr_hook)(struct net_device *dev,
 5836			     unsigned char *addr) __read_mostly;
 5837EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
 5838#endif
 5839
 5840/**
 5841 *	netdev_is_rx_handler_busy - check if receive handler is registered
 5842 *	@dev: device to check
 5843 *
 5844 *	Check if a receive handler is already registered for a given device.
 5845 *	Return true if there one.
 5846 *
 5847 *	The caller must hold the rtnl_mutex.
 5848 */
 5849bool netdev_is_rx_handler_busy(struct net_device *dev)
 5850{
 5851	ASSERT_RTNL();
 5852	return dev && rtnl_dereference(dev->rx_handler);
 5853}
 5854EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
 5855
 5856/**
 5857 *	netdev_rx_handler_register - register receive handler
 5858 *	@dev: device to register a handler for
 5859 *	@rx_handler: receive handler to register
 5860 *	@rx_handler_data: data pointer that is used by rx handler
 5861 *
 5862 *	Register a receive handler for a device. This handler will then be
 5863 *	called from __netif_receive_skb. A negative errno code is returned
 5864 *	on a failure.
 5865 *
 5866 *	The caller must hold the rtnl_mutex.
 5867 *
 5868 *	For a general description of rx_handler, see enum rx_handler_result.
 5869 */
 5870int netdev_rx_handler_register(struct net_device *dev,
 5871			       rx_handler_func_t *rx_handler,
 5872			       void *rx_handler_data)
 5873{
 5874	if (netdev_is_rx_handler_busy(dev))
 5875		return -EBUSY;
 5876
 5877	if (dev->priv_flags & IFF_NO_RX_HANDLER)
 5878		return -EINVAL;
 5879
 5880	/* Note: rx_handler_data must be set before rx_handler */
 5881	rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
 5882	rcu_assign_pointer(dev->rx_handler, rx_handler);
 5883
 5884	return 0;
 5885}
 5886EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
 5887
 5888/**
 5889 *	netdev_rx_handler_unregister - unregister receive handler
 5890 *	@dev: device to unregister a handler from
 5891 *
 5892 *	Unregister a receive handler from a device.
 5893 *
 5894 *	The caller must hold the rtnl_mutex.
 5895 */
 5896void netdev_rx_handler_unregister(struct net_device *dev)
 5897{
 5898
 5899	ASSERT_RTNL();
 5900	RCU_INIT_POINTER(dev->rx_handler, NULL);
 5901	/* a reader seeing a non NULL rx_handler in a rcu_read_lock()
 5902	 * section has a guarantee to see a non NULL rx_handler_data
 5903	 * as well.
 5904	 */
 5905	synchronize_net();
 5906	RCU_INIT_POINTER(dev->rx_handler_data, NULL);
 5907}
 5908EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
 5909
 5910/*
 5911 * Limit the use of PFMEMALLOC reserves to those protocols that implement
 5912 * the special handling of PFMEMALLOC skbs.
 5913 */
 5914static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
 5915{
 5916	switch (skb->protocol) {
 5917	case htons(ETH_P_ARP):
 5918	case htons(ETH_P_IP):
 5919	case htons(ETH_P_IPV6):
 5920	case htons(ETH_P_8021Q):
 5921	case htons(ETH_P_8021AD):
 5922		return true;
 5923	default:
 5924		return false;
 5925	}
 5926}
 5927
 5928static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
 5929			     int *ret, struct net_device *orig_dev)
 5930{
 5931	if (nf_hook_ingress_active(skb)) {
 5932		int ingress_retval;
 5933
 5934		if (unlikely(*pt_prev)) {
 5935			*ret = deliver_skb(skb, *pt_prev, orig_dev);
 5936			*pt_prev = NULL;
 5937		}
 5938
 5939		rcu_read_lock();
 5940		ingress_retval = nf_hook_ingress(skb);
 5941		rcu_read_unlock();
 5942		return ingress_retval;
 5943	}
 5944	return 0;
 5945}
 5946
 5947static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
 5948				    struct packet_type **ppt_prev)
 5949{
 5950	enum skb_drop_reason drop_reason = SKB_DROP_REASON_UNHANDLED_PROTO;
 5951	struct packet_type *ptype, *pt_prev;
 5952	rx_handler_func_t *rx_handler;
 5953	struct sk_buff *skb = *pskb;
 5954	struct net_device *orig_dev;
 5955	bool deliver_exact = false;
 5956	int ret = NET_RX_DROP;
 5957	__be16 type;
 5958
 5959	net_timestamp_check(!READ_ONCE(net_hotdata.tstamp_prequeue), skb);
 5960
 5961	trace_netif_receive_skb(skb);
 5962
 5963	orig_dev = skb->dev;
 5964
 5965	skb_reset_network_header(skb);
 5966#if !defined(CONFIG_DEBUG_NET)
 5967	/* We plan to no longer reset the transport header here.
 5968	 * Give some time to fuzzers and dev build to catch bugs
 5969	 * in network stacks.
 5970	 */
 5971	if (!skb_transport_header_was_set(skb))
 5972		skb_reset_transport_header(skb);
 5973#endif
 5974	skb_reset_mac_len(skb);
 5975
 5976	pt_prev = NULL;
 5977
 5978another_round:
 5979	skb->skb_iif = skb->dev->ifindex;
 5980
 5981	__this_cpu_inc(softnet_data.processed);
 5982
 5983	if (static_branch_unlikely(&generic_xdp_needed_key)) {
 5984		int ret2;
 5985
 5986		migrate_disable();
 5987		ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog),
 5988				      &skb);
 5989		migrate_enable();
 5990
 5991		if (ret2 != XDP_PASS) {
 5992			ret = NET_RX_DROP;
 5993			goto out;
 5994		}
 5995	}
 5996
 5997	if (eth_type_vlan(skb->protocol)) {
 5998		skb = skb_vlan_untag(skb);
 5999		if (unlikely(!skb))
 6000			goto out;
 6001	}
 6002
 6003	if (skb_skip_tc_classify(skb))
 6004		goto skip_classify;
 6005
 6006	if (pfmemalloc)
 6007		goto skip_taps;
 6008
 6009	list_for_each_entry_rcu(ptype, &dev_net_rcu(skb->dev)->ptype_all,
 6010				list) {
 6011		if (unlikely(pt_prev))
 6012			ret = deliver_skb(skb, pt_prev, orig_dev);
 6013		pt_prev = ptype;
 6014	}
 6015
 6016	list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
 6017		if (unlikely(pt_prev))
 6018			ret = deliver_skb(skb, pt_prev, orig_dev);
 6019		pt_prev = ptype;
 6020	}
 6021
 6022skip_taps:
 6023#ifdef CONFIG_NET_INGRESS
 6024	if (static_branch_unlikely(&ingress_needed_key)) {
 6025		bool another = false;
 6026
 6027		nf_skip_egress(skb, true);
 6028		skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
 6029					 &another);
 6030		if (another)
 6031			goto another_round;
 6032		if (!skb)
 6033			goto out;
 6034
 6035		nf_skip_egress(skb, false);
 6036		if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
 6037			goto out;
 6038	}
 6039#endif
 6040	skb_reset_redirect(skb);
 6041skip_classify:
 6042	if (pfmemalloc && !skb_pfmemalloc_protocol(skb)) {
 6043		drop_reason = SKB_DROP_REASON_PFMEMALLOC;
 6044		goto drop;
 6045	}
 6046
 6047	if (skb_vlan_tag_present(skb)) {
 6048		if (unlikely(pt_prev)) {
 6049			ret = deliver_skb(skb, pt_prev, orig_dev);
 6050			pt_prev = NULL;
 6051		}
 6052		if (vlan_do_receive(&skb))
 6053			goto another_round;
 6054		else if (unlikely(!skb))
 6055			goto out;
 6056	}
 6057
 6058	rx_handler = rcu_dereference(skb->dev->rx_handler);
 6059	if (rx_handler) {
 6060		if (unlikely(pt_prev)) {
 6061			ret = deliver_skb(skb, pt_prev, orig_dev);
 6062			pt_prev = NULL;
 6063		}
 6064		switch (rx_handler(&skb)) {
 6065		case RX_HANDLER_CONSUMED:
 6066			ret = NET_RX_SUCCESS;
 6067			goto out;
 6068		case RX_HANDLER_ANOTHER:
 6069			goto another_round;
 6070		case RX_HANDLER_EXACT:
 6071			deliver_exact = true;
 6072			break;
 6073		case RX_HANDLER_PASS:
 6074			break;
 6075		default:
 6076			BUG();
 6077		}
 6078	}
 6079
 6080	if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
 6081check_vlan_id:
 6082		if (skb_vlan_tag_get_id(skb)) {
 6083			/* Vlan id is non 0 and vlan_do_receive() above couldn't
 6084			 * find vlan device.
 6085			 */
 6086			skb->pkt_type = PACKET_OTHERHOST;
 6087		} else if (eth_type_vlan(skb->protocol)) {
 6088			/* Outer header is 802.1P with vlan 0, inner header is
 6089			 * 802.1Q or 802.1AD and vlan_do_receive() above could
 6090			 * not find vlan dev for vlan id 0.
 6091			 */
 6092			__vlan_hwaccel_clear_tag(skb);
 6093			skb = skb_vlan_untag(skb);
 6094			if (unlikely(!skb))
 6095				goto out;
 6096			if (vlan_do_receive(&skb))
 6097				/* After stripping off 802.1P header with vlan 0
 6098				 * vlan dev is found for inner header.
 6099				 */
 6100				goto another_round;
 6101			else if (unlikely(!skb))
 6102				goto out;
 6103			else
 6104				/* We have stripped outer 802.1P vlan 0 header.
 6105				 * But could not find vlan dev.
 6106				 * check again for vlan id to set OTHERHOST.
 6107				 */
 6108				goto check_vlan_id;
 6109		}
 6110		/* Note: we might in the future use prio bits
 6111		 * and set skb->priority like in vlan_do_receive()
 6112		 * For the time being, just ignore Priority Code Point
 6113		 */
 6114		__vlan_hwaccel_clear_tag(skb);
 6115	}
 6116
 6117	type = skb->protocol;
 6118
 6119	/* deliver only exact match when indicated */
 6120	if (likely(!deliver_exact)) {
 6121		deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
 6122				       &ptype_base[ntohs(type) &
 6123						   PTYPE_HASH_MASK]);
 6124
 6125		/* orig_dev and skb->dev could belong to different netns;
 6126		 * Even in such case we need to traverse only the list
 6127		 * coming from skb->dev, as the ptype owner (packet socket)
 6128		 * will use dev_net(skb->dev) to do namespace filtering.
 6129		 */
 6130		deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
 6131				       &dev_net_rcu(skb->dev)->ptype_specific);
 6132	}
 6133
 6134	deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
 6135			       &orig_dev->ptype_specific);
 6136
 6137	if (unlikely(skb->dev != orig_dev)) {
 6138		deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
 6139				       &skb->dev->ptype_specific);
 6140	}
 6141
 6142	if (pt_prev) {
 6143		*ppt_prev = pt_prev;
 6144	} else {
 6145drop:
 6146		if (!deliver_exact)
 6147			dev_core_stats_rx_dropped_inc(skb->dev);
 6148		else
 6149			dev_core_stats_rx_nohandler_inc(skb->dev);
 6150
 6151		kfree_skb_reason(skb, drop_reason);
 6152		/* Jamal, now you will not able to escape explaining
 6153		 * me how you were going to use this. :-)
 6154		 */
 6155		ret = NET_RX_DROP;
 6156	}
 6157
 6158out:
 6159	/* The invariant here is that if *ppt_prev is not NULL
 6160	 * then skb should also be non-NULL.
 6161	 *
 6162	 * Apparently *ppt_prev assignment above holds this invariant due to
 6163	 * skb dereferencing near it.
 6164	 */
 6165	*pskb = skb;
 6166	return ret;
 6167}
 6168
 6169static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
 6170{
 6171	struct net_device *orig_dev = skb->dev;
 6172	struct packet_type *pt_prev = NULL;
 6173	int ret;
 6174
 6175	ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
 6176	if (pt_prev)
 6177		ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
 6178					 skb->dev, pt_prev, orig_dev);
 6179	return ret;
 6180}
 6181
 6182/**
 6183 *	netif_receive_skb_core - special purpose version of netif_receive_skb
 6184 *	@skb: buffer to process
 6185 *
 6186 *	More direct receive version of netif_receive_skb().  It should
 6187 *	only be used by callers that have a need to skip RPS and Generic XDP.
 6188 *	Caller must also take care of handling if ``(page_is_)pfmemalloc``.
 6189 *
 6190 *	This function may only be called from softirq context and interrupts
 6191 *	should be enabled.
 6192 *
 6193 *	Return values (usually ignored):
 6194 *	NET_RX_SUCCESS: no congestion
 6195 *	NET_RX_DROP: packet was dropped
 6196 */
 6197int netif_receive_skb_core(struct sk_buff *skb)
 6198{
 6199	int ret;
 6200
 6201	rcu_read_lock();
 6202	ret = __netif_receive_skb_one_core(skb, false);
 6203	rcu_read_unlock();
 6204
 6205	return ret;
 6206}
 6207EXPORT_SYMBOL(netif_receive_skb_core);
 6208
 6209static inline void __netif_receive_skb_list_ptype(struct list_head *head,
 6210						  struct packet_type *pt_prev,
 6211						  struct net_device *orig_dev)
 6212{
 6213	struct sk_buff *skb, *next;
 6214
 6215	if (!pt_prev)
 6216		return;
 6217	if (list_empty(head))
 6218		return;
 6219	if (pt_prev->list_func != NULL)
 6220		INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
 6221				   ip_list_rcv, head, pt_prev, orig_dev);
 6222	else
 6223		list_for_each_entry_safe(skb, next, head, list) {
 6224			skb_list_del_init(skb);
 6225			pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
 6226		}
 6227}
 6228
 6229static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
 6230{
 6231	/* Fast-path assumptions:
 6232	 * - There is no RX handler.
 6233	 * - Only one packet_type matches.
 6234	 * If either of these fails, we will end up doing some per-packet
 6235	 * processing in-line, then handling the 'last ptype' for the whole
 6236	 * sublist.  This can't cause out-of-order delivery to any single ptype,
 6237	 * because the 'last ptype' must be constant across the sublist, and all
 6238	 * other ptypes are handled per-packet.
 6239	 */
 6240	/* Current (common) ptype of sublist */
 6241	struct packet_type *pt_curr = NULL;
 6242	/* Current (common) orig_dev of sublist */
 6243	struct net_device *od_curr = NULL;
 6244	struct sk_buff *skb, *next;
 6245	LIST_HEAD(sublist);
 6246
 6247	list_for_each_entry_safe(skb, next, head, list) {
 6248		struct net_device *orig_dev = skb->dev;
 6249		struct packet_type *pt_prev = NULL;
 6250
 6251		skb_list_del_init(skb);
 6252		__netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
 6253		if (!pt_prev)
 6254			continue;
 6255		if (pt_curr != pt_prev || od_curr != orig_dev) {
 6256			/* dispatch old sublist */
 6257			__netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
 6258			/* start new sublist */
 6259			INIT_LIST_HEAD(&sublist);
 6260			pt_curr = pt_prev;
 6261			od_curr = orig_dev;
 6262		}
 6263		list_add_tail(&skb->list, &sublist);
 6264	}
 6265
 6266	/* dispatch final sublist */
 6267	__netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
 6268}
 6269
 6270static int __netif_receive_skb(struct sk_buff *skb)
 6271{
 6272	int ret;
 6273
 6274	if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
 6275		unsigned int noreclaim_flag;
 6276
 6277		/*
 6278		 * PFMEMALLOC skbs are special, they should
 6279		 * - be delivered to SOCK_MEMALLOC sockets only
 6280		 * - stay away from userspace
 6281		 * - have bounded memory usage
 6282		 *
 6283		 * Use PF_MEMALLOC as this saves us from propagating the allocation
 6284		 * context down to all allocation sites.
 6285		 */
 6286		noreclaim_flag = memalloc_noreclaim_save();
 6287		ret = __netif_receive_skb_one_core(skb, true);
 6288		memalloc_noreclaim_restore(noreclaim_flag);
 6289	} else
 6290		ret = __netif_receive_skb_one_core(skb, false);
 6291
 6292	return ret;
 6293}
 6294
 6295static void __netif_receive_skb_list(struct list_head *head)
 6296{
 6297	unsigned long noreclaim_flag = 0;
 6298	struct sk_buff *skb, *next;
 6299	bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
 6300
 6301	list_for_each_entry_safe(skb, next, head, list) {
 6302		if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
 6303			struct list_head sublist;
 6304
 6305			/* Handle the previous sublist */
 6306			list_cut_before(&sublist, head, &skb->list);
 6307			if (!list_empty(&sublist))
 6308				__netif_receive_skb_list_core(&sublist, pfmemalloc);
 6309			pfmemalloc = !pfmemalloc;
 6310			/* See comments in __netif_receive_skb */
 6311			if (pfmemalloc)
 6312				noreclaim_flag = memalloc_noreclaim_save();
 6313			else
 6314				memalloc_noreclaim_restore(noreclaim_flag);
 6315		}
 6316	}
 6317	/* Handle the remaining sublist */
 6318	if (!list_empty(head))
 6319		__netif_receive_skb_list_core(head, pfmemalloc);
 6320	/* Restore pflags */
 6321	if (pfmemalloc)
 6322		memalloc_noreclaim_restore(noreclaim_flag);
 6323}
 6324
 6325static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
 6326{
 6327	struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
 6328	struct bpf_prog *new = xdp->prog;
 6329	int ret = 0;
 6330
 6331	switch (xdp->command) {
 6332	case XDP_SETUP_PROG:
 6333		rcu_assign_pointer(dev->xdp_prog, new);
 6334		if (old)
 6335			bpf_prog_put(old);
 6336
 6337		if (old && !new) {
 6338			static_branch_dec(&generic_xdp_needed_key);
 6339		} else if (new && !old) {
 6340			static_branch_inc(&generic_xdp_needed_key);
 6341			netif_disable_lro(dev);
 6342			dev_disable_gro_hw(dev);
 6343		}
 6344		break;
 6345
 6346	default:
 6347		ret = -EINVAL;
 6348		break;
 6349	}
 6350
 6351	return ret;
 6352}
 6353
 6354static int netif_receive_skb_internal(struct sk_buff *skb)
 6355{
 6356	int ret;
 6357
 6358	net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb);
 6359
 6360	if (skb_defer_rx_timestamp(skb))
 6361		return NET_RX_SUCCESS;
 6362
 6363	rcu_read_lock();
 6364#ifdef CONFIG_RPS
 6365	if (static_branch_unlikely(&rps_needed)) {
 6366		struct rps_dev_flow voidflow, *rflow = &voidflow;
 6367		int cpu = get_rps_cpu(skb->dev, skb, &rflow);
 6368
 6369		if (cpu >= 0) {
 6370			ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
 6371			rcu_read_unlock();
 6372			return ret;
 6373		}
 6374	}
 6375#endif
 6376	ret = __netif_receive_skb(skb);
 6377	rcu_read_unlock();
 6378	return ret;
 6379}
 6380
 6381void netif_receive_skb_list_internal(struct list_head *head)
 6382{
 6383	struct sk_buff *skb, *next;
 6384	LIST_HEAD(sublist);
 6385
 6386	list_for_each_entry_safe(skb, next, head, list) {
 6387		net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue),
 6388				    skb);
 6389		skb_list_del_init(skb);
 6390		if (!skb_defer_rx_timestamp(skb))
 6391			list_add_tail(&skb->list, &sublist);
 6392	}
 6393	list_splice_init(&sublist, head);
 6394
 6395	rcu_read_lock();
 6396#ifdef CONFIG_RPS
 6397	if (static_branch_unlikely(&rps_needed)) {
 6398		list_for_each_entry_safe(skb, next, head, list) {
 6399			struct rps_dev_flow voidflow, *rflow = &voidflow;
 6400			int cpu = get_rps_cpu(skb->dev, skb, &rflow);
 6401
 6402			if (cpu >= 0) {
 6403				/* Will be handled, remove from list */
 6404				skb_list_del_init(skb);
 6405				enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
 6406			}
 6407		}
 6408	}
 6409#endif
 6410	__netif_receive_skb_list(head);
 6411	rcu_read_unlock();
 6412}
 6413
 6414/**
 6415 *	netif_receive_skb - process receive buffer from network
 6416 *	@skb: buffer to process
 6417 *
 6418 *	netif_receive_skb() is the main receive data processing function.
 6419 *	It always succeeds. The buffer may be dropped during processing
 6420 *	for congestion control or by the protocol layers.
 6421 *
 6422 *	This function may only be called from softirq context and interrupts
 6423 *	should be enabled.
 6424 *
 6425 *	Return values (usually ignored):
 6426 *	NET_RX_SUCCESS: no congestion
 6427 *	NET_RX_DROP: packet was dropped
 6428 */
 6429int netif_receive_skb(struct sk_buff *skb)
 6430{
 6431	int ret;
 6432
 6433	trace_netif_receive_skb_entry(skb);
 6434
 6435	ret = netif_receive_skb_internal(skb);
 6436	trace_netif_receive_skb_exit(ret);
 6437
 6438	return ret;
 6439}
 6440EXPORT_SYMBOL(netif_receive_skb);
 6441
 6442/**
 6443 *	netif_receive_skb_list - process many receive buffers from network
 6444 *	@head: list of skbs to process.
 6445 *
 6446 *	Since return value of netif_receive_skb() is normally ignored, and
 6447 *	wouldn't be meaningful for a list, this function returns void.
 6448 *
 6449 *	This function may only be called from softirq context and interrupts
 6450 *	should be enabled.
 6451 */
 6452void netif_receive_skb_list(struct list_head *head)
 6453{
 6454	struct sk_buff *skb;
 6455
 6456	if (list_empty(head))
 6457		return;
 6458	if (trace_netif_receive_skb_list_entry_enabled()) {
 6459		list_for_each_entry(skb, head, list)
 6460			trace_netif_receive_skb_list_entry(skb);
 6461	}
 6462	netif_receive_skb_list_internal(head);
 6463	trace_netif_receive_skb_list_exit(0);
 6464}
 6465EXPORT_SYMBOL(netif_receive_skb_list);
 6466
 6467/* Network device is going away, flush any packets still pending */
 6468static void flush_backlog(struct work_struct *work)
 6469{
 6470	struct sk_buff *skb, *tmp;
 6471	struct sk_buff_head list;
 6472	struct softnet_data *sd;
 6473
 6474	__skb_queue_head_init(&list);
 6475	local_bh_disable();
 6476	sd = this_cpu_ptr(&softnet_data);
 6477
 6478	backlog_lock_irq_disable(sd);
 6479	skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
 6480		if (READ_ONCE(skb->dev->reg_state) == NETREG_UNREGISTERING) {
 6481			__skb_unlink(skb, &sd->input_pkt_queue);
 6482			__skb_queue_tail(&list, skb);
 6483			rps_input_queue_head_incr(sd);
 6484		}
 6485	}
 6486	backlog_unlock_irq_enable(sd);
 6487
 6488	local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
 6489	skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
 6490		if (READ_ONCE(skb->dev->reg_state) == NETREG_UNREGISTERING) {
 6491			__skb_unlink(skb, &sd->process_queue);
 6492			__skb_queue_tail(&list, skb);
 6493			rps_input_queue_head_incr(sd);
 6494		}
 6495	}
 6496	local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
 6497	local_bh_enable();
 6498
 6499	__skb_queue_purge_reason(&list, SKB_DROP_REASON_DEV_READY);
 6500}
 6501
 6502static bool flush_required(int cpu)
 6503{
 6504#if IS_ENABLED(CONFIG_RPS)
 6505	struct softnet_data *sd = &per_cpu(softnet_data, cpu);
 6506	bool do_flush;
 6507
 6508	backlog_lock_irq_disable(sd);
 6509
 6510	/* as insertion into process_queue happens with the rps lock held,
 6511	 * process_queue access may race only with dequeue
 6512	 */
 6513	do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
 6514		   !skb_queue_empty_lockless(&sd->process_queue);
 6515	backlog_unlock_irq_enable(sd);
 6516
 6517	return do_flush;
 6518#endif
 6519	/* without RPS we can't safely check input_pkt_queue: during a
 6520	 * concurrent remote skb_queue_splice() we can detect as empty both
 6521	 * input_pkt_queue and process_queue even if the latter could end-up
 6522	 * containing a lot of packets.
 6523	 */
 6524	return true;
 6525}
 6526
 6527struct flush_backlogs {
 6528	cpumask_t		flush_cpus;
 6529	struct work_struct	w[];
 6530};
 6531
 6532static struct flush_backlogs *flush_backlogs_alloc(void)
 6533{
 6534	return kmalloc(struct_size_t(struct flush_backlogs, w, nr_cpu_ids),
 6535		       GFP_KERNEL);
 6536}
 6537
 6538static struct flush_backlogs *flush_backlogs_fallback;
 6539static DEFINE_MUTEX(flush_backlogs_mutex);
 6540
 6541static void flush_all_backlogs(void)
 6542{
 6543	struct flush_backlogs *ptr = flush_backlogs_alloc();
 6544	unsigned int cpu;
 6545
 6546	if (!ptr) {
 6547		mutex_lock(&flush_backlogs_mutex);
 6548		ptr = flush_backlogs_fallback;
 6549	}
 6550	cpumask_clear(&ptr->flush_cpus);
 6551
 6552	cpus_read_lock();
 6553
 6554	for_each_online_cpu(cpu) {
 6555		if (flush_required(cpu)) {
 6556			INIT_WORK(&ptr->w[cpu], flush_backlog);
 6557			queue_work_on(cpu, system_highpri_wq, &ptr->w[cpu]);
 6558			__cpumask_set_cpu(cpu, &ptr->flush_cpus);
 6559		}
 6560	}
 6561
 6562	/* we can have in flight packet[s] on the cpus we are not flushing,
 6563	 * synchronize_net() in unregister_netdevice_many() will take care of
 6564	 * them.
 6565	 */
 6566	for_each_cpu(cpu, &ptr->flush_cpus)
 6567		flush_work(&ptr->w[cpu]);
 6568
 6569	cpus_read_unlock();
 6570
 6571	if (ptr != flush_backlogs_fallback)
 6572		kfree(ptr);
 6573	else
 6574		mutex_unlock(&flush_backlogs_mutex);
 6575}
 6576
 6577static void net_rps_send_ipi(struct softnet_data *remsd)
 6578{
 6579#ifdef CONFIG_RPS
 6580	while (remsd) {
 6581		struct softnet_data *next = remsd->rps_ipi_next;
 6582
 6583		if (cpu_online(remsd->cpu))
 6584			smp_call_function_single_async(remsd->cpu, &remsd->csd);
 6585		remsd = next;
 6586	}
 6587#endif
 6588}
 6589
 6590/*
 6591 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
 6592 * Note: called with local irq disabled, but exits with local irq enabled.
 6593 */
 6594static void net_rps_action_and_irq_enable(struct softnet_data *sd)
 6595{
 6596#ifdef CONFIG_RPS
 6597	struct softnet_data *remsd = sd->rps_ipi_list;
 6598
 6599	if (!use_backlog_threads() && remsd) {
 6600		sd->rps_ipi_list = NULL;
 6601
 6602		local_irq_enable();
 6603
 6604		/* Send pending IPI's to kick RPS processing on remote cpus. */
 6605		net_rps_send_ipi(remsd);
 6606	} else
 6607#endif
 6608		local_irq_enable();
 6609}
 6610
 6611static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
 6612{
 6613#ifdef CONFIG_RPS
 6614	return !use_backlog_threads() && sd->rps_ipi_list;
 6615#else
 6616	return false;
 6617#endif
 6618}
 6619
 6620static int process_backlog(struct napi_struct *napi, int quota)
 6621{
 6622	struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
 6623	bool again = true;
 6624	int work = 0;
 6625
 6626	/* Check if we have pending ipi, its better to send them now,
 6627	 * not waiting net_rx_action() end.
 6628	 */
 6629	if (sd_has_rps_ipi_waiting(sd)) {
 6630		local_irq_disable();
 6631		net_rps_action_and_irq_enable(sd);
 6632	}
 6633
 6634	napi->weight = READ_ONCE(net_hotdata.dev_rx_weight);
 6635	while (again) {
 6636		struct sk_buff *skb;
 6637
 6638		local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
 6639		while ((skb = __skb_dequeue(&sd->process_queue))) {
 6640			local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
 6641			rcu_read_lock();
 6642			__netif_receive_skb(skb);
 6643			rcu_read_unlock();
 6644			if (++work >= quota) {
 6645				rps_input_queue_head_add(sd, work);
 6646				return work;
 6647			}
 6648
 6649			local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
 6650		}
 6651		local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
 6652
 6653		backlog_lock_irq_disable(sd);
 6654		if (skb_queue_empty(&sd->input_pkt_queue)) {
 6655			/*
 6656			 * Inline a custom version of __napi_complete().
 6657			 * only current cpu owns and manipulates this napi,
 6658			 * and NAPI_STATE_SCHED is the only possible flag set
 6659			 * on backlog.
 6660			 * We can use a plain write instead of clear_bit(),
 6661			 * and we dont need an smp_mb() memory barrier.
 6662			 */
 6663			napi->state &= NAPIF_STATE_THREADED;
 6664			again = false;
 6665		} else {
 6666			local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
 6667			skb_queue_splice_tail_init(&sd->input_pkt_queue,
 6668						   &sd->process_queue);
 6669			local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
 6670		}
 6671		backlog_unlock_irq_enable(sd);
 6672	}
 6673
 6674	if (work)
 6675		rps_input_queue_head_add(sd, work);
 6676	return work;
 6677}
 6678
 6679/**
 6680 * __napi_schedule - schedule for receive
 6681 * @n: entry to schedule
 6682 *
 6683 * The entry's receive function will be scheduled to run.
 6684 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
 6685 */
 6686void __napi_schedule(struct napi_struct *n)
 6687{
 6688	unsigned long flags;
 6689
 6690	local_irq_save(flags);
 6691	____napi_schedule(this_cpu_ptr(&softnet_data), n);
 6692	local_irq_restore(flags);
 6693}
 6694EXPORT_SYMBOL(__napi_schedule);
 6695
 6696/**
 6697 *	napi_schedule_prep - check if napi can be scheduled
 6698 *	@n: napi context
 6699 *
 6700 * Test if NAPI routine is already running, and if not mark
 6701 * it as running.  This is used as a condition variable to
 6702 * insure only one NAPI poll instance runs.  We also make
 6703 * sure there is no pending NAPI disable.
 6704 */
 6705bool napi_schedule_prep(struct napi_struct *n)
 6706{
 6707	unsigned long new, val = READ_ONCE(n->state);
 6708
 6709	do {
 6710		if (unlikely(val & NAPIF_STATE_DISABLE))
 6711			return false;
 6712		new = val | NAPIF_STATE_SCHED;
 6713
 6714		/* Sets STATE_MISSED bit if STATE_SCHED was already set
 6715		 * This was suggested by Alexander Duyck, as compiler
 6716		 * emits better code than :
 6717		 * if (val & NAPIF_STATE_SCHED)
 6718		 *     new |= NAPIF_STATE_MISSED;
 6719		 */
 6720		new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
 6721						   NAPIF_STATE_MISSED;
 6722	} while (!try_cmpxchg(&n->state, &val, new));
 6723
 6724	return !(val & NAPIF_STATE_SCHED);
 6725}
 6726EXPORT_SYMBOL(napi_schedule_prep);
 6727
 6728/**
 6729 * __napi_schedule_irqoff - schedule for receive
 6730 * @n: entry to schedule
 6731 *
 6732 * Variant of __napi_schedule() assuming hard irqs are masked.
 6733 *
 6734 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
 6735 * because the interrupt disabled assumption might not be true
 6736 * due to force-threaded interrupts and spinlock substitution.
 6737 */
 6738void __napi_schedule_irqoff(struct napi_struct *n)
 6739{
 6740	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
 6741		____napi_schedule(this_cpu_ptr(&softnet_data), n);
 6742	else
 6743		__napi_schedule(n);
 6744}
 6745EXPORT_SYMBOL(__napi_schedule_irqoff);
 6746
 6747bool napi_complete_done(struct napi_struct *n, int work_done)
 6748{
 6749	unsigned long flags, val, new, timeout = 0;
 6750	bool ret = true;
 6751
 6752	/*
 6753	 * 1) Don't let napi dequeue from the cpu poll list
 6754	 *    just in case its running on a different cpu.
 6755	 * 2) If we are busy polling, do nothing here, we have
 6756	 *    the guarantee we will be called later.
 6757	 */
 6758	if (unlikely(n->state & (NAPIF_STATE_NPSVC |
 6759				 NAPIF_STATE_IN_BUSY_POLL)))
 6760		return false;
 6761
 6762	if (work_done) {
 6763		if (n->gro.bitmask)
 6764			timeout = napi_get_gro_flush_timeout(n);
 6765		n->defer_hard_irqs_count = napi_get_defer_hard_irqs(n);
 6766	}
 6767	if (n->defer_hard_irqs_count > 0) {
 6768		n->defer_hard_irqs_count--;
 6769		timeout = napi_get_gro_flush_timeout(n);
 6770		if (timeout)
 6771			ret = false;
 6772	}
 6773
 6774	/*
 6775	 * When the NAPI instance uses a timeout and keeps postponing
 6776	 * it, we need to bound somehow the time packets are kept in
 6777	 * the GRO layer.
 6778	 */
 6779	gro_flush_normal(&n->gro, !!timeout);
 6780
 6781	if (unlikely(!list_empty(&n->poll_list))) {
 6782		/* If n->poll_list is not empty, we need to mask irqs */
 6783		local_irq_save(flags);
 6784		list_del_init(&n->poll_list);
 6785		local_irq_restore(flags);
 6786	}
 6787	WRITE_ONCE(n->list_owner, -1);
 6788
 6789	val = READ_ONCE(n->state);
 6790	do {
 6791		WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
 6792
 6793		new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
 6794			      NAPIF_STATE_SCHED_THREADED |
 6795			      NAPIF_STATE_PREFER_BUSY_POLL);
 6796
 6797		/* If STATE_MISSED was set, leave STATE_SCHED set,
 6798		 * because we will call napi->poll() one more time.
 6799		 * This C code was suggested by Alexander Duyck to help gcc.
 6800		 */
 6801		new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
 6802						    NAPIF_STATE_SCHED;
 6803	} while (!try_cmpxchg(&n->state, &val, new));
 6804
 6805	if (unlikely(val & NAPIF_STATE_MISSED)) {
 6806		__napi_schedule(n);
 6807		return false;
 6808	}
 6809
 6810	if (timeout)
 6811		hrtimer_start(&n->timer, ns_to_ktime(timeout),
 6812			      HRTIMER_MODE_REL_PINNED);
 6813	return ret;
 6814}
 6815EXPORT_SYMBOL(napi_complete_done);
 6816
 6817static void skb_defer_free_flush(void)
 6818{
 6819	struct llist_node *free_list;
 6820	struct sk_buff *skb, *next;
 6821	struct skb_defer_node *sdn;
 6822	int node;
 6823
 6824	for_each_node(node) {
 6825		sdn = this_cpu_ptr(net_hotdata.skb_defer_nodes) + node;
 6826
 6827		if (llist_empty(&sdn->defer_list))
 6828			continue;
 6829		atomic_long_set(&sdn->defer_count, 0);
 6830		free_list = llist_del_all(&sdn->defer_list);
 6831
 6832		llist_for_each_entry_safe(skb, next, free_list, ll_node) {
 6833			prefetch(next);
 6834			napi_consume_skb(skb, 1);
 6835		}
 6836	}
 6837}
 6838
 6839#if defined(CONFIG_NET_RX_BUSY_POLL)
 6840
 6841static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
 6842{
 6843	if (!skip_schedule) {
 6844		gro_normal_list(&napi->gro);
 6845		__napi_schedule(napi);
 6846		return;
 6847	}
 6848
 6849	/* Flush too old packets. If HZ < 1000, flush all packets */
 6850	gro_flush_normal(&napi->gro, HZ >= 1000);
 6851
 6852	clear_bit(NAPI_STATE_SCHED, &napi->state);
 6853}
 6854
 6855enum {
 6856	NAPI_F_PREFER_BUSY_POLL	= 1,
 6857	NAPI_F_END_ON_RESCHED	= 2,
 6858};
 6859
 6860static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock,
 6861			   unsigned flags, u16 budget)
 6862{
 6863	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
 6864	bool skip_schedule = false;
 6865	unsigned long timeout;
 6866	int rc;
 6867
 6868	/* Busy polling means there is a high chance device driver hard irq
 6869	 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
 6870	 * set in napi_schedule_prep().
 6871	 * Since we are about to call napi->poll() once more, we can safely
 6872	 * clear NAPI_STATE_MISSED.
 6873	 *
 6874	 * Note: x86 could use a single "lock and ..." instruction
 6875	 * to perform these two clear_bit()
 6876	 */
 6877	clear_bit(NAPI_STATE_MISSED, &napi->state);
 6878	clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
 6879
 6880	local_bh_disable();
 6881	bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
 6882
 6883	if (flags & NAPI_F_PREFER_BUSY_POLL) {
 6884		napi->defer_hard_irqs_count = napi_get_defer_hard_irqs(napi);
 6885		timeout = napi_get_gro_flush_timeout(napi);
 6886		if (napi->defer_hard_irqs_count && timeout) {
 6887			hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
 6888			skip_schedule = true;
 6889		}
 6890	}
 6891
 6892	/* All we really want here is to re-enable device interrupts.
 6893	 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
 6894	 */
 6895	rc = napi->poll(napi, budget);
 6896	/* We can't gro_normal_list() here, because napi->poll() might have
 6897	 * rearmed the napi (napi_complete_done()) in which case it could
 6898	 * already be running on another CPU.
 6899	 */
 6900	trace_napi_poll(napi, rc, budget);
 6901	netpoll_poll_unlock(have_poll_lock);
 6902	if (rc == budget)
 6903		__busy_poll_stop(napi, skip_schedule);
 6904	bpf_net_ctx_clear(bpf_net_ctx);
 6905	local_bh_enable();
 6906}
 6907
 6908static void __napi_busy_loop(unsigned int napi_id,
 6909		      bool (*loop_end)(void *, unsigned long),
 6910		      void *loop_end_arg, unsigned flags, u16 budget)
 6911{
 6912	unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
 6913	int (*napi_poll)(struct napi_struct *napi, int budget);
 6914	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
 6915	void *have_poll_lock = NULL;
 6916	struct napi_struct *napi;
 6917
 6918	WARN_ON_ONCE(!rcu_read_lock_held());
 6919
 6920restart:
 6921	napi_poll = NULL;
 6922
 6923	napi = napi_by_id(napi_id);
 6924	if (!napi)
 6925		return;
 6926
 6927	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
 6928		preempt_disable();
 6929	for (;;) {
 6930		int work = 0;
 6931
 6932		local_bh_disable();
 6933		bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
 6934		if (!napi_poll) {
 6935			unsigned long val = READ_ONCE(napi->state);
 6936
 6937			/* If multiple threads are competing for this napi,
 6938			 * we avoid dirtying napi->state as much as we can.
 6939			 */
 6940			if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
 6941				   NAPIF_STATE_IN_BUSY_POLL)) {
 6942				if (flags & NAPI_F_PREFER_BUSY_POLL)
 6943					set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
 6944				goto count;
 6945			}
 6946			if (cmpxchg(&napi->state, val,
 6947				    val | NAPIF_STATE_IN_BUSY_POLL |
 6948					  NAPIF_STATE_SCHED) != val) {
 6949				if (flags & NAPI_F_PREFER_BUSY_POLL)
 6950					set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
 6951				goto count;
 6952			}
 6953			have_poll_lock = netpoll_poll_lock(napi);
 6954			napi_poll = napi->poll;
 6955		}
 6956		work = napi_poll(napi, budget);
 6957		trace_napi_poll(napi, work, budget);
 6958		gro_normal_list(&napi->gro);
 6959count:
 6960		if (work > 0)
 6961			__NET_ADD_STATS(dev_net(napi->dev),
 6962					LINUX_MIB_BUSYPOLLRXPACKETS, work);
 6963		skb_defer_free_flush();
 6964		bpf_net_ctx_clear(bpf_net_ctx);
 6965		local_bh_enable();
 6966
 6967		if (!loop_end || loop_end(loop_end_arg, start_time))
 6968			break;
 6969
 6970		if (unlikely(need_resched())) {
 6971			if (flags & NAPI_F_END_ON_RESCHED)
 6972				break;
 6973			if (napi_poll)
 6974				busy_poll_stop(napi, have_poll_lock, flags, budget);
 6975			if (!IS_ENABLED(CONFIG_PREEMPT_RT))
 6976				preempt_enable();
 6977			rcu_read_unlock();
 6978			cond_resched();
 6979			rcu_read_lock();
 6980			if (loop_end(loop_end_arg, start_time))
 6981				return;
 6982			goto restart;
 6983		}
 6984		cpu_relax();
 6985	}
 6986	if (napi_poll)
 6987		busy_poll_stop(napi, have_poll_lock, flags, budget);
 6988	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
 6989		preempt_enable();
 6990}
 6991
 6992void napi_busy_loop_rcu(unsigned int napi_id,
 6993			bool (*loop_end)(void *, unsigned long),
 6994			void *loop_end_arg, bool prefer_busy_poll, u16 budget)
 6995{
 6996	unsigned flags = NAPI_F_END_ON_RESCHED;
 6997
 6998	if (prefer_busy_poll)
 6999		flags |= NAPI_F_PREFER_BUSY_POLL;
 7000
 7001	__napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget);
 7002}
 7003
 7004void napi_busy_loop(unsigned int napi_id,
 7005		    bool (*loop_end)(void *, unsigned long),
 7006		    void *loop_end_arg, bool prefer_busy_poll, u16 budget)
 7007{
 7008	unsigned flags = prefer_busy_poll ? NAPI_F_PREFER_BUSY_POLL : 0;
 7009
 7010	rcu_read_lock();
 7011	__napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget);
 7012	rcu_read_unlock();
 7013}
 7014EXPORT_SYMBOL(napi_busy_loop);
 7015
 7016void napi_suspend_irqs(unsigned int napi_id)
 7017{
 7018	struct napi_struct *napi;
 7019
 7020	rcu_read_lock();
 7021	napi = napi_by_id(napi_id);
 7022	if (napi) {
 7023		unsigned long timeout = napi_get_irq_suspend_timeout(napi);
 7024
 7025		if (timeout)
 7026			hrtimer_start(&napi->timer, ns_to_ktime(timeout),
 7027				      HRTIMER_MODE_REL_PINNED);
 7028	}
 7029	rcu_read_unlock();
 7030}
 7031
 7032void napi_resume_irqs(unsigned int napi_id)
 7033{
 7034	struct napi_struct *napi;
 7035
 7036	rcu_read_lock();
 7037	napi = napi_by_id(napi_id);
 7038	if (napi) {
 7039		/* If irq_suspend_timeout is set to 0 between the call to
 7040		 * napi_suspend_irqs and now, the original value still
 7041		 * determines the safety timeout as intended and napi_watchdog
 7042		 * will resume irq processing.
 7043		 */
 7044		if (napi_get_irq_suspend_timeout(napi)) {
 7045			local_bh_disable();
 7046			napi_schedule(napi);
 7047			local_bh_enable();
 7048		}
 7049	}
 7050	rcu_read_unlock();
 7051}
 7052
 7053#endif /* CONFIG_NET_RX_BUSY_POLL */
 7054
 7055static void __napi_hash_add_with_id(struct napi_struct *napi,
 7056				    unsigned int napi_id)
 7057{
 7058	napi->gro.cached_napi_id = napi_id;
 7059
 7060	WRITE_ONCE(napi->napi_id, napi_id);
 7061	hlist_add_head_rcu(&napi->napi_hash_node,
 7062			   &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
 7063}
 7064
 7065static void napi_hash_add_with_id(struct napi_struct *napi,
 7066				  unsigned int napi_id)
 7067{
 7068	unsigned long flags;
 7069
 7070	spin_lock_irqsave(&napi_hash_lock, flags);
 7071	WARN_ON_ONCE(napi_by_id(napi_id));
 7072	__napi_hash_add_with_id(napi, napi_id);
 7073	spin_unlock_irqrestore(&napi_hash_lock, flags);
 7074}
 7075
 7076static void napi_hash_add(struct napi_struct *napi)
 7077{
 7078	unsigned long flags;
 7079
 7080	if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
 7081		return;
 7082
 7083	spin_lock_irqsave(&napi_hash_lock, flags);
 7084
 7085	/* 0..NR_CPUS range is reserved for sender_cpu use */
 7086	do {
 7087		if (unlikely(!napi_id_valid(++napi_gen_id)))
 7088			napi_gen_id = MIN_NAPI_ID;
 7089	} while (napi_by_id(napi_gen_id));
 7090
 7091	__napi_hash_add_with_id(napi, napi_gen_id);
 7092
 7093	spin_unlock_irqrestore(&napi_hash_lock, flags);
 7094}
 7095
 7096/* Warning : caller is responsible to make sure rcu grace period
 7097 * is respected before freeing memory containing @napi
 7098 */
 7099static void napi_hash_del(struct napi_struct *napi)
 7100{
 7101	unsigned long flags;
 7102
 7103	spin_lock_irqsave(&napi_hash_lock, flags);
 7104
 7105	hlist_del_init_rcu(&napi->napi_hash_node);
 7106
 7107	spin_unlock_irqrestore(&napi_hash_lock, flags);
 7108}
 7109
 7110static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
 7111{
 7112	struct napi_struct *napi;
 7113
 7114	napi = container_of(timer, struct napi_struct, timer);
 7115
 7116	/* Note : we use a relaxed variant of napi_schedule_prep() not setting
 7117	 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
 7118	 */
 7119	if (!napi_disable_pending(napi) &&
 7120	    !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
 7121		clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
 7122		__napi_schedule_irqoff(napi);
 7123	}
 7124
 7125	return HRTIMER_NORESTART;
 7126}
 7127
 7128static void napi_stop_kthread(struct napi_struct *napi)
 7129{
 7130	unsigned long val, new;
 7131
 7132	/* Wait until the napi STATE_THREADED is unset. */
 7133	while (true) {
 7134		val = READ_ONCE(napi->state);
 7135
 7136		/* If napi kthread own this napi or the napi is idle,
 7137		 * STATE_THREADED can be unset here.
 7138		 */
 7139		if ((val & NAPIF_STATE_SCHED_THREADED) ||
 7140		    !(val & NAPIF_STATE_SCHED)) {
 7141			new = val & (~(NAPIF_STATE_THREADED |
 7142				       NAPIF_STATE_THREADED_BUSY_POLL));
 7143		} else {
 7144			msleep(20);
 7145			continue;
 7146		}
 7147
 7148		if (try_cmpxchg(&napi->state, &val, new))
 7149			break;
 7150	}
 7151
 7152	/* Once STATE_THREADED is unset, wait for SCHED_THREADED to be unset by
 7153	 * the kthread.
 7154	 */
 7155	while (true) {
 7156		if (!test_bit(NAPI_STATE_SCHED_THREADED, &napi->state))
 7157			break;
 7158
 7159		msleep(20);
 7160	}
 7161
 7162	kthread_stop(napi->thread);
 7163	napi->thread = NULL;
 7164}
 7165
 7166static void napi_set_threaded_state(struct napi_struct *napi,
 7167				    enum netdev_napi_threaded threaded_mode)
 7168{
 7169	bool threaded = threaded_mode != NETDEV_NAPI_THREADED_DISABLED;
 7170	bool busy_poll = threaded_mode == NETDEV_NAPI_THREADED_BUSY_POLL;
 7171
 7172	assign_bit(NAPI_STATE_THREADED, &napi->state, threaded);
 7173	assign_bit(NAPI_STATE_THREADED_BUSY_POLL, &napi->state, busy_poll);
 7174}
 7175
 7176int napi_set_threaded(struct napi_struct *napi,
 7177		      enum netdev_napi_threaded threaded)
 7178{
 7179	if (threaded) {
 7180		if (!napi->thread) {
 7181			int err = napi_kthread_create(napi);
 7182
 7183			if (err)
 7184				return err;
 7185		}
 7186	}
 7187
 7188	if (napi->config)
 7189		napi->config->threaded = threaded;
 7190
 7191	/* Setting/unsetting threaded mode on a napi might not immediately
 7192	 * take effect, if the current napi instance is actively being
 7193	 * polled. In this case, the switch between threaded mode and
 7194	 * softirq mode will happen in the next round of napi_schedule().
 7195	 * This should not cause hiccups/stalls to the live traffic.
 7196	 */
 7197	if (!threaded && napi->thread) {
 7198		napi_stop_kthread(napi);
 7199	} else {
 7200		/* Make sure kthread is created before THREADED bit is set. */
 7201		smp_mb__before_atomic();
 7202		napi_set_threaded_state(napi, threaded);
 7203	}
 7204
 7205	return 0;
 7206}
 7207
 7208int netif_set_threaded(struct net_device *dev,
 7209		       enum netdev_napi_threaded threaded)
 7210{
 7211	struct napi_struct *napi;
 7212	int i, err = 0;
 7213
 7214	netdev_assert_locked_or_invisible(dev);
 7215
 7216	if (threaded) {
 7217		list_for_each_entry(napi, &dev->napi_list, dev_list) {
 7218			if (!napi->thread) {
 7219				err = napi_kthread_create(napi);
 7220				if (err) {
 7221					threaded = NETDEV_NAPI_THREADED_DISABLED;
 7222					break;
 7223				}
 7224			}
 7225		}
 7226	}
 7227
 7228	WRITE_ONCE(dev->threaded, threaded);
 7229
 7230	/* The error should not occur as the kthreads are already created. */
 7231	list_for_each_entry(napi, &dev->napi_list, dev_list)
 7232		WARN_ON_ONCE(napi_set_threaded(napi, threaded));
 7233
 7234	/* Override the config for all NAPIs even if currently not listed */
 7235	for (i = 0; i < dev->num_napi_configs; i++)
 7236		dev->napi_config[i].threaded = threaded;
 7237
 7238	return err;
 7239}
 7240
 7241/**
 7242 * netif_threaded_enable() - enable threaded NAPIs
 7243 * @dev: net_device instance
 7244 *
 7245 * Enable threaded mode for the NAPI instances of the device. This may be useful
 7246 * for devices where multiple NAPI instances get scheduled by a single
 7247 * interrupt. Threaded NAPI allows moving the NAPI processing to cores other
 7248 * than the core where IRQ is mapped.
 7249 *
 7250 * This function should be called before @dev is registered.
 7251 */
 7252void netif_threaded_enable(struct net_device *dev)
 7253{
 7254	WARN_ON_ONCE(netif_set_threaded(dev, NETDEV_NAPI_THREADED_ENABLED));
 7255}
 7256EXPORT_SYMBOL(netif_threaded_enable);
 7257
 7258/**
 7259 * netif_queue_set_napi - Associate queue with the napi
 7260 * @dev: device to which NAPI and queue belong
 7261 * @queue_index: Index of queue
 7262 * @type: queue type as RX or TX
 7263 * @napi: NAPI context, pass NULL to clear previously set NAPI
 7264 *
 7265 * Set queue with its corresponding napi context. This should be done after
 7266 * registering the NAPI handler for the queue-vector and the queues have been
 7267 * mapped to the corresponding interrupt vector.
 7268 */
 7269void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index,
 7270			  enum netdev_queue_type type, struct napi_struct *napi)
 7271{
 7272	struct netdev_rx_queue *rxq;
 7273	struct netdev_queue *txq;
 7274
 7275	if (WARN_ON_ONCE(napi && !napi->dev))
 7276		return;
 7277	netdev_ops_assert_locked_or_invisible(dev);
 7278
 7279	switch (type) {
 7280	case NETDEV_QUEUE_TYPE_RX:
 7281		rxq = __netif_get_rx_queue(dev, queue_index);
 7282		rxq->napi = napi;
 7283		return;
 7284	case NETDEV_QUEUE_TYPE_TX:
 7285		txq = netdev_get_tx_queue(dev, queue_index);
 7286		txq->napi = napi;
 7287		return;
 7288	default:
 7289		return;
 7290	}
 7291}
 7292EXPORT_SYMBOL(netif_queue_set_napi);
 7293
 7294static void
 7295netif_napi_irq_notify(struct irq_affinity_notify *notify,
 7296		      const cpumask_t *mask)
 7297{
 7298	struct napi_struct *napi =
 7299		container_of(notify, struct napi_struct, notify);
 7300#ifdef CONFIG_RFS_ACCEL
 7301	struct cpu_rmap *rmap = napi->dev->rx_cpu_rmap;
 7302	int err;
 7303#endif
 7304
 7305	if (napi->config && napi->dev->irq_affinity_auto)
 7306		cpumask_copy(&napi->config->affinity_mask, mask);
 7307
 7308#ifdef CONFIG_RFS_ACCEL
 7309	if (napi->dev->rx_cpu_rmap_auto) {
 7310		err = cpu_rmap_update(rmap, napi->napi_rmap_idx, mask);
 7311		if (err)
 7312			netdev_warn(napi->dev, "RMAP update failed (%d)\n",
 7313				    err);
 7314	}
 7315#endif
 7316}
 7317
 7318#ifdef CONFIG_RFS_ACCEL
 7319static void netif_napi_affinity_release(struct kref *ref)
 7320{
 7321	struct napi_struct *napi =
 7322		container_of(ref, struct napi_struct, notify.kref);
 7323	struct cpu_rmap *rmap = napi->dev->rx_cpu_rmap;
 7324
 7325	netdev_assert_locked(napi->dev);
 7326	WARN_ON(test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER,
 7327				   &napi->state));
 7328
 7329	if (!napi->dev->rx_cpu_rmap_auto)
 7330		return;
 7331	rmap->obj[napi->napi_rmap_idx] = NULL;
 7332	napi->napi_rmap_idx = -1;
 7333	cpu_rmap_put(rmap);
 7334}
 7335
 7336int netif_enable_cpu_rmap(struct net_device *dev, unsigned int num_irqs)
 7337{
 7338	if (dev->rx_cpu_rmap_auto)
 7339		return 0;
 7340
 7341	dev->rx_cpu_rmap = alloc_irq_cpu_rmap(num_irqs);
 7342	if (!dev->rx_cpu_rmap)
 7343		return -ENOMEM;
 7344
 7345	dev->rx_cpu_rmap_auto = true;
 7346	return 0;
 7347}
 7348EXPORT_SYMBOL(netif_enable_cpu_rmap);
 7349
 7350static void netif_del_cpu_rmap(struct net_device *dev)
 7351{
 7352	struct cpu_rmap *rmap = dev->rx_cpu_rmap;
 7353
 7354	if (!dev->rx_cpu_rmap_auto)
 7355		return;
 7356
 7357	/* Free the rmap */
 7358	cpu_rmap_put(rmap);
 7359	dev->rx_cpu_rmap = NULL;
 7360	dev->rx_cpu_rmap_auto = false;
 7361}
 7362
 7363#else
 7364static void netif_napi_affinity_release(struct kref *ref)
 7365{
 7366}
 7367
 7368int netif_enable_cpu_rmap(struct net_device *dev, unsigned int num_irqs)
 7369{
 7370	return 0;
 7371}
 7372EXPORT_SYMBOL(netif_enable_cpu_rmap);
 7373
 7374static void netif_del_cpu_rmap(struct net_device *dev)
 7375{
 7376}
 7377#endif
 7378
 7379void netif_set_affinity_auto(struct net_device *dev)
 7380{
 7381	unsigned int i, maxqs, numa;
 7382
 7383	maxqs = max(dev->num_tx_queues, dev->num_rx_queues);
 7384	numa = dev_to_node(&dev->dev);
 7385
 7386	for (i = 0; i < maxqs; i++)
 7387		cpumask_set_cpu(cpumask_local_spread(i, numa),
 7388				&dev->napi_config[i].affinity_mask);
 7389
 7390	dev->irq_affinity_auto = true;
 7391}
 7392EXPORT_SYMBOL(netif_set_affinity_auto);
 7393
 7394void netif_napi_set_irq_locked(struct napi_struct *napi, int irq)
 7395{
 7396	int rc;
 7397
 7398	netdev_assert_locked_or_invisible(napi->dev);
 7399
 7400	if (napi->irq == irq)
 7401		return;
 7402
 7403	/* Remove existing resources */
 7404	if (test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state))
 7405		irq_set_affinity_notifier(napi->irq, NULL);
 7406
 7407	napi->irq = irq;
 7408	if (irq < 0 ||
 7409	    (!napi->dev->rx_cpu_rmap_auto && !napi->dev->irq_affinity_auto))
 7410		return;
 7411
 7412	/* Abort for buggy drivers */
 7413	if (napi->dev->irq_affinity_auto && WARN_ON_ONCE(!napi->config))
 7414		return;
 7415
 7416#ifdef CONFIG_RFS_ACCEL
 7417	if (napi->dev->rx_cpu_rmap_auto) {
 7418		rc = cpu_rmap_add(napi->dev->rx_cpu_rmap, napi);
 7419		if (rc < 0)
 7420			return;
 7421
 7422		cpu_rmap_get(napi->dev->rx_cpu_rmap);
 7423		napi->napi_rmap_idx = rc;
 7424	}
 7425#endif
 7426
 7427	/* Use core IRQ notifier */
 7428	napi->notify.notify = netif_napi_irq_notify;
 7429	napi->notify.release = netif_napi_affinity_release;
 7430	rc = irq_set_affinity_notifier(irq, &napi->notify);
 7431	if (rc) {
 7432		netdev_warn(napi->dev, "Unable to set IRQ notifier (%d)\n",
 7433			    rc);
 7434		goto put_rmap;
 7435	}
 7436
 7437	set_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state);
 7438	return;
 7439
 7440put_rmap:
 7441#ifdef CONFIG_RFS_ACCEL
 7442	if (napi->dev->rx_cpu_rmap_auto) {
 7443		napi->dev->rx_cpu_rmap->obj[napi->napi_rmap_idx] = NULL;
 7444		cpu_rmap_put(napi->dev->rx_cpu_rmap);
 7445		napi->napi_rmap_idx = -1;
 7446	}
 7447#endif
 7448	napi->notify.notify = NULL;
 7449	napi->notify.release = NULL;
 7450}
 7451EXPORT_SYMBOL(netif_napi_set_irq_locked);
 7452
 7453static void napi_restore_config(struct napi_struct *n)
 7454{
 7455	n->defer_hard_irqs = n->config->defer_hard_irqs;
 7456	n->gro_flush_timeout = n->config->gro_flush_timeout;
 7457	n->irq_suspend_timeout = n->config->irq_suspend_timeout;
 7458
 7459	if (n->dev->irq_affinity_auto &&
 7460	    test_bit(NAPI_STATE_HAS_NOTIFIER, &n->state))
 7461		irq_set_affinity(n->irq, &n->config->affinity_mask);
 7462
 7463	/* a NAPI ID might be stored in the config, if so use it. if not, use
 7464	 * napi_hash_add to generate one for us.
 7465	 */
 7466	if (n->config->napi_id) {
 7467		napi_hash_add_with_id(n, n->config->napi_id);
 7468	} else {
 7469		napi_hash_add(n);
 7470		n->config->napi_id = n->napi_id;
 7471	}
 7472
 7473	WARN_ON_ONCE(napi_set_threaded(n, n->config->threaded));
 7474}
 7475
 7476static void napi_save_config(struct napi_struct *n)
 7477{
 7478	n->config->defer_hard_irqs = n->defer_hard_irqs;
 7479	n->config->gro_flush_timeout = n->gro_flush_timeout;
 7480	n->config->irq_suspend_timeout = n->irq_suspend_timeout;
 7481	napi_hash_del(n);
 7482}
 7483
 7484/* Netlink wants the NAPI list to be sorted by ID, if adding a NAPI which will
 7485 * inherit an existing ID try to insert it at the right position.
 7486 */
 7487static void
 7488netif_napi_dev_list_add(struct net_device *dev, struct napi_struct *napi)
 7489{
 7490	unsigned int new_id, pos_id;
 7491	struct list_head *higher;
 7492	struct napi_struct *pos;
 7493
 7494	new_id = UINT_MAX;
 7495	if (napi->config && napi->config->napi_id)
 7496		new_id = napi->config->napi_id;
 7497
 7498	higher = &dev->napi_list;
 7499	list_for_each_entry(pos, &dev->napi_list, dev_list) {
 7500		if (napi_id_valid(pos->napi_id))
 7501			pos_id = pos->napi_id;
 7502		else if (pos->config)
 7503			pos_id = pos->config->napi_id;
 7504		else
 7505			pos_id = UINT_MAX;
 7506
 7507		if (pos_id <= new_id)
 7508			break;
 7509		higher = &pos->dev_list;
 7510	}
 7511	list_add_rcu(&napi->dev_list, higher); /* adds after higher */
 7512}
 7513
 7514/* Double check that napi_get_frags() allocates skbs with
 7515 * skb->head being backed by slab, not a page fragment.
 7516 * This is to make sure bug fixed in 3226b158e67c
 7517 * ("net: avoid 32 x truesize under-estimation for tiny skbs")
 7518 * does not accidentally come back.
 7519 */
 7520static void napi_get_frags_check(struct napi_struct *napi)
 7521{
 7522	struct sk_buff *skb;
 7523
 7524	local_bh_disable();
 7525	skb = napi_get_frags(napi);
 7526	WARN_ON_ONCE(skb && skb->head_frag);
 7527	napi_free_frags(napi);
 7528	local_bh_enable();
 7529}
 7530
 7531void netif_napi_add_weight_locked(struct net_device *dev,
 7532				  struct napi_struct *napi,
 7533				  int (*poll)(struct napi_struct *, int),
 7534				  int weight)
 7535{
 7536	netdev_assert_locked(dev);
 7537	if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
 7538		return;
 7539
 7540	INIT_LIST_HEAD(&napi->poll_list);
 7541	INIT_HLIST_NODE(&napi->napi_hash_node);
 7542	hrtimer_setup(&napi->timer, napi_watchdog, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
 7543	gro_init(&napi->gro);
 7544	napi->skb = NULL;
 7545	napi->poll = poll;
 7546	if (weight > NAPI_POLL_WEIGHT)
 7547		netdev_err_once(dev, "%s() called with weight %d\n", __func__,
 7548				weight);
 7549	napi->weight = weight;
 7550	napi->dev = dev;
 7551#ifdef CONFIG_NETPOLL
 7552	napi->poll_owner = -1;
 7553#endif
 7554	napi->list_owner = -1;
 7555	set_bit(NAPI_STATE_SCHED, &napi->state);
 7556	set_bit(NAPI_STATE_NPSVC, &napi->state);
 7557	netif_napi_dev_list_add(dev, napi);
 7558
 7559	/* default settings from sysfs are applied to all NAPIs. any per-NAPI
 7560	 * configuration will be loaded in napi_enable
 7561	 */
 7562	napi_set_defer_hard_irqs(napi, READ_ONCE(dev->napi_defer_hard_irqs));
 7563	napi_set_gro_flush_timeout(napi, READ_ONCE(dev->gro_flush_timeout));
 7564
 7565	napi_get_frags_check(napi);
 7566	/* Create kthread for this napi if dev->threaded is set.
 7567	 * Clear dev->threaded if kthread creation failed so that
 7568	 * threaded mode will not be enabled in napi_enable().
 7569	 */
 7570	if (napi_get_threaded_config(dev, napi))
 7571		if (napi_kthread_create(napi))
 7572			dev->threaded = NETDEV_NAPI_THREADED_DISABLED;
 7573	netif_napi_set_irq_locked(napi, -1);
 7574}
 7575EXPORT_SYMBOL(netif_napi_add_weight_locked);
 7576
 7577void napi_disable_locked(struct napi_struct *n)
 7578{
 7579	unsigned long val, new;
 7580
 7581	might_sleep();
 7582	netdev_assert_locked(n->dev);
 7583
 7584	set_bit(NAPI_STATE_DISABLE, &n->state);
 7585
 7586	val = READ_ONCE(n->state);
 7587	do {
 7588		while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
 7589			usleep_range(20, 200);
 7590			val = READ_ONCE(n->state);
 7591		}
 7592
 7593		new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
 7594		new &= ~(NAPIF_STATE_THREADED |
 7595			 NAPIF_STATE_THREADED_BUSY_POLL |
 7596			 NAPIF_STATE_PREFER_BUSY_POLL);
 7597	} while (!try_cmpxchg(&n->state, &val, new));
 7598
 7599	hrtimer_cancel(&n->timer);
 7600
 7601	if (n->config)
 7602		napi_save_config(n);
 7603	else
 7604		napi_hash_del(n);
 7605
 7606	clear_bit(NAPI_STATE_DISABLE, &n->state);
 7607}
 7608EXPORT_SYMBOL(napi_disable_locked);
 7609
 7610/**
 7611 * napi_disable() - prevent NAPI from scheduling
 7612 * @n: NAPI context
 7613 *
 7614 * Stop NAPI from being scheduled on this context.
 7615 * Waits till any outstanding processing completes.
 7616 * Takes netdev_lock() for associated net_device.
 7617 */
 7618void napi_disable(struct napi_struct *n)
 7619{
 7620	netdev_lock(n->dev);
 7621	napi_disable_locked(n);
 7622	netdev_unlock(n->dev);
 7623}
 7624EXPORT_SYMBOL(napi_disable);
 7625
 7626void napi_enable_locked(struct napi_struct *n)
 7627{
 7628	unsigned long new, val = READ_ONCE(n->state);
 7629
 7630	if (n->config)
 7631		napi_restore_config(n);
 7632	else
 7633		napi_hash_add(n);
 7634
 7635	do {
 7636		BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
 7637
 7638		new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
 7639		if (n->dev->threaded && n->thread)
 7640			new |= NAPIF_STATE_THREADED;
 7641	} while (!try_cmpxchg(&n->state, &val, new));
 7642}
 7643EXPORT_SYMBOL(napi_enable_locked);
 7644
 7645/**
 7646 * napi_enable() - enable NAPI scheduling
 7647 * @n: NAPI context
 7648 *
 7649 * Enable scheduling of a NAPI instance.
 7650 * Must be paired with napi_disable().
 7651 * Takes netdev_lock() for associated net_device.
 7652 */
 7653void napi_enable(struct napi_struct *n)
 7654{
 7655	netdev_lock(n->dev);
 7656	napi_enable_locked(n);
 7657	netdev_unlock(n->dev);
 7658}
 7659EXPORT_SYMBOL(napi_enable);
 7660
 7661/* Must be called in process context */
 7662void __netif_napi_del_locked(struct napi_struct *napi)
 7663{
 7664	netdev_assert_locked(napi->dev);
 7665
 7666	if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
 7667		return;
 7668
 7669	/* Make sure NAPI is disabled (or was never enabled). */
 7670	WARN_ON(!test_bit(NAPI_STATE_SCHED, &napi->state));
 7671
 7672	if (test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state))
 7673		irq_set_affinity_notifier(napi->irq, NULL);
 7674
 7675	if (napi->config) {
 7676		napi->index = -1;
 7677		napi->config = NULL;
 7678	}
 7679
 7680	list_del_rcu(&napi->dev_list);
 7681	napi_free_frags(napi);
 7682
 7683	gro_cleanup(&napi->gro);
 7684
 7685	if (napi->thread) {
 7686		kthread_stop(napi->thread);
 7687		napi->thread = NULL;
 7688	}
 7689}
 7690EXPORT_SYMBOL(__netif_napi_del_locked);
 7691
 7692static int __napi_poll(struct napi_struct *n, bool *repoll)
 7693{
 7694	int work, weight;
 7695
 7696	weight = n->weight;
 7697
 7698	/* This NAPI_STATE_SCHED test is for avoiding a race
 7699	 * with netpoll's poll_napi().  Only the entity which
 7700	 * obtains the lock and sees NAPI_STATE_SCHED set will
 7701	 * actually make the ->poll() call.  Therefore we avoid
 7702	 * accidentally calling ->poll() when NAPI is not scheduled.
 7703	 */
 7704	work = 0;
 7705	if (napi_is_scheduled(n)) {
 7706		work = n->poll(n, weight);
 7707		trace_napi_poll(n, work, weight);
 7708
 7709		xdp_do_check_flushed(n);
 7710	}
 7711
 7712	if (unlikely(work > weight))
 7713		netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
 7714				n->poll, work, weight);
 7715
 7716	if (likely(work < weight))
 7717		return work;
 7718
 7719	/* Drivers must not modify the NAPI state if they
 7720	 * consume the entire weight.  In such cases this code
 7721	 * still "owns" the NAPI instance and therefore can
 7722	 * move the instance around on the list at-will.
 7723	 */
 7724	if (unlikely(napi_disable_pending(n))) {
 7725		napi_complete(n);
 7726		return work;
 7727	}
 7728
 7729	/* The NAPI context has more processing work, but busy-polling
 7730	 * is preferred. Exit early.
 7731	 */
 7732	if (napi_prefer_busy_poll(n)) {
 7733		if (napi_complete_done(n, work)) {
 7734			/* If timeout is not set, we need to make sure
 7735			 * that the NAPI is re-scheduled.
 7736			 */
 7737			napi_schedule(n);
 7738		}
 7739		return work;
 7740	}
 7741
 7742	/* Flush too old packets. If HZ < 1000, flush all packets */
 7743	gro_flush_normal(&n->gro, HZ >= 1000);
 7744
 7745	/* Some drivers may have called napi_schedule
 7746	 * prior to exhausting their budget.
 7747	 */
 7748	if (unlikely(!list_empty(&n->poll_list))) {
 7749		pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
 7750			     n->dev ? n->dev->name : "backlog");
 7751		return work;
 7752	}
 7753
 7754	*repoll = true;
 7755
 7756	return work;
 7757}
 7758
 7759static int napi_poll(struct napi_struct *n, struct list_head *repoll)
 7760{
 7761	bool do_repoll = false;
 7762	void *have;
 7763	int work;
 7764
 7765	list_del_init(&n->poll_list);
 7766
 7767	have = netpoll_poll_lock(n);
 7768
 7769	work = __napi_poll(n, &do_repoll);
 7770
 7771	if (do_repoll) {
 7772#if defined(CONFIG_DEBUG_NET)
 7773		if (unlikely(!napi_is_scheduled(n)))
 7774			pr_crit("repoll requested for device %s %ps but napi is not scheduled.\n",
 7775				n->dev->name, n->poll);
 7776#endif
 7777		list_add_tail(&n->poll_list, repoll);
 7778	}
 7779	netpoll_poll_unlock(have);
 7780
 7781	return work;
 7782}
 7783
 7784static int napi_thread_wait(struct napi_struct *napi)
 7785{
 7786	set_current_state(TASK_INTERRUPTIBLE);
 7787
 7788	while (!kthread_should_stop()) {
 7789		/* Testing SCHED_THREADED bit here to make sure the current
 7790		 * kthread owns this napi and could poll on this napi.
 7791		 * Testing SCHED bit is not enough because SCHED bit might be
 7792		 * set by some other busy poll thread or by napi_disable().
 7793		 */
 7794		if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) {
 7795			WARN_ON(!list_empty(&napi->poll_list));
 7796			__set_current_state(TASK_RUNNING);
 7797			return 0;
 7798		}
 7799
 7800		schedule();
 7801		set_current_state(TASK_INTERRUPTIBLE);
 7802	}
 7803	__set_current_state(TASK_RUNNING);
 7804
 7805	return -1;
 7806}
 7807
 7808static void napi_threaded_poll_loop(struct napi_struct *napi,
 7809				    unsigned long *busy_poll_last_qs)
 7810{
 7811	unsigned long last_qs = busy_poll_last_qs ? *busy_poll_last_qs : jiffies;
 7812	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
 7813	struct softnet_data *sd;
 7814
 7815	for (;;) {
 7816		bool repoll = false;
 7817		void *have;
 7818
 7819		local_bh_disable();
 7820		bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
 7821
 7822		sd = this_cpu_ptr(&softnet_data);
 7823		sd->in_napi_threaded_poll = true;
 7824
 7825		have = netpoll_poll_lock(napi);
 7826		__napi_poll(napi, &repoll);
 7827		netpoll_poll_unlock(have);
 7828
 7829		sd->in_napi_threaded_poll = false;
 7830		barrier();
 7831
 7832		if (sd_has_rps_ipi_waiting(sd)) {
 7833			local_irq_disable();
 7834			net_rps_action_and_irq_enable(sd);
 7835		}
 7836		skb_defer_free_flush();
 7837		bpf_net_ctx_clear(bpf_net_ctx);
 7838
 7839		/* When busy poll is enabled, the old packets are not flushed in
 7840		 * napi_complete_done. So flush them here.
 7841		 */
 7842		if (busy_poll_last_qs)
 7843			gro_flush_normal(&napi->gro, HZ >= 1000);
 7844		local_bh_enable();
 7845
 7846		/* Call cond_resched here to avoid watchdog warnings. */
 7847		if (repoll || busy_poll_last_qs) {
 7848			rcu_softirq_qs_periodic(last_qs);
 7849			cond_resched();
 7850		}
 7851
 7852		if (!repoll)
 7853			break;
 7854	}
 7855
 7856	if (busy_poll_last_qs)
 7857		*busy_poll_last_qs = last_qs;
 7858}
 7859
 7860static int napi_threaded_poll(void *data)
 7861{
 7862	struct napi_struct *napi = data;
 7863	unsigned long last_qs = jiffies;
 7864	bool want_busy_poll;
 7865	bool in_busy_poll;
 7866	unsigned long val;
 7867
 7868	while (!napi_thread_wait(napi)) {
 7869		val = READ_ONCE(napi->state);
 7870
 7871		want_busy_poll = val & NAPIF_STATE_THREADED_BUSY_POLL;
 7872		in_busy_poll = val & NAPIF_STATE_IN_BUSY_POLL;
 7873
 7874		if (unlikely(val & NAPIF_STATE_DISABLE))
 7875			want_busy_poll = false;
 7876
 7877		if (want_busy_poll != in_busy_poll)
 7878			assign_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state,
 7879				   want_busy_poll);
 7880
 7881		napi_threaded_poll_loop(napi, want_busy_poll ? &last_qs : NULL);
 7882	}
 7883
 7884	return 0;
 7885}
 7886
 7887static __latent_entropy void net_rx_action(void)
 7888{
 7889	struct softnet_data *sd = this_cpu_ptr(&softnet_data);
 7890	unsigned long time_limit = jiffies +
 7891		usecs_to_jiffies(READ_ONCE(net_hotdata.netdev_budget_usecs));
 7892	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
 7893	int budget = READ_ONCE(net_hotdata.netdev_budget);
 7894	LIST_HEAD(list);
 7895	LIST_HEAD(repoll);
 7896
 7897	bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
 7898start:
 7899	sd->in_net_rx_action = true;
 7900	local_irq_disable();
 7901	list_splice_init(&sd->poll_list, &list);
 7902	local_irq_enable();
 7903
 7904	for (;;) {
 7905		struct napi_struct *n;
 7906
 7907		skb_defer_free_flush();
 7908
 7909		if (list_empty(&list)) {
 7910			if (list_empty(&repoll)) {
 7911				sd->in_net_rx_action = false;
 7912				barrier();
 7913				/* We need to check if ____napi_schedule()
 7914				 * had refilled poll_list while
 7915				 * sd->in_net_rx_action was true.
 7916				 */
 7917				if (!list_empty(&sd->poll_list))
 7918					goto start;
 7919				if (!sd_has_rps_ipi_waiting(sd))
 7920					goto end;
 7921			}
 7922			break;
 7923		}
 7924
 7925		n = list_first_entry(&list, struct napi_struct, poll_list);
 7926		budget -= napi_poll(n, &repoll);
 7927
 7928		/* If softirq window is exhausted then punt.
 7929		 * Allow this to run for 2 jiffies since which will allow
 7930		 * an average latency of 1.5/HZ.
 7931		 */
 7932		if (unlikely(budget <= 0 ||
 7933			     time_after_eq(jiffies, time_limit))) {
 7934			/* Pairs with READ_ONCE() in softnet_seq_show() */
 7935			WRITE_ONCE(sd->time_squeeze, sd->time_squeeze + 1);
 7936			break;
 7937		}
 7938	}
 7939
 7940	local_irq_disable();
 7941
 7942	list_splice_tail_init(&sd->poll_list, &list);
 7943	list_splice_tail(&repoll, &list);
 7944	list_splice(&list, &sd->poll_list);
 7945	if (!list_empty(&sd->poll_list))
 7946		__raise_softirq_irqoff(NET_RX_SOFTIRQ);
 7947	else
 7948		sd->in_net_rx_action = false;
 7949
 7950	net_rps_action_and_irq_enable(sd);
 7951end:
 7952	bpf_net_ctx_clear(bpf_net_ctx);
 7953}
 7954
 7955struct netdev_adjacent {
 7956	struct net_device *dev;
 7957	netdevice_tracker dev_tracker;
 7958
 7959	/* upper master flag, there can only be one master device per list */
 7960	bool master;
 7961
 7962	/* lookup ignore flag */
 7963	bool ignore;
 7964
 7965	/* counter for the number of times this device was added to us */
 7966	u16 ref_nr;
 7967
 7968	/* private field for the users */
 7969	void *private;
 7970
 7971	struct list_head list;
 7972	struct rcu_head rcu;
 7973};
 7974
 7975static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
 7976						 struct list_head *adj_list)
 7977{
 7978	struct netdev_adjacent *adj;
 7979
 7980	list_for_each_entry(adj, adj_list, list) {
 7981		if (adj->dev == adj_dev)
 7982			return adj;
 7983	}
 7984	return NULL;
 7985}
 7986
 7987static int ____netdev_has_upper_dev(struct net_device *upper_dev,
 7988				    struct netdev_nested_priv *priv)
 7989{
 7990	struct net_device *dev = (struct net_device *)priv->data;
 7991
 7992	return upper_dev == dev;
 7993}
 7994
 7995/**
 7996 * netdev_has_upper_dev - Check if device is linked to an upper device
 7997 * @dev: device
 7998 * @upper_dev: upper device to check
 7999 *
 8000 * Find out if a device is linked to specified upper device and return true
 8001 * in case it is. Note that this checks only immediate upper device,
 8002 * not through a complete stack of devices. The caller must hold the RTNL lock.
 8003 */
 8004bool netdev_has_upper_dev(struct net_device *dev,
 8005			  struct net_device *upper_dev)
 8006{
 8007	struct netdev_nested_priv priv = {
 8008		.data = (void *)upper_dev,
 8009	};
 8010
 8011	ASSERT_RTNL();
 8012
 8013	return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
 8014					     &priv);
 8015}
 8016EXPORT_SYMBOL(netdev_has_upper_dev);
 8017
 8018/**
 8019 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
 8020 * @dev: device
 8021 * @upper_dev: upper device to check
 8022 *
 8023 * Find out if a device is linked to specified upper device and return true
 8024 * in case it is. Note that this checks the entire upper device chain.
 8025 * The caller must hold rcu lock.
 8026 */
 8027
 8028bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
 8029				  struct net_device *upper_dev)
 8030{
 8031	struct netdev_nested_priv priv = {
 8032		.data = (void *)upper_dev,
 8033	};
 8034
 8035	return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
 8036					       &priv);
 8037}
 8038EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
 8039
 8040/**
 8041 * netdev_has_any_upper_dev - Check if device is linked to some device
 8042 * @dev: device
 8043 *
 8044 * Find out if a device is linked to an upper device and return true in case
 8045 * it is. The caller must hold the RTNL lock.
 8046 */
 8047bool netdev_has_any_upper_dev(struct net_device *dev)
 8048{
 8049	ASSERT_RTNL();
 8050
 8051	return !list_empty(&dev->adj_list.upper);
 8052}
 8053EXPORT_SYMBOL(netdev_has_any_upper_dev);
 8054
 8055/**
 8056 * netdev_master_upper_dev_get - Get master upper device
 8057 * @dev: device
 8058 *
 8059 * Find a master upper device and return pointer to it or NULL in case
 8060 * it's not there. The caller must hold the RTNL lock.
 8061 */
 8062struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
 8063{
 8064	struct netdev_adjacent *upper;
 8065
 8066	ASSERT_RTNL();
 8067
 8068	if (list_empty(&dev->adj_list.upper))
 8069		return NULL;
 8070
 8071	upper = list_first_entry(&dev->adj_list.upper,
 8072				 struct netdev_adjacent, list);
 8073	if (likely(upper->master))
 8074		return upper->dev;
 8075	return NULL;
 8076}
 8077EXPORT_SYMBOL(netdev_master_upper_dev_get);
 8078
 8079static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
 8080{
 8081	struct netdev_adjacent *upper;
 8082
 8083	ASSERT_RTNL();
 8084
 8085	if (list_empty(&dev->adj_list.upper))
 8086		return NULL;
 8087
 8088	upper = list_first_entry(&dev->adj_list.upper,
 8089				 struct netdev_adjacent, list);
 8090	if (likely(upper->master) && !upper->ignore)
 8091		return upper->dev;
 8092	return NULL;
 8093}
 8094
 8095/**
 8096 * netdev_has_any_lower_dev - Check if device is linked to some device
 8097 * @dev: device
 8098 *
 8099 * Find out if a device is linked to a lower device and return true in case
 8100 * it is. The caller must hold the RTNL lock.
 8101 */
 8102static bool netdev_has_any_lower_dev(struct net_device *dev)
 8103{
 8104	ASSERT_RTNL();
 8105
 8106	return !list_empty(&dev->adj_list.lower);
 8107}
 8108
 8109void *netdev_adjacent_get_private(struct list_head *adj_list)
 8110{
 8111	struct netdev_adjacent *adj;
 8112
 8113	adj = list_entry(adj_list, struct netdev_adjacent, list);
 8114
 8115	return adj->private;
 8116}
 8117EXPORT_SYMBOL(netdev_adjacent_get_private);
 8118
 8119/**
 8120 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
 8121 * @dev: device
 8122 * @iter: list_head ** of the current position
 8123 *
 8124 * Gets the next device from the dev's upper list, starting from iter
 8125 * position. The caller must hold RCU read lock.
 8126 */
 8127struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
 8128						 struct list_head **iter)
 8129{
 8130	struct netdev_adjacent *upper;
 8131
 8132	WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
 8133
 8134	upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
 8135
 8136	if (&upper->list == &dev->adj_list.upper)
 8137		return NULL;
 8138
 8139	*iter = &upper->list;
 8140
 8141	return upper->dev;
 8142}
 8143EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
 8144
 8145static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
 8146						  struct list_head **iter,
 8147						  bool *ignore)
 8148{
 8149	struct netdev_adjacent *upper;
 8150
 8151	upper = list_entry((*iter)->next, struct netdev_adjacent, list);
 8152
 8153	if (&upper->list == &dev->adj_list.upper)
 8154		return NULL;
 8155
 8156	*iter = &upper->list;
 8157	*ignore = upper->ignore;
 8158
 8159	return upper->dev;
 8160}
 8161
 8162static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
 8163						    struct list_head **iter)
 8164{
 8165	struct netdev_adjacent *upper;
 8166
 8167	WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
 8168
 8169	upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
 8170
 8171	if (&upper->list == &dev->adj_list.upper)
 8172		return NULL;
 8173
 8174	*iter = &upper->list;
 8175
 8176	return upper->dev;
 8177}
 8178
 8179static int __netdev_walk_all_upper_dev(struct net_device *dev,
 8180				       int (*fn)(struct net_device *dev,
 8181					 struct netdev_nested_priv *priv),
 8182				       struct netdev_nested_priv *priv)
 8183{
 8184	struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
 8185	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
 8186	int ret, cur = 0;
 8187	bool ignore;
 8188
 8189	now = dev;
 8190	iter = &dev->adj_list.upper;
 8191
 8192	while (1) {
 8193		if (now != dev) {
 8194			ret = fn(now, priv);
 8195			if (ret)
 8196				return ret;
 8197		}
 8198
 8199		next = NULL;
 8200		while (1) {
 8201			udev = __netdev_next_upper_dev(now, &iter, &ignore);
 8202			if (!udev)
 8203				break;
 8204			if (ignore)
 8205				continue;
 8206
 8207			next = udev;
 8208			niter = &udev->adj_list.upper;
 8209			dev_stack[cur] = now;
 8210			iter_stack[cur++] = iter;
 8211			break;
 8212		}
 8213
 8214		if (!next) {
 8215			if (!cur)
 8216				return 0;
 8217			next = dev_stack[--cur];
 8218			niter = iter_stack[cur];
 8219		}
 8220
 8221		now = next;
 8222		iter = niter;
 8223	}
 8224
 8225	return 0;
 8226}
 8227
 8228int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
 8229				  int (*fn)(struct net_device *dev,
 8230					    struct netdev_nested_priv *priv),
 8231				  struct netdev_nested_priv *priv)
 8232{
 8233	struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
 8234	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
 8235	int ret, cur = 0;
 8236
 8237	now = dev;
 8238	iter = &dev->adj_list.upper;
 8239
 8240	while (1) {
 8241		if (now != dev) {
 8242			ret = fn(now, priv);
 8243			if (ret)
 8244				return ret;
 8245		}
 8246
 8247		next = NULL;
 8248		while (1) {
 8249			udev = netdev_next_upper_dev_rcu(now, &iter);
 8250			if (!udev)
 8251				break;
 8252
 8253			next = udev;
 8254			niter = &udev->adj_list.upper;
 8255			dev_stack[cur] = now;
 8256			iter_stack[cur++] = iter;
 8257			break;
 8258		}
 8259
 8260		if (!next) {
 8261			if (!cur)
 8262				return 0;
 8263			next = dev_stack[--cur];
 8264			niter = iter_stack[cur];
 8265		}
 8266
 8267		now = next;
 8268		iter = niter;
 8269	}
 8270
 8271	return 0;
 8272}
 8273EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
 8274
 8275static bool __netdev_has_upper_dev(struct net_device *dev,
 8276				   struct net_device *upper_dev)
 8277{
 8278	struct netdev_nested_priv priv = {
 8279		.flags = 0,
 8280		.data = (void *)upper_dev,
 8281	};
 8282
 8283	ASSERT_RTNL();
 8284
 8285	return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
 8286					   &priv);
 8287}
 8288
 8289/**
 8290 * netdev_lower_get_next_private - Get the next ->private from the
 8291 *				   lower neighbour list
 8292 * @dev: device
 8293 * @iter: list_head ** of the current position
 8294 *
 8295 * Gets the next netdev_adjacent->private from the dev's lower neighbour
 8296 * list, starting from iter position. The caller must hold either hold the
 8297 * RTNL lock or its own locking that guarantees that the neighbour lower
 8298 * list will remain unchanged.
 8299 */
 8300void *netdev_lower_get_next_private(struct net_device *dev,
 8301				    struct list_head **iter)
 8302{
 8303	struct netdev_adjacent *lower;
 8304
 8305	lower = list_entry(*iter, struct netdev_adjacent, list);
 8306
 8307	if (&lower->list == &dev->adj_list.lower)
 8308		return NULL;
 8309
 8310	*iter = lower->list.next;
 8311
 8312	return lower->private;
 8313}
 8314EXPORT_SYMBOL(netdev_lower_get_next_private);
 8315
 8316/**
 8317 * netdev_lower_get_next_private_rcu - Get the next ->private from the
 8318 *				       lower neighbour list, RCU
 8319 *				       variant
 8320 * @dev: device
 8321 * @iter: list_head ** of the current position
 8322 *
 8323 * Gets the next netdev_adjacent->private from the dev's lower neighbour
 8324 * list, starting from iter position. The caller must hold RCU read lock.
 8325 */
 8326void *netdev_lower_get_next_private_rcu(struct net_device *dev,
 8327					struct list_head **iter)
 8328{
 8329	struct netdev_adjacent *lower;
 8330
 8331	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
 8332
 8333	lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
 8334
 8335	if (&lower->list == &dev->adj_list.lower)
 8336		return NULL;
 8337
 8338	*iter = &lower->list;
 8339
 8340	return lower->private;
 8341}
 8342EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
 8343
 8344/**
 8345 * netdev_lower_get_next - Get the next device from the lower neighbour
 8346 *                         list
 8347 * @dev: device
 8348 * @iter: list_head ** of the current position
 8349 *
 8350 * Gets the next netdev_adjacent from the dev's lower neighbour
 8351 * list, starting from iter position. The caller must hold RTNL lock or
 8352 * its own locking that guarantees that the neighbour lower
 8353 * list will remain unchanged.
 8354 */
 8355void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
 8356{
 8357	struct netdev_adjacent *lower;
 8358
 8359	lower = list_entry(*iter, struct netdev_adjacent, list);
 8360
 8361	if (&lower->list == &dev->adj_list.lower)
 8362		return NULL;
 8363
 8364	*iter = lower->list.next;
 8365
 8366	return lower->dev;
 8367}
 8368EXPORT_SYMBOL(netdev_lower_get_next);
 8369
 8370static struct net_device *netdev_next_lower_dev(struct net_device *dev,
 8371						struct list_head **iter)
 8372{
 8373	struct netdev_adjacent *lower;
 8374
 8375	lower = list_entry((*iter)->next, struct netdev_adjacent, list);
 8376
 8377	if (&lower->list == &dev->adj_list.lower)
 8378		return NULL;
 8379
 8380	*iter = &lower->list;
 8381
 8382	return lower->dev;
 8383}
 8384
 8385static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
 8386						  struct list_head **iter,
 8387						  bool *ignore)
 8388{
 8389	struct netdev_adjacent *lower;
 8390
 8391	lower = list_entry((*iter)->next, struct netdev_adjacent, list);
 8392
 8393	if (&lower->list == &dev->adj_list.lower)
 8394		return NULL;
 8395
 8396	*iter = &lower->list;
 8397	*ignore = lower->ignore;
 8398
 8399	return lower->dev;
 8400}
 8401
 8402int netdev_walk_all_lower_dev(struct net_device *dev,
 8403			      int (*fn)(struct net_device *dev,
 8404					struct netdev_nested_priv *priv),
 8405			      struct netdev_nested_priv *priv)
 8406{
 8407	struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
 8408	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
 8409	int ret, cur = 0;
 8410
 8411	now = dev;
 8412	iter = &dev->adj_list.lower;
 8413
 8414	while (1) {
 8415		if (now != dev) {
 8416			ret = fn(now, priv);
 8417			if (ret)
 8418				return ret;
 8419		}
 8420
 8421		next = NULL;
 8422		while (1) {
 8423			ldev = netdev_next_lower_dev(now, &iter);
 8424			if (!ldev)
 8425				break;
 8426
 8427			next = ldev;
 8428			niter = &ldev->adj_list.lower;
 8429			dev_stack[cur] = now;
 8430			iter_stack[cur++] = iter;
 8431			break;
 8432		}
 8433
 8434		if (!next) {
 8435			if (!cur)
 8436				return 0;
 8437			next = dev_stack[--cur];
 8438			niter = iter_stack[cur];
 8439		}
 8440
 8441		now = next;
 8442		iter = niter;
 8443	}
 8444
 8445	return 0;
 8446}
 8447EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
 8448
 8449static int __netdev_walk_all_lower_dev(struct net_device *dev,
 8450				       int (*fn)(struct net_device *dev,
 8451					 struct netdev_nested_priv *priv),
 8452				       struct netdev_nested_priv *priv)
 8453{
 8454	struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
 8455	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
 8456	int ret, cur = 0;
 8457	bool ignore;
 8458
 8459	now = dev;
 8460	iter = &dev->adj_list.lower;
 8461
 8462	while (1) {
 8463		if (now != dev) {
 8464			ret = fn(now, priv);
 8465			if (ret)
 8466				return ret;
 8467		}
 8468
 8469		next = NULL;
 8470		while (1) {
 8471			ldev = __netdev_next_lower_dev(now, &iter, &ignore);
 8472			if (!ldev)
 8473				break;
 8474			if (ignore)
 8475				continue;
 8476
 8477			next = ldev;
 8478			niter = &ldev->adj_list.lower;
 8479			dev_stack[cur] = now;
 8480			iter_stack[cur++] = iter;
 8481			break;
 8482		}
 8483
 8484		if (!next) {
 8485			if (!cur)
 8486				return 0;
 8487			next = dev_stack[--cur];
 8488			niter = iter_stack[cur];
 8489		}
 8490
 8491		now = next;
 8492		iter = niter;
 8493	}
 8494
 8495	return 0;
 8496}
 8497
 8498struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
 8499					     struct list_head **iter)
 8500{
 8501	struct netdev_adjacent *lower;
 8502
 8503	lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
 8504	if (&lower->list == &dev->adj_list.lower)
 8505		return NULL;
 8506
 8507	*iter = &lower->list;
 8508
 8509	return lower->dev;
 8510}
 8511EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
 8512
 8513static u8 __netdev_upper_depth(struct net_device *dev)
 8514{
 8515	struct net_device *udev;
 8516	struct list_head *iter;
 8517	u8 max_depth = 0;
 8518	bool ignore;
 8519
 8520	for (iter = &dev->adj_list.upper,
 8521	     udev = __netdev_next_upper_dev(dev, &iter, &ignore);
 8522	     udev;
 8523	     udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
 8524		if (ignore)
 8525			continue;
 8526		if (max_depth < udev->upper_level)
 8527			max_depth = udev->upper_level;
 8528	}
 8529
 8530	return max_depth;
 8531}
 8532
 8533static u8 __netdev_lower_depth(struct net_device *dev)
 8534{
 8535	struct net_device *ldev;
 8536	struct list_head *iter;
 8537	u8 max_depth = 0;
 8538	bool ignore;
 8539
 8540	for (iter = &dev->adj_list.lower,
 8541	     ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
 8542	     ldev;
 8543	     ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
 8544		if (ignore)
 8545			continue;
 8546		if (max_depth < ldev->lower_level)
 8547			max_depth = ldev->lower_level;
 8548	}
 8549
 8550	return max_depth;
 8551}
 8552
 8553static int __netdev_update_upper_level(struct net_device *dev,
 8554				       struct netdev_nested_priv *__unused)
 8555{
 8556	dev->upper_level = __netdev_upper_depth(dev) + 1;
 8557	return 0;
 8558}
 8559
 8560#ifdef CONFIG_LOCKDEP
 8561static LIST_HEAD(net_unlink_list);
 8562
 8563static void net_unlink_todo(struct net_device *dev)
 8564{
 8565	if (list_empty(&dev->unlink_list))
 8566		list_add_tail(&dev->unlink_list, &net_unlink_list);
 8567}
 8568#endif
 8569
 8570static int __netdev_update_lower_level(struct net_device *dev,
 8571				       struct netdev_nested_priv *priv)
 8572{
 8573	dev->lower_level = __netdev_lower_depth(dev) + 1;
 8574
 8575#ifdef CONFIG_LOCKDEP
 8576	if (!priv)
 8577		return 0;
 8578
 8579	if (priv->flags & NESTED_SYNC_IMM)
 8580		dev->nested_level = dev->lower_level - 1;
 8581	if (priv->flags & NESTED_SYNC_TODO)
 8582		net_unlink_todo(dev);
 8583#endif
 8584	return 0;
 8585}
 8586
 8587int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
 8588				  int (*fn)(struct net_device *dev,
 8589					    struct netdev_nested_priv *priv),
 8590				  struct netdev_nested_priv *priv)
 8591{
 8592	struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
 8593	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
 8594	int ret, cur = 0;
 8595
 8596	now = dev;
 8597	iter = &dev->adj_list.lower;
 8598
 8599	while (1) {
 8600		if (now != dev) {
 8601			ret = fn(now, priv);
 8602			if (ret)
 8603				return ret;
 8604		}
 8605
 8606		next = NULL;
 8607		while (1) {
 8608			ldev = netdev_next_lower_dev_rcu(now, &iter);
 8609			if (!ldev)
 8610				break;
 8611
 8612			next = ldev;
 8613			niter = &ldev->adj_list.lower;
 8614			dev_stack[cur] = now;
 8615			iter_stack[cur++] = iter;
 8616			break;
 8617		}
 8618
 8619		if (!next) {
 8620			if (!cur)
 8621				return 0;
 8622			next = dev_stack[--cur];
 8623			niter = iter_stack[cur];
 8624		}
 8625
 8626		now = next;
 8627		iter = niter;
 8628	}
 8629
 8630	return 0;
 8631}
 8632EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
 8633
 8634/**
 8635 * netdev_lower_get_first_private_rcu - Get the first ->private from the
 8636 *				       lower neighbour list, RCU
 8637 *				       variant
 8638 * @dev: device
 8639 *
 8640 * Gets the first netdev_adjacent->private from the dev's lower neighbour
 8641 * list. The caller must hold RCU read lock.
 8642 */
 8643void *netdev_lower_get_first_private_rcu(struct net_device *dev)
 8644{
 8645	struct netdev_adjacent *lower;
 8646
 8647	lower = list_first_or_null_rcu(&dev->adj_list.lower,
 8648			struct netdev_adjacent, list);
 8649	if (lower)
 8650		return lower->private;
 8651	return NULL;
 8652}
 8653EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
 8654
 8655/**
 8656 * netdev_master_upper_dev_get_rcu - Get master upper device
 8657 * @dev: device
 8658 *
 8659 * Find a master upper device and return pointer to it or NULL in case
 8660 * it's not there. The caller must hold the RCU read lock.
 8661 */
 8662struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
 8663{
 8664	struct netdev_adjacent *upper;
 8665
 8666	upper = list_first_or_null_rcu(&dev->adj_list.upper,
 8667				       struct netdev_adjacent, list);
 8668	if (upper && likely(upper->master))
 8669		return upper->dev;
 8670	return NULL;
 8671}
 8672EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
 8673
 8674static int netdev_adjacent_sysfs_add(struct net_device *dev,
 8675			      struct net_device *adj_dev,
 8676			      struct list_head *dev_list)
 8677{
 8678	char linkname[IFNAMSIZ+7];
 8679
 8680	sprintf(linkname, dev_list == &dev->adj_list.upper ?
 8681		"upper_%s" : "lower_%s", adj_dev->name);
 8682	return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
 8683				 linkname);
 8684}
 8685static void netdev_adjacent_sysfs_del(struct net_device *dev,
 8686			       char *name,
 8687			       struct list_head *dev_list)
 8688{
 8689	char linkname[IFNAMSIZ+7];
 8690
 8691	sprintf(linkname, dev_list == &dev->adj_list.upper ?
 8692		"upper_%s" : "lower_%s", name);
 8693	sysfs_remove_link(&(dev->dev.kobj), linkname);
 8694}
 8695
 8696static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
 8697						 struct net_device *adj_dev,
 8698						 struct list_head *dev_list)
 8699{
 8700	return (dev_list == &dev->adj_list.upper ||
 8701		dev_list == &dev->adj_list.lower) &&
 8702		net_eq(dev_net(dev), dev_net(adj_dev));
 8703}
 8704
 8705static int __netdev_adjacent_dev_insert(struct net_device *dev,
 8706					struct net_device *adj_dev,
 8707					struct list_head *dev_list,
 8708					void *private, bool master)
 8709{
 8710	struct netdev_adjacent *adj;
 8711	int ret;
 8712
 8713	adj = __netdev_find_adj(adj_dev, dev_list);
 8714
 8715	if (adj) {
 8716		adj->ref_nr += 1;
 8717		pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
 8718			 dev->name, adj_dev->name, adj->ref_nr);
 8719
 8720		return 0;
 8721	}
 8722
 8723	adj = kmalloc(sizeof(*adj), GFP_KERNEL);
 8724	if (!adj)
 8725		return -ENOMEM;
 8726
 8727	adj->dev = adj_dev;
 8728	adj->master = master;
 8729	adj->ref_nr = 1;
 8730	adj->private = private;
 8731	adj->ignore = false;
 8732	netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL);
 8733
 8734	pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
 8735		 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
 8736
 8737	if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
 8738		ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
 8739		if (ret)
 8740			goto free_adj;
 8741	}
 8742
 8743	/* Ensure that master link is always the first item in list. */
 8744	if (master) {
 8745		ret = sysfs_create_link(&(dev->dev.kobj),
 8746					&(adj_dev->dev.kobj), "master");
 8747		if (ret)
 8748			goto remove_symlinks;
 8749
 8750		list_add_rcu(&adj->list, dev_list);
 8751	} else {
 8752		list_add_tail_rcu(&adj->list, dev_list);
 8753	}
 8754
 8755	return 0;
 8756
 8757remove_symlinks:
 8758	if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
 8759		netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
 8760free_adj:
 8761	netdev_put(adj_dev, &adj->dev_tracker);
 8762	kfree(adj);
 8763
 8764	return ret;
 8765}
 8766
 8767static void __netdev_adjacent_dev_remove(struct net_device *dev,
 8768					 struct net_device *adj_dev,
 8769					 u16 ref_nr,
 8770					 struct list_head *dev_list)
 8771{
 8772	struct netdev_adjacent *adj;
 8773
 8774	pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
 8775		 dev->name, adj_dev->name, ref_nr);
 8776
 8777	adj = __netdev_find_adj(adj_dev, dev_list);
 8778
 8779	if (!adj) {
 8780		pr_err("Adjacency does not exist for device %s from %s\n",
 8781		       dev->name, adj_dev->name);
 8782		WARN_ON(1);
 8783		return;
 8784	}
 8785
 8786	if (adj->ref_nr > ref_nr) {
 8787		pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
 8788			 dev->name, adj_dev->name, ref_nr,
 8789			 adj->ref_nr - ref_nr);
 8790		adj->ref_nr -= ref_nr;
 8791		return;
 8792	}
 8793
 8794	if (adj->master)
 8795		sysfs_remove_link(&(dev->dev.kobj), "master");
 8796
 8797	if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
 8798		netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
 8799
 8800	list_del_rcu(&adj->list);
 8801	pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
 8802		 adj_dev->name, dev->name, adj_dev->name);
 8803	netdev_put(adj_dev, &adj->dev_tracker);
 8804	kfree_rcu(adj, rcu);
 8805}
 8806
 8807static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
 8808					    struct net_device *upper_dev,
 8809					    struct list_head *up_list,
 8810					    struct list_head *down_list,
 8811					    void *private, bool master)
 8812{
 8813	int ret;
 8814
 8815	ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
 8816					   private, master);
 8817	if (ret)
 8818		return ret;
 8819
 8820	ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
 8821					   private, false);
 8822	if (ret) {
 8823		__netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
 8824		return ret;
 8825	}
 8826
 8827	return 0;
 8828}
 8829
 8830static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
 8831					       struct net_device *upper_dev,
 8832					       u16 ref_nr,
 8833					       struct list_head *up_list,
 8834					       struct list_head *down_list)
 8835{
 8836	__netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
 8837	__netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
 8838}
 8839
 8840static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
 8841						struct net_device *upper_dev,
 8842						void *private, bool master)
 8843{
 8844	return __netdev_adjacent_dev_link_lists(dev, upper_dev,
 8845						&dev->adj_list.upper,
 8846						&upper_dev->adj_list.lower,
 8847						private, master);
 8848}
 8849
 8850static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
 8851						   struct net_device *upper_dev)
 8852{
 8853	__netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
 8854					   &dev->adj_list.upper,
 8855					   &upper_dev->adj_list.lower);
 8856}
 8857
 8858static int __netdev_upper_dev_link(struct net_device *dev,
 8859				   struct net_device *upper_dev, bool master,
 8860				   void *upper_priv, void *upper_info,
 8861				   struct netdev_nested_priv *priv,
 8862				   struct netlink_ext_ack *extack)
 8863{
 8864	struct netdev_notifier_changeupper_info changeupper_info = {
 8865		.info = {
 8866			.dev = dev,
 8867			.extack = extack,
 8868		},
 8869		.upper_dev = upper_dev,
 8870		.master = master,
 8871		.linking = true,
 8872		.upper_info = upper_info,
 8873	};
 8874	struct net_device *master_dev;
 8875	int ret = 0;
 8876
 8877	ASSERT_RTNL();
 8878
 8879	if (dev == upper_dev)
 8880		return -EBUSY;
 8881
 8882	/* To prevent loops, check if dev is not upper device to upper_dev. */
 8883	if (__netdev_has_upper_dev(upper_dev, dev))
 8884		return -EBUSY;
 8885
 8886	if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
 8887		return -EMLINK;
 8888
 8889	if (!master) {
 8890		if (__netdev_has_upper_dev(dev, upper_dev))
 8891			return -EEXIST;
 8892	} else {
 8893		master_dev = __netdev_master_upper_dev_get(dev);
 8894		if (master_dev)
 8895			return master_dev == upper_dev ? -EEXIST : -EBUSY;
 8896	}
 8897
 8898	ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
 8899					    &changeupper_info.info);
 8900	ret = notifier_to_errno(ret);
 8901	if (ret)
 8902		return ret;
 8903
 8904	ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
 8905						   master);
 8906	if (ret)
 8907		return ret;
 8908
 8909	ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
 8910					    &changeupper_info.info);
 8911	ret = notifier_to_errno(ret);
 8912	if (ret)
 8913		goto rollback;
 8914
 8915	__netdev_update_upper_level(dev, NULL);
 8916	__netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
 8917
 8918	__netdev_update_lower_level(upper_dev, priv);
 8919	__netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
 8920				    priv);
 8921
 8922	return 0;
 8923
 8924rollback:
 8925	__netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
 8926
 8927	return ret;
 8928}
 8929
 8930/**
 8931 * netdev_upper_dev_link - Add a link to the upper device
 8932 * @dev: device
 8933 * @upper_dev: new upper device
 8934 * @extack: netlink extended ack
 8935 *
 8936 * Adds a link to device which is upper to this one. The caller must hold
 8937 * the RTNL lock. On a failure a negative errno code is returned.
 8938 * On success the reference counts are adjusted and the function
 8939 * returns zero.
 8940 */
 8941int netdev_upper_dev_link(struct net_device *dev,
 8942			  struct net_device *upper_dev,
 8943			  struct netlink_ext_ack *extack)
 8944{
 8945	struct netdev_nested_priv priv = {
 8946		.flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
 8947		.data = NULL,
 8948	};
 8949
 8950	return __netdev_upper_dev_link(dev, upper_dev, false,
 8951				       NULL, NULL, &priv, extack);
 8952}
 8953EXPORT_SYMBOL(netdev_upper_dev_link);
 8954
 8955/**
 8956 * netdev_master_upper_dev_link - Add a master link to the upper device
 8957 * @dev: device
 8958 * @upper_dev: new upper device
 8959 * @upper_priv: upper device private
 8960 * @upper_info: upper info to be passed down via notifier
 8961 * @extack: netlink extended ack
 8962 *
 8963 * Adds a link to device which is upper to this one. In this case, only
 8964 * one master upper device can be linked, although other non-master devices
 8965 * might be linked as well. The caller must hold the RTNL lock.
 8966 * On a failure a negative errno code is returned. On success the reference
 8967 * counts are adjusted and the function returns zero.
 8968 */
 8969int netdev_master_upper_dev_link(struct net_device *dev,
 8970				 struct net_device *upper_dev,
 8971				 void *upper_priv, void *upper_info,
 8972				 struct netlink_ext_ack *extack)
 8973{
 8974	struct netdev_nested_priv priv = {
 8975		.flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
 8976		.data = NULL,
 8977	};
 8978
 8979	return __netdev_upper_dev_link(dev, upper_dev, true,
 8980				       upper_priv, upper_info, &priv, extack);
 8981}
 8982EXPORT_SYMBOL(netdev_master_upper_dev_link);
 8983
 8984static void __netdev_upper_dev_unlink(struct net_device *dev,
 8985				      struct net_device *upper_dev,
 8986				      struct netdev_nested_priv *priv)
 8987{
 8988	struct netdev_notifier_changeupper_info changeupper_info = {
 8989		.info = {
 8990			.dev = dev,
 8991		},
 8992		.upper_dev = upper_dev,
 8993		.linking = false,
 8994	};
 8995
 8996	ASSERT_RTNL();
 8997
 8998	changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
 8999
 9000	call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
 9001				      &changeupper_info.info);
 9002
 9003	__netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
 9004
 9005	call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
 9006				      &changeupper_info.info);
 9007
 9008	__netdev_update_upper_level(dev, NULL);
 9009	__netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
 9010
 9011	__netdev_update_lower_level(upper_dev, priv);
 9012	__netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
 9013				    priv);
 9014}
 9015
 9016/**
 9017 * netdev_upper_dev_unlink - Removes a link to upper device
 9018 * @dev: device
 9019 * @upper_dev: new upper device
 9020 *
 9021 * Removes a link to device which is upper to this one. The caller must hold
 9022 * the RTNL lock.
 9023 */
 9024void netdev_upper_dev_unlink(struct net_device *dev,
 9025			     struct net_device *upper_dev)
 9026{
 9027	struct netdev_nested_priv priv = {
 9028		.flags = NESTED_SYNC_TODO,
 9029		.data = NULL,
 9030	};
 9031
 9032	__netdev_upper_dev_unlink(dev, upper_dev, &priv);
 9033}
 9034EXPORT_SYMBOL(netdev_upper_dev_unlink);
 9035
 9036static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
 9037				      struct net_device *lower_dev,
 9038				      bool val)
 9039{
 9040	struct netdev_adjacent *adj;
 9041
 9042	adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
 9043	if (adj)
 9044		adj->ignore = val;
 9045
 9046	adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
 9047	if (adj)
 9048		adj->ignore = val;
 9049}
 9050
 9051static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
 9052					struct net_device *lower_dev)
 9053{
 9054	__netdev_adjacent_dev_set(upper_dev, lower_dev, true);
 9055}
 9056
 9057static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
 9058				       struct net_device *lower_dev)
 9059{
 9060	__netdev_adjacent_dev_set(upper_dev, lower_dev, false);
 9061}
 9062
 9063int netdev_adjacent_change_prepare(struct net_device *old_dev,
 9064				   struct net_device *new_dev,
 9065				   struct net_device *dev,
 9066				   struct netlink_ext_ack *extack)
 9067{
 9068	struct netdev_nested_priv priv = {
 9069		.flags = 0,
 9070		.data = NULL,
 9071	};
 9072	int err;
 9073
 9074	if (!new_dev)
 9075		return 0;
 9076
 9077	if (old_dev && new_dev != old_dev)
 9078		netdev_adjacent_dev_disable(dev, old_dev);
 9079	err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
 9080				      extack);
 9081	if (err) {
 9082		if (old_dev && new_dev != old_dev)
 9083			netdev_adjacent_dev_enable(dev, old_dev);
 9084		return err;
 9085	}
 9086
 9087	return 0;
 9088}
 9089EXPORT_SYMBOL(netdev_adjacent_change_prepare);
 9090
 9091void netdev_adjacent_change_commit(struct net_device *old_dev,
 9092				   struct net_device *new_dev,
 9093				   struct net_device *dev)
 9094{
 9095	struct netdev_nested_priv priv = {
 9096		.flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
 9097		.data = NULL,
 9098	};
 9099
 9100	if (!new_dev || !old_dev)
 9101		return;
 9102
 9103	if (new_dev == old_dev)
 9104		return;
 9105
 9106	netdev_adjacent_dev_enable(dev, old_dev);
 9107	__netdev_upper_dev_unlink(old_dev, dev, &priv);
 9108}
 9109EXPORT_SYMBOL(netdev_adjacent_change_commit);
 9110
 9111void netdev_adjacent_change_abort(struct net_device *old_dev,
 9112				  struct net_device *new_dev,
 9113				  struct net_device *dev)
 9114{
 9115	struct netdev_nested_priv priv = {
 9116		.flags = 0,
 9117		.data = NULL,
 9118	};
 9119
 9120	if (!new_dev)
 9121		return;
 9122
 9123	if (old_dev && new_dev != old_dev)
 9124		netdev_adjacent_dev_enable(dev, old_dev);
 9125
 9126	__netdev_upper_dev_unlink(new_dev, dev, &priv);
 9127}
 9128EXPORT_SYMBOL(netdev_adjacent_change_abort);
 9129
 9130/**
 9131 * netdev_bonding_info_change - Dispatch event about slave change
 9132 * @dev: device
 9133 * @bonding_info: info to dispatch
 9134 *
 9135 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
 9136 * The caller must hold the RTNL lock.
 9137 */
 9138void netdev_bonding_info_change(struct net_device *dev,
 9139				struct netdev_bonding_info *bonding_info)
 9140{
 9141	struct netdev_notifier_bonding_info info = {
 9142		.info.dev = dev,
 9143	};
 9144
 9145	memcpy(&info.bonding_info, bonding_info,
 9146	       sizeof(struct netdev_bonding_info));
 9147	call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
 9148				      &info.info);
 9149}
 9150EXPORT_SYMBOL(netdev_bonding_info_change);
 9151
 9152static int netdev_offload_xstats_enable_l3(struct net_device *dev,
 9153					   struct netlink_ext_ack *extack)
 9154{
 9155	struct netdev_notifier_offload_xstats_info info = {
 9156		.info.dev = dev,
 9157		.info.extack = extack,
 9158		.type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
 9159	};
 9160	int err;
 9161	int rc;
 9162
 9163	dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
 9164					 GFP_KERNEL);
 9165	if (!dev->offload_xstats_l3)
 9166		return -ENOMEM;
 9167
 9168	rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
 9169						  NETDEV_OFFLOAD_XSTATS_DISABLE,
 9170						  &info.info);
 9171	err = notifier_to_errno(rc);
 9172	if (err)
 9173		goto free_stats;
 9174
 9175	return 0;
 9176
 9177free_stats:
 9178	kfree(dev->offload_xstats_l3);
 9179	dev->offload_xstats_l3 = NULL;
 9180	return err;
 9181}
 9182
 9183int netdev_offload_xstats_enable(struct net_device *dev,
 9184				 enum netdev_offload_xstats_type type,
 9185				 struct netlink_ext_ack *extack)
 9186{
 9187	ASSERT_RTNL();
 9188
 9189	if (netdev_offload_xstats_enabled(dev, type))
 9190		return -EALREADY;
 9191
 9192	switch (type) {
 9193	case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
 9194		return netdev_offload_xstats_enable_l3(dev, extack);
 9195	}
 9196
 9197	WARN_ON(1);
 9198	return -EINVAL;
 9199}
 9200EXPORT_SYMBOL(netdev_offload_xstats_enable);
 9201
 9202static void netdev_offload_xstats_disable_l3(struct net_device *dev)
 9203{
 9204	struct netdev_notifier_offload_xstats_info info = {
 9205		.info.dev = dev,
 9206		.type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
 9207	};
 9208
 9209	call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
 9210				      &info.info);
 9211	kfree(dev->offload_xstats_l3);
 9212	dev->offload_xstats_l3 = NULL;
 9213}
 9214
 9215int netdev_offload_xstats_disable(struct net_device *dev,
 9216				  enum netdev_offload_xstats_type type)
 9217{
 9218	ASSERT_RTNL();
 9219
 9220	if (!netdev_offload_xstats_enabled(dev, type))
 9221		return -EALREADY;
 9222
 9223	switch (type) {
 9224	case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
 9225		netdev_offload_xstats_disable_l3(dev);
 9226		return 0;
 9227	}
 9228
 9229	WARN_ON(1);
 9230	return -EINVAL;
 9231}
 9232EXPORT_SYMBOL(netdev_offload_xstats_disable);
 9233
 9234static void netdev_offload_xstats_disable_all(struct net_device *dev)
 9235{
 9236	netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
 9237}
 9238
 9239static struct rtnl_hw_stats64 *
 9240netdev_offload_xstats_get_ptr(const struct net_device *dev,
 9241			      enum netdev_offload_xstats_type type)
 9242{
 9243	switch (type) {
 9244	case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
 9245		return dev->offload_xstats_l3;
 9246	}
 9247
 9248	WARN_ON(1);
 9249	return NULL;
 9250}
 9251
 9252bool netdev_offload_xstats_enabled(const struct net_device *dev,
 9253				   enum netdev_offload_xstats_type type)
 9254{
 9255	ASSERT_RTNL();
 9256
 9257	return netdev_offload_xstats_get_ptr(dev, type);
 9258}
 9259EXPORT_SYMBOL(netdev_offload_xstats_enabled);
 9260
 9261struct netdev_notifier_offload_xstats_ru {
 9262	bool used;
 9263};
 9264
 9265struct netdev_notifier_offload_xstats_rd {
 9266	struct rtnl_hw_stats64 stats;
 9267	bool used;
 9268};
 9269
 9270static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
 9271				  const struct rtnl_hw_stats64 *src)
 9272{
 9273	dest->rx_packets	  += src->rx_packets;
 9274	dest->tx_packets	  += src->tx_packets;
 9275	dest->rx_bytes		  += src->rx_bytes;
 9276	dest->tx_bytes		  += src->tx_bytes;
 9277	dest->rx_errors		  += src->rx_errors;
 9278	dest->tx_errors		  += src->tx_errors;
 9279	dest->rx_dropped	  += src->rx_dropped;
 9280	dest->tx_dropped	  += src->tx_dropped;
 9281	dest->multicast		  += src->multicast;
 9282}
 9283
 9284static int netdev_offload_xstats_get_used(struct net_device *dev,
 9285					  enum netdev_offload_xstats_type type,
 9286					  bool *p_used,
 9287					  struct netlink_ext_ack *extack)
 9288{
 9289	struct netdev_notifier_offload_xstats_ru report_used = {};
 9290	struct netdev_notifier_offload_xstats_info info = {
 9291		.info.dev = dev,
 9292		.info.extack = extack,
 9293		.type = type,
 9294		.report_used = &report_used,
 9295	};
 9296	int rc;
 9297
 9298	WARN_ON(!netdev_offload_xstats_enabled(dev, type));
 9299	rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
 9300					   &info.info);
 9301	*p_used = report_used.used;
 9302	return notifier_to_errno(rc);
 9303}
 9304
 9305static int netdev_offload_xstats_get_stats(struct net_device *dev,
 9306					   enum netdev_offload_xstats_type type,
 9307					   struct rtnl_hw_stats64 *p_stats,
 9308					   bool *p_used,
 9309					   struct netlink_ext_ack *extack)
 9310{
 9311	struct netdev_notifier_offload_xstats_rd report_delta = {};
 9312	struct netdev_notifier_offload_xstats_info info = {
 9313		.info.dev = dev,
 9314		.info.extack = extack,
 9315		.type = type,
 9316		.report_delta = &report_delta,
 9317	};
 9318	struct rtnl_hw_stats64 *stats;
 9319	int rc;
 9320
 9321	stats = netdev_offload_xstats_get_ptr(dev, type);
 9322	if (WARN_ON(!stats))
 9323		return -EINVAL;
 9324
 9325	rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
 9326					   &info.info);
 9327
 9328	/* Cache whatever we got, even if there was an error, otherwise the
 9329	 * successful stats retrievals would get lost.
 9330	 */
 9331	netdev_hw_stats64_add(stats, &report_delta.stats);
 9332
 9333	if (p_stats)
 9334		*p_stats = *stats;
 9335	*p_used = report_delta.used;
 9336
 9337	return notifier_to_errno(rc);
 9338}
 9339
 9340int netdev_offload_xstats_get(struct net_device *dev,
 9341			      enum netdev_offload_xstats_type type,
 9342			      struct rtnl_hw_stats64 *p_stats, bool *p_used,
 9343			      struct netlink_ext_ack *extack)
 9344{
 9345	ASSERT_RTNL();
 9346
 9347	if (p_stats)
 9348		return netdev_offload_xstats_get_stats(dev, type, p_stats,
 9349						       p_used, extack);
 9350	else
 9351		return netdev_offload_xstats_get_used(dev, type, p_used,
 9352						      extack);
 9353}
 9354EXPORT_SYMBOL(netdev_offload_xstats_get);
 9355
 9356void
 9357netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
 9358				   const struct rtnl_hw_stats64 *stats)
 9359{
 9360	report_delta->used = true;
 9361	netdev_hw_stats64_add(&report_delta->stats, stats);
 9362}
 9363EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
 9364
 9365void
 9366netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
 9367{
 9368	report_used->used = true;
 9369}
 9370EXPORT_SYMBOL(netdev_offload_xstats_report_used);
 9371
 9372void netdev_offload_xstats_push_delta(struct net_device *dev,
 9373				      enum netdev_offload_xstats_type type,
 9374				      const struct rtnl_hw_stats64 *p_stats)
 9375{
 9376	struct rtnl_hw_stats64 *stats;
 9377
 9378	ASSERT_RTNL();
 9379
 9380	stats = netdev_offload_xstats_get_ptr(dev, type);
 9381	if (WARN_ON(!stats))
 9382		return;
 9383
 9384	netdev_hw_stats64_add(stats, p_stats);
 9385}
 9386EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
 9387
 9388/**
 9389 * netdev_get_xmit_slave - Get the xmit slave of master device
 9390 * @dev: device
 9391 * @skb: The packet
 9392 * @all_slaves: assume all the slaves are active
 9393 *
 9394 * The reference counters are not incremented so the caller must be
 9395 * careful with locks. The caller must hold RCU lock.
 9396 * %NULL is returned if no slave is found.
 9397 */
 9398
 9399struct net_device *netdev_get_xmit_slave(struct net_device *dev,
 9400					 struct sk_buff *skb,
 9401					 bool all_slaves)
 9402{
 9403	const struct net_device_ops *ops = dev->netdev_ops;
 9404
 9405	if (!ops->ndo_get_xmit_slave)
 9406		return NULL;
 9407	return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
 9408}
 9409EXPORT_SYMBOL(netdev_get_xmit_slave);
 9410
 9411static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
 9412						  struct sock *sk)
 9413{
 9414	const struct net_device_ops *ops = dev->netdev_ops;
 9415
 9416	if (!ops->ndo_sk_get_lower_dev)
 9417		return NULL;
 9418	return ops->ndo_sk_get_lower_dev(dev, sk);
 9419}
 9420
 9421/**
 9422 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
 9423 * @dev: device
 9424 * @sk: the socket
 9425 *
 9426 * %NULL is returned if no lower device is found.
 9427 */
 9428
 9429struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
 9430					    struct sock *sk)
 9431{
 9432	struct net_device *lower;
 9433
 9434	lower = netdev_sk_get_lower_dev(dev, sk);
 9435	while (lower) {
 9436		dev = lower;
 9437		lower = netdev_sk_get_lower_dev(dev, sk);
 9438	}
 9439
 9440	return dev;
 9441}
 9442EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
 9443
 9444static void netdev_adjacent_add_links(struct net_device *dev)
 9445{
 9446	struct netdev_adjacent *iter;
 9447
 9448	struct net *net = dev_net(dev);
 9449
 9450	list_for_each_entry(iter, &dev->adj_list.upper, list) {
 9451		if (!net_eq(net, dev_net(iter->dev)))
 9452			continue;
 9453		netdev_adjacent_sysfs_add(iter->dev, dev,
 9454					  &iter->dev->adj_list.lower);
 9455		netdev_adjacent_sysfs_add(dev, iter->dev,
 9456					  &dev->adj_list.upper);
 9457	}
 9458
 9459	list_for_each_entry(iter, &dev->adj_list.lower, list) {
 9460		if (!net_eq(net, dev_net(iter->dev)))
 9461			continue;
 9462		netdev_adjacent_sysfs_add(iter->dev, dev,
 9463					  &iter->dev->adj_list.upper);
 9464		netdev_adjacent_sysfs_add(dev, iter->dev,
 9465					  &dev->adj_list.lower);
 9466	}
 9467}
 9468
 9469static void netdev_adjacent_del_links(struct net_device *dev)
 9470{
 9471	struct netdev_adjacent *iter;
 9472
 9473	struct net *net = dev_net(dev);
 9474
 9475	list_for_each_entry(iter, &dev->adj_list.upper, list) {
 9476		if (!net_eq(net, dev_net(iter->dev)))
 9477			continue;
 9478		netdev_adjacent_sysfs_del(iter->dev, dev->name,
 9479					  &iter->dev->adj_list.lower);
 9480		netdev_adjacent_sysfs_del(dev, iter->dev->name,
 9481					  &dev->adj_list.upper);
 9482	}
 9483
 9484	list_for_each_entry(iter, &dev->adj_list.lower, list) {
 9485		if (!net_eq(net, dev_net(iter->dev)))
 9486			continue;
 9487		netdev_adjacent_sysfs_del(iter->dev, dev->name,
 9488					  &iter->dev->adj_list.upper);
 9489		netdev_adjacent_sysfs_del(dev, iter->dev->name,
 9490					  &dev->adj_list.lower);
 9491	}
 9492}
 9493
 9494void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
 9495{
 9496	struct netdev_adjacent *iter;
 9497
 9498	struct net *net = dev_net(dev);
 9499
 9500	list_for_each_entry(iter, &dev->adj_list.upper, list) {
 9501		if (!net_eq(net, dev_net(iter->dev)))
 9502			continue;
 9503		netdev_adjacent_sysfs_del(iter->dev, oldname,
 9504					  &iter->dev->adj_list.lower);
 9505		netdev_adjacent_sysfs_add(iter->dev, dev,
 9506					  &iter->dev->adj_list.lower);
 9507	}
 9508
 9509	list_for_each_entry(iter, &dev->adj_list.lower, list) {
 9510		if (!net_eq(net, dev_net(iter->dev)))
 9511			continue;
 9512		netdev_adjacent_sysfs_del(iter->dev, oldname,
 9513					  &iter->dev->adj_list.upper);
 9514		netdev_adjacent_sysfs_add(iter->dev, dev,
 9515					  &iter->dev->adj_list.upper);
 9516	}
 9517}
 9518
 9519void *netdev_lower_dev_get_private(struct net_device *dev,
 9520				   struct net_device *lower_dev)
 9521{
 9522	struct netdev_adjacent *lower;
 9523
 9524	if (!lower_dev)
 9525		return NULL;
 9526	lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
 9527	if (!lower)
 9528		return NULL;
 9529
 9530	return lower->private;
 9531}
 9532EXPORT_SYMBOL(netdev_lower_dev_get_private);
 9533
 9534
 9535/**
 9536 * netdev_lower_state_changed - Dispatch event about lower device state change
 9537 * @lower_dev: device
 9538 * @lower_state_info: state to dispatch
 9539 *
 9540 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
 9541 * The caller must hold the RTNL lock.
 9542 */
 9543void netdev_lower_state_changed(struct net_device *lower_dev,
 9544				void *lower_state_info)
 9545{
 9546	struct netdev_notifier_changelowerstate_info changelowerstate_info = {
 9547		.info.dev = lower_dev,
 9548	};
 9549
 9550	ASSERT_RTNL();
 9551	changelowerstate_info.lower_state_info = lower_state_info;
 9552	call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
 9553				      &changelowerstate_info.info);
 9554}
 9555EXPORT_SYMBOL(netdev_lower_state_changed);
 9556
 9557static void dev_change_rx_flags(struct net_device *dev, int flags)
 9558{
 9559	const struct net_device_ops *ops = dev->netdev_ops;
 9560
 9561	if (ops->ndo_change_rx_flags)
 9562		ops->ndo_change_rx_flags(dev, flags);
 9563}
 9564
 9565static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
 9566{
 9567	unsigned int old_flags = dev->flags;
 9568	unsigned int promiscuity, flags;
 9569	kuid_t uid;
 9570	kgid_t gid;
 9571
 9572	ASSERT_RTNL();
 9573
 9574	promiscuity = dev->promiscuity + inc;
 9575	if (promiscuity == 0) {
 9576		/*
 9577		 * Avoid overflow.
 9578		 * If inc causes overflow, untouch promisc and return error.
 9579		 */
 9580		if (unlikely(inc > 0)) {
 9581			netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
 9582			return -EOVERFLOW;
 9583		}
 9584		flags = old_flags & ~IFF_PROMISC;
 9585	} else {
 9586		flags = old_flags | IFF_PROMISC;
 9587	}
 9588	WRITE_ONCE(dev->promiscuity, promiscuity);
 9589	if (flags != old_flags) {
 9590		WRITE_ONCE(dev->flags, flags);
 9591		netdev_info(dev, "%s promiscuous mode\n",
 9592			    dev->flags & IFF_PROMISC ? "entered" : "left");
 9593		if (audit_enabled) {
 9594			current_uid_gid(&uid, &gid);
 9595			audit_log(audit_context(), GFP_ATOMIC,
 9596				  AUDIT_ANOM_PROMISCUOUS,
 9597				  "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
 9598				  dev->name, (dev->flags & IFF_PROMISC),
 9599				  (old_flags & IFF_PROMISC),
 9600				  from_kuid(&init_user_ns, audit_get_loginuid(current)),
 9601				  from_kuid(&init_user_ns, uid),
 9602				  from_kgid(&init_user_ns, gid),
 9603				  audit_get_sessionid(current));
 9604		}
 9605
 9606		dev_change_rx_flags(dev, IFF_PROMISC);
 9607	}
 9608	if (notify) {
 9609		/* The ops lock is only required to ensure consistent locking
 9610		 * for `NETDEV_CHANGE` notifiers. This function is sometimes
 9611		 * called without the lock, even for devices that are ops
 9612		 * locked, such as in `dev_uc_sync_multiple` when using
 9613		 * bonding or teaming.
 9614		 */
 9615		netdev_ops_assert_locked(dev);
 9616		__dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL);
 9617	}
 9618	return 0;
 9619}
 9620
 9621int netif_set_promiscuity(struct net_device *dev, int inc)
 9622{
 9623	unsigned int old_flags = dev->flags;
 9624	int err;
 9625
 9626	err = __dev_set_promiscuity(dev, inc, true);
 9627	if (err < 0)
 9628		return err;
 9629	if (dev->flags != old_flags)
 9630		dev_set_rx_mode(dev);
 9631	return err;
 9632}
 9633
 9634int netif_set_allmulti(struct net_device *dev, int inc, bool notify)
 9635{
 9636	unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
 9637	unsigned int allmulti, flags;
 9638
 9639	ASSERT_RTNL();
 9640
 9641	allmulti = dev->allmulti + inc;
 9642	if (allmulti == 0) {
 9643		/*
 9644		 * Avoid overflow.
 9645		 * If inc causes overflow, untouch allmulti and return error.
 9646		 */
 9647		if (unlikely(inc > 0)) {
 9648			netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
 9649			return -EOVERFLOW;
 9650		}
 9651		flags = old_flags & ~IFF_ALLMULTI;
 9652	} else {
 9653		flags = old_flags | IFF_ALLMULTI;
 9654	}
 9655	WRITE_ONCE(dev->allmulti, allmulti);
 9656	if (flags != old_flags) {
 9657		WRITE_ONCE(dev->flags, flags);
 9658		netdev_info(dev, "%s allmulticast mode\n",
 9659			    dev->flags & IFF_ALLMULTI ? "entered" : "left");
 9660		dev_change_rx_flags(dev, IFF_ALLMULTI);
 9661		dev_set_rx_mode(dev);
 9662		if (notify)
 9663			__dev_notify_flags(dev, old_flags,
 9664					   dev->gflags ^ old_gflags, 0, NULL);
 9665	}
 9666	return 0;
 9667}
 9668
 9669/*
 9670 *	Upload unicast and multicast address lists to device and
 9671 *	configure RX filtering. When the device doesn't support unicast
 9672 *	filtering it is put in promiscuous mode while unicast addresses
 9673 *	are present.
 9674 */
 9675void __dev_set_rx_mode(struct net_device *dev)
 9676{
 9677	const struct net_device_ops *ops = dev->netdev_ops;
 9678
 9679	/* dev_open will call this function so the list will stay sane. */
 9680	if (!(dev->flags&IFF_UP))
 9681		return;
 9682
 9683	if (!netif_device_present(dev))
 9684		return;
 9685
 9686	if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
 9687		/* Unicast addresses changes may only happen under the rtnl,
 9688		 * therefore calling __dev_set_promiscuity here is safe.
 9689		 */
 9690		if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
 9691			__dev_set_promiscuity(dev, 1, false);
 9692			dev->uc_promisc = true;
 9693		} else if (netdev_uc_empty(dev) && dev->uc_promisc) {
 9694			__dev_set_promiscuity(dev, -1, false);
 9695			dev->uc_promisc = false;
 9696		}
 9697	}
 9698
 9699	if (ops->ndo_set_rx_mode)
 9700		ops->ndo_set_rx_mode(dev);
 9701}
 9702
 9703void dev_set_rx_mode(struct net_device *dev)
 9704{
 9705	netif_addr_lock_bh(dev);
 9706	__dev_set_rx_mode(dev);
 9707	netif_addr_unlock_bh(dev);
 9708}
 9709
 9710/**
 9711 * netif_get_flags() - get flags reported to userspace
 9712 * @dev: device
 9713 *
 9714 * Get the combination of flag bits exported through APIs to userspace.
 9715 */
 9716unsigned int netif_get_flags(const struct net_device *dev)
 9717{
 9718	unsigned int flags;
 9719
 9720	flags = (READ_ONCE(dev->flags) & ~(IFF_PROMISC |
 9721				IFF_ALLMULTI |
 9722				IFF_RUNNING |
 9723				IFF_LOWER_UP |
 9724				IFF_DORMANT)) |
 9725		(READ_ONCE(dev->gflags) & (IFF_PROMISC |
 9726				IFF_ALLMULTI));
 9727
 9728	if (netif_running(dev)) {
 9729		if (netif_oper_up(dev))
 9730			flags |= IFF_RUNNING;
 9731		if (netif_carrier_ok(dev))
 9732			flags |= IFF_LOWER_UP;
 9733		if (netif_dormant(dev))
 9734			flags |= IFF_DORMANT;
 9735	}
 9736
 9737	return flags;
 9738}
 9739EXPORT_SYMBOL(netif_get_flags);
 9740
 9741int __dev_change_flags(struct net_device *dev, unsigned int flags,
 9742		       struct netlink_ext_ack *extack)
 9743{
 9744	unsigned int old_flags = dev->flags;
 9745	int ret;
 9746
 9747	ASSERT_RTNL();
 9748
 9749	/*
 9750	 *	Set the flags on our device.
 9751	 */
 9752
 9753	dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
 9754			       IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
 9755			       IFF_AUTOMEDIA)) |
 9756		     (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
 9757				    IFF_ALLMULTI));
 9758
 9759	/*
 9760	 *	Load in the correct multicast list now the flags have changed.
 9761	 */
 9762
 9763	if ((old_flags ^ flags) & IFF_MULTICAST)
 9764		dev_change_rx_flags(dev, IFF_MULTICAST);
 9765
 9766	dev_set_rx_mode(dev);
 9767
 9768	/*
 9769	 *	Have we downed the interface. We handle IFF_UP ourselves
 9770	 *	according to user attempts to set it, rather than blindly
 9771	 *	setting it.
 9772	 */
 9773
 9774	ret = 0;
 9775	if ((old_flags ^ flags) & IFF_UP) {
 9776		if (old_flags & IFF_UP)
 9777			__dev_close(dev);
 9778		else
 9779			ret = __dev_open(dev, extack);
 9780	}
 9781
 9782	if ((flags ^ dev->gflags) & IFF_PROMISC) {
 9783		int inc = (flags & IFF_PROMISC) ? 1 : -1;
 9784		old_flags = dev->flags;
 9785
 9786		dev->gflags ^= IFF_PROMISC;
 9787
 9788		if (__dev_set_promiscuity(dev, inc, false) >= 0)
 9789			if (dev->flags != old_flags)
 9790				dev_set_rx_mode(dev);
 9791	}
 9792
 9793	/* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
 9794	 * is important. Some (broken) drivers set IFF_PROMISC, when
 9795	 * IFF_ALLMULTI is requested not asking us and not reporting.
 9796	 */
 9797	if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
 9798		int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
 9799
 9800		dev->gflags ^= IFF_ALLMULTI;
 9801		netif_set_allmulti(dev, inc, false);
 9802	}
 9803
 9804	return ret;
 9805}
 9806
 9807void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
 9808			unsigned int gchanges, u32 portid,
 9809			const struct nlmsghdr *nlh)
 9810{
 9811	unsigned int changes = dev->flags ^ old_flags;
 9812
 9813	if (gchanges)
 9814		rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh);
 9815
 9816	if (changes & IFF_UP) {
 9817		if (dev->flags & IFF_UP)
 9818			call_netdevice_notifiers(NETDEV_UP, dev);
 9819		else
 9820			call_netdevice_notifiers(NETDEV_DOWN, dev);
 9821	}
 9822
 9823	if (dev->flags & IFF_UP &&
 9824	    (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
 9825		struct netdev_notifier_change_info change_info = {
 9826			.info = {
 9827				.dev = dev,
 9828			},
 9829			.flags_changed = changes,
 9830		};
 9831
 9832		call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
 9833	}
 9834}
 9835
 9836int netif_change_flags(struct net_device *dev, unsigned int flags,
 9837		       struct netlink_ext_ack *extack)
 9838{
 9839	int ret;
 9840	unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
 9841
 9842	ret = __dev_change_flags(dev, flags, extack);
 9843	if (ret < 0)
 9844		return ret;
 9845
 9846	changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
 9847	__dev_notify_flags(dev, old_flags, changes, 0, NULL);
 9848	return ret;
 9849}
 9850
 9851int __netif_set_mtu(struct net_device *dev, int new_mtu)
 9852{
 9853	const struct net_device_ops *ops = dev->netdev_ops;
 9854
 9855	if (ops->ndo_change_mtu)
 9856		return ops->ndo_change_mtu(dev, new_mtu);
 9857
 9858	/* Pairs with all the lockless reads of dev->mtu in the stack */
 9859	WRITE_ONCE(dev->mtu, new_mtu);
 9860	return 0;
 9861}
 9862EXPORT_SYMBOL_NS_GPL(__netif_set_mtu, "NETDEV_INTERNAL");
 9863
 9864int dev_validate_mtu(struct net_device *dev, int new_mtu,
 9865		     struct netlink_ext_ack *extack)
 9866{
 9867	/* MTU must be positive, and in range */
 9868	if (new_mtu < 0 || new_mtu < dev->min_mtu) {
 9869		NL_SET_ERR_MSG(extack, "mtu less than device minimum");
 9870		return -EINVAL;
 9871	}
 9872
 9873	if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
 9874		NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
 9875		return -EINVAL;
 9876	}
 9877	return 0;
 9878}
 9879
 9880/**
 9881 * netif_set_mtu_ext() - Change maximum transfer unit
 9882 * @dev: device
 9883 * @new_mtu: new transfer unit
 9884 * @extack: netlink extended ack
 9885 *
 9886 * Change the maximum transfer size of the network device.
 9887 *
 9888 * Return: 0 on success, -errno on failure.
 9889 */
 9890int netif_set_mtu_ext(struct net_device *dev, int new_mtu,
 9891		      struct netlink_ext_ack *extack)
 9892{
 9893	int err, orig_mtu;
 9894
 9895	netdev_ops_assert_locked(dev);
 9896
 9897	if (new_mtu == dev->mtu)
 9898		return 0;
 9899
 9900	err = dev_validate_mtu(dev, new_mtu, extack);
 9901	if (err)
 9902		return err;
 9903
 9904	if (!netif_device_present(dev))
 9905		return -ENODEV;
 9906
 9907	err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
 9908	err = notifier_to_errno(err);
 9909	if (err)
 9910		return err;
 9911
 9912	orig_mtu = dev->mtu;
 9913	err = __netif_set_mtu(dev, new_mtu);
 9914
 9915	if (!err) {
 9916		err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
 9917						   orig_mtu);
 9918		err = notifier_to_errno(err);
 9919		if (err) {
 9920			/* setting mtu back and notifying everyone again,
 9921			 * so that they have a chance to revert changes.
 9922			 */
 9923			__netif_set_mtu(dev, orig_mtu);
 9924			call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
 9925						     new_mtu);
 9926		}
 9927	}
 9928	return err;
 9929}
 9930
 9931int netif_set_mtu(struct net_device *dev, int new_mtu)
 9932{
 9933	struct netlink_ext_ack extack;
 9934	int err;
 9935
 9936	memset(&extack, 0, sizeof(extack));
 9937	err = netif_set_mtu_ext(dev, new_mtu, &extack);
 9938	if (err && extack._msg)
 9939		net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
 9940	return err;
 9941}
 9942EXPORT_SYMBOL(netif_set_mtu);
 9943
 9944int netif_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
 9945{
 9946	unsigned int orig_len = dev->tx_queue_len;
 9947	int res;
 9948
 9949	if (new_len != (unsigned int)new_len)
 9950		return -ERANGE;
 9951
 9952	if (new_len != orig_len) {
 9953		WRITE_ONCE(dev->tx_queue_len, new_len);
 9954		res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
 9955		res = notifier_to_errno(res);
 9956		if (res)
 9957			goto err_rollback;
 9958		res = dev_qdisc_change_tx_queue_len(dev);
 9959		if (res)
 9960			goto err_rollback;
 9961	}
 9962
 9963	return 0;
 9964
 9965err_rollback:
 9966	netdev_err(dev, "refused to change device tx_queue_len\n");
 9967	WRITE_ONCE(dev->tx_queue_len, orig_len);
 9968	return res;
 9969}
 9970
 9971void netif_set_group(struct net_device *dev, int new_group)
 9972{
 9973	dev->group = new_group;
 9974}
 9975
 9976/**
 9977 * netif_pre_changeaddr_notify() - Call NETDEV_PRE_CHANGEADDR.
 9978 * @dev: device
 9979 * @addr: new address
 9980 * @extack: netlink extended ack
 9981 *
 9982 * Return: 0 on success, -errno on failure.
 9983 */
 9984int netif_pre_changeaddr_notify(struct net_device *dev, const char *addr,
 9985				struct netlink_ext_ack *extack)
 9986{
 9987	struct netdev_notifier_pre_changeaddr_info info = {
 9988		.info.dev = dev,
 9989		.info.extack = extack,
 9990		.dev_addr = addr,
 9991	};
 9992	int rc;
 9993
 9994	rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
 9995	return notifier_to_errno(rc);
 9996}
 9997EXPORT_SYMBOL_NS_GPL(netif_pre_changeaddr_notify, "NETDEV_INTERNAL");
 9998
 9999int netif_set_mac_address(struct net_device *dev, struct sockaddr_storage *ss,
10000			  struct netlink_ext_ack *extack)
10001{
10002	const struct net_device_ops *ops = dev->netdev_ops;
10003	int err;
10004
10005	if (!ops->ndo_set_mac_address)
10006		return -EOPNOTSUPP;
10007	if (ss->ss_family != dev->type)
10008		return -EINVAL;
10009	if (!netif_device_present(dev))
10010		return -ENODEV;
10011	err = netif_pre_changeaddr_notify(dev, ss->__data, extack);
10012	if (err)
10013		return err;
10014	if (memcmp(dev->dev_addr, ss->__data, dev->addr_len)) {
10015		err = ops->ndo_set_mac_address(dev, ss);
10016		if (err)
10017			return err;
10018	}
10019	dev->addr_assign_type = NET_ADDR_SET;
10020	call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
10021	add_device_randomness(dev->dev_addr, dev->addr_len);
10022	return 0;
10023}
10024
10025DECLARE_RWSEM(dev_addr_sem);
10026
10027/* "sa" is a true struct sockaddr with limited "sa_data" member. */
10028int netif_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
10029{
10030	size_t size = sizeof(sa->sa_data);
10031	struct net_device *dev;
10032	int ret = 0;
10033
10034	down_read(&dev_addr_sem);
10035	rcu_read_lock();
10036
10037	dev = dev_get_by_name_rcu(net, dev_name);
10038	if (!dev) {
10039		ret = -ENODEV;
10040		goto unlock;
10041	}
10042	if (!dev->addr_len)
10043		memset(sa->sa_data, 0, size);
10044	else
10045		memcpy(sa->sa_data, dev->dev_addr,
10046		       min_t(size_t, size, dev->addr_len));
10047	sa->sa_family = dev->type;
10048
10049unlock:
10050	rcu_read_unlock();
10051	up_read(&dev_addr_sem);
10052	return ret;
10053}
10054EXPORT_SYMBOL_NS_GPL(netif_get_mac_address, "NETDEV_INTERNAL");
10055
10056int netif_change_carrier(struct net_device *dev, bool new_carrier)
10057{
10058	const struct net_device_ops *ops = dev->netdev_ops;
10059
10060	if (!ops->ndo_change_carrier)
10061		return -EOPNOTSUPP;
10062	if (!netif_device_present(dev))
10063		return -ENODEV;
10064	return ops->ndo_change_carrier(dev, new_carrier);
10065}
10066
10067/**
10068 *	dev_get_phys_port_id - Get device physical port ID
10069 *	@dev: device
10070 *	@ppid: port ID
10071 *
10072 *	Get device physical port ID
10073 */
10074int dev_get_phys_port_id(struct net_device *dev,
10075			 struct netdev_phys_item_id *ppid)
10076{
10077	const struct net_device_ops *ops = dev->netdev_ops;
10078
10079	if (!ops->ndo_get_phys_port_id)
10080		return -EOPNOTSUPP;
10081	return ops->ndo_get_phys_port_id(dev, ppid);
10082}
10083
10084/**
10085 *	dev_get_phys_port_name - Get device physical port name
10086 *	@dev: device
10087 *	@name: port name
10088 *	@len: limit of bytes to copy to name
10089 *
10090 *	Get device physical port name
10091 */
10092int dev_get_phys_port_name(struct net_device *dev,
10093			   char *name, size_t len)
10094{
10095	const struct net_device_ops *ops = dev->netdev_ops;
10096	int err;
10097
10098	if (ops->ndo_get_phys_port_name) {
10099		err = ops->ndo_get_phys_port_name(dev, name, len);
10100		if (err != -EOPNOTSUPP)
10101			return err;
10102	}
10103	return devlink_compat_phys_port_name_get(dev, name, len);
10104}
10105
10106/**
10107 * netif_get_port_parent_id() - Get the device's port parent identifier
10108 * @dev: network device
10109 * @ppid: pointer to a storage for the port's parent identifier
10110 * @recurse: allow/disallow recursion to lower devices
10111 *
10112 * Get the devices's port parent identifier.
10113 *
10114 * Return: 0 on success, -errno on failure.
10115 */
10116int netif_get_port_parent_id(struct net_device *dev,
10117			     struct netdev_phys_item_id *ppid, bool recurse)
10118{
10119	const struct net_device_ops *ops = dev->netdev_ops;
10120	struct netdev_phys_item_id first = { };
10121	struct net_device *lower_dev;
10122	struct list_head *iter;
10123	int err;
10124
10125	if (ops->ndo_get_port_parent_id) {
10126		err = ops->ndo_get_port_parent_id(dev, ppid);
10127		if (err != -EOPNOTSUPP)
10128			return err;
10129	}
10130
10131	err = devlink_compat_switch_id_get(dev, ppid);
10132	if (!recurse || err != -EOPNOTSUPP)
10133		return err;
10134
10135	netdev_for_each_lower_dev(dev, lower_dev, iter) {
10136		err = netif_get_port_parent_id(lower_dev, ppid, true);
10137		if (err)
10138			break;
10139		if (!first.id_len)
10140			first = *ppid;
10141		else if (memcmp(&first, ppid, sizeof(*ppid)))
10142			return -EOPNOTSUPP;
10143	}
10144
10145	return err;
10146}
10147EXPORT_SYMBOL(netif_get_port_parent_id);
10148
10149/**
10150 *	netdev_port_same_parent_id - Indicate if two network devices have
10151 *	the same port parent identifier
10152 *	@a: first network device
10153 *	@b: second network device
10154 */
10155bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
10156{
10157	struct netdev_phys_item_id a_id = { };
10158	struct netdev_phys_item_id b_id = { };
10159
10160	if (netif_get_port_parent_id(a, &a_id, true) ||
10161	    netif_get_port_parent_id(b, &b_id, true))
10162		return false;
10163
10164	return netdev_phys_item_id_same(&a_id, &b_id);
10165}
10166EXPORT_SYMBOL(netdev_port_same_parent_id);
10167
10168int netif_change_proto_down(struct net_device *dev, bool proto_down)
10169{
10170	if (!dev->change_proto_down)
10171		return -EOPNOTSUPP;
10172	if (!netif_device_present(dev))
10173		return -ENODEV;
10174	if (proto_down)
10175		netif_carrier_off(dev);
10176	else
10177		netif_carrier_on(dev);
10178	WRITE_ONCE(dev->proto_down, proto_down);
10179	return 0;
10180}
10181
10182/**
10183 *	netdev_change_proto_down_reason_locked - proto down reason
10184 *
10185 *	@dev: device
10186 *	@mask: proto down mask
10187 *	@value: proto down value
10188 */
10189void netdev_change_proto_down_reason_locked(struct net_device *dev,
10190					    unsigned long mask, u32 value)
10191{
10192	u32 proto_down_reason;
10193	int b;
10194
10195	if (!mask) {
10196		proto_down_reason = value;
10197	} else {
10198		proto_down_reason = dev->proto_down_reason;
10199		for_each_set_bit(b, &mask, 32) {
10200			if (value & (1 << b))
10201				proto_down_reason |= BIT(b);
10202			else
10203				proto_down_reason &= ~BIT(b);
10204		}
10205	}
10206	WRITE_ONCE(dev->proto_down_reason, proto_down_reason);
10207}
10208
10209struct bpf_xdp_link {
10210	struct bpf_link link;
10211	struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
10212	int flags;
10213};
10214
10215static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
10216{
10217	if (flags & XDP_FLAGS_HW_MODE)
10218		return XDP_MODE_HW;
10219	if (flags & XDP_FLAGS_DRV_MODE)
10220		return XDP_MODE_DRV;
10221	if (flags & XDP_FLAGS_SKB_MODE)
10222		return XDP_MODE_SKB;
10223	return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
10224}
10225
10226static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
10227{
10228	switch (mode) {
10229	case XDP_MODE_SKB:
10230		return generic_xdp_install;
10231	case XDP_MODE_DRV:
10232	case XDP_MODE_HW:
10233		return dev->netdev_ops->ndo_bpf;
10234	default:
10235		return NULL;
10236	}
10237}
10238
10239static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
10240					 enum bpf_xdp_mode mode)
10241{
10242	return dev->xdp_state[mode].link;
10243}
10244
10245static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
10246				     enum bpf_xdp_mode mode)
10247{
10248	struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
10249
10250	if (link)
10251		return link->link.prog;
10252	return dev->xdp_state[mode].prog;
10253}
10254
10255u8 dev_xdp_prog_count(struct net_device *dev)
10256{
10257	u8 count = 0;
10258	int i;
10259
10260	for (i = 0; i < __MAX_XDP_MODE; i++)
10261		if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
10262			count++;
10263	return count;
10264}
10265EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
10266
10267u8 dev_xdp_sb_prog_count(struct net_device *dev)
10268{
10269	u8 count = 0;
10270	int i;
10271
10272	for (i = 0; i < __MAX_XDP_MODE; i++)
10273		if (dev->xdp_state[i].prog &&
10274		    !dev->xdp_state[i].prog->aux->xdp_has_frags)
10275			count++;
10276	return count;
10277}
10278
10279int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
10280{
10281	if (!dev->netdev_ops->ndo_bpf)
10282		return -EOPNOTSUPP;
10283
10284	if (dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED &&
10285	    bpf->command == XDP_SETUP_PROG &&
10286	    bpf->prog && !bpf->prog->aux->xdp_has_frags) {
10287		NL_SET_ERR_MSG(bpf->extack,
10288			       "unable to propagate XDP to device using tcp-data-split");
10289		return -EBUSY;
10290	}
10291
10292	if (dev_get_min_mp_channel_count(dev)) {
10293		NL_SET_ERR_MSG(bpf->extack, "unable to propagate XDP to device using memory provider");
10294		return -EBUSY;
10295	}
10296
10297	return dev->netdev_ops->ndo_bpf(dev, bpf);
10298}
10299EXPORT_SYMBOL_GPL(netif_xdp_propagate);
10300
10301u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
10302{
10303	struct bpf_prog *prog = dev_xdp_prog(dev, mode);
10304
10305	return prog ? prog->aux->id : 0;
10306}
10307
10308static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
10309			     struct bpf_xdp_link *link)
10310{
10311	dev->xdp_state[mode].link = link;
10312	dev->xdp_state[mode].prog = NULL;
10313}
10314
10315static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
10316			     struct bpf_prog *prog)
10317{
10318	dev->xdp_state[mode].link = NULL;
10319	dev->xdp_state[mode].prog = prog;
10320}
10321
10322static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
10323			   bpf_op_t bpf_op, struct netlink_ext_ack *extack,
10324			   u32 flags, struct bpf_prog *prog)
10325{
10326	struct netdev_bpf xdp;
10327	int err;
10328
10329	netdev_ops_assert_locked(dev);
10330
10331	if (dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED &&
10332	    prog && !prog->aux->xdp_has_frags) {
10333		NL_SET_ERR_MSG(extack, "unable to install XDP to device using tcp-data-split");
10334		return -EBUSY;
10335	}
10336
10337	if (dev_get_min_mp_channel_count(dev)) {
10338		NL_SET_ERR_MSG(extack, "unable to install XDP to device using memory provider");
10339		return -EBUSY;
10340	}
10341
10342	memset(&xdp, 0, sizeof(xdp));
10343	xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
10344	xdp.extack = extack;
10345	xdp.flags = flags;
10346	xdp.prog = prog;
10347
10348	/* Drivers assume refcnt is already incremented (i.e, prog pointer is
10349	 * "moved" into driver), so they don't increment it on their own, but
10350	 * they do decrement refcnt when program is detached or replaced.
10351	 * Given net_device also owns link/prog, we need to bump refcnt here
10352	 * to prevent drivers from underflowing it.
10353	 */
10354	if (prog)
10355		bpf_prog_inc(prog);
10356	err = bpf_op(dev, &xdp);
10357	if (err) {
10358		if (prog)
10359			bpf_prog_put(prog);
10360		return err;
10361	}
10362
10363	if (mode != XDP_MODE_HW)
10364		bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
10365
10366	return 0;
10367}
10368
10369static void dev_xdp_uninstall(struct net_device *dev)
10370{
10371	struct bpf_xdp_link *link;
10372	struct bpf_prog *prog;
10373	enum bpf_xdp_mode mode;
10374	bpf_op_t bpf_op;
10375
10376	ASSERT_RTNL();
10377
10378	for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
10379		prog = dev_xdp_prog(dev, mode);
10380		if (!prog)
10381			continue;
10382
10383		bpf_op = dev_xdp_bpf_op(dev, mode);
10384		if (!bpf_op)
10385			continue;
10386
10387		WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
10388
10389		/* auto-detach link from net device */
10390		link = dev_xdp_link(dev, mode);
10391		if (link)
10392			link->dev = NULL;
10393		else
10394			bpf_prog_put(prog);
10395
10396		dev_xdp_set_link(dev, mode, NULL);
10397	}
10398}
10399
10400static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
10401			  struct bpf_xdp_link *link, struct bpf_prog *new_prog,
10402			  struct bpf_prog *old_prog, u32 flags)
10403{
10404	unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
10405	struct bpf_prog *cur_prog;
10406	struct net_device *upper;
10407	struct list_head *iter;
10408	enum bpf_xdp_mode mode;
10409	bpf_op_t bpf_op;
10410	int err;
10411
10412	ASSERT_RTNL();
10413
10414	/* either link or prog attachment, never both */
10415	if (link && (new_prog || old_prog))
10416		return -EINVAL;
10417	/* link supports only XDP mode flags */
10418	if (link && (flags & ~XDP_FLAGS_MODES)) {
10419		NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
10420		return -EINVAL;
10421	}
10422	/* just one XDP mode bit should be set, zero defaults to drv/skb mode */
10423	if (num_modes > 1) {
10424		NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
10425		return -EINVAL;
10426	}
10427	/* avoid ambiguity if offload + drv/skb mode progs are both loaded */
10428	if (!num_modes && dev_xdp_prog_count(dev) > 1) {
10429		NL_SET_ERR_MSG(extack,
10430			       "More than one program loaded, unset mode is ambiguous");
10431		return -EINVAL;
10432	}
10433	/* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
10434	if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
10435		NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
10436		return -EINVAL;
10437	}
10438
10439	mode = dev_xdp_mode(dev, flags);
10440	/* can't replace attached link */
10441	if (dev_xdp_link(dev, mode)) {
10442		NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
10443		return -EBUSY;
10444	}
10445
10446	/* don't allow if an upper device already has a program */
10447	netdev_for_each_upper_dev_rcu(dev, upper, iter) {
10448		if (dev_xdp_prog_count(upper) > 0) {
10449			NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
10450			return -EEXIST;
10451		}
10452	}
10453
10454	cur_prog = dev_xdp_prog(dev, mode);
10455	/* can't replace attached prog with link */
10456	if (link && cur_prog) {
10457		NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
10458		return -EBUSY;
10459	}
10460	if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
10461		NL_SET_ERR_MSG(extack, "Active program does not match expected");
10462		return -EEXIST;
10463	}
10464
10465	/* put effective new program into new_prog */
10466	if (link)
10467		new_prog = link->link.prog;
10468
10469	if (new_prog) {
10470		bool offload = mode == XDP_MODE_HW;
10471		enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
10472					       ? XDP_MODE_DRV : XDP_MODE_SKB;
10473
10474		if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
10475			NL_SET_ERR_MSG(extack, "XDP program already attached");
10476			return -EBUSY;
10477		}
10478		if (!offload && dev_xdp_prog(dev, other_mode)) {
10479			NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
10480			return -EEXIST;
10481		}
10482		if (!offload && bpf_prog_is_offloaded(new_prog->aux)) {
10483			NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
10484			return -EINVAL;
10485		}
10486		if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) {
10487			NL_SET_ERR_MSG(extack, "Program bound to different device");
10488			return -EINVAL;
10489		}
10490		if (bpf_prog_is_dev_bound(new_prog->aux) && mode == XDP_MODE_SKB) {
10491			NL_SET_ERR_MSG(extack, "Can't attach device-bound programs in generic mode");
10492			return -EINVAL;
10493		}
10494		if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
10495			NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
10496			return -EINVAL;
10497		}
10498		if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
10499			NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
10500			return -EINVAL;
10501		}
10502	}
10503
10504	/* don't call drivers if the effective program didn't change */
10505	if (new_prog != cur_prog) {
10506		bpf_op = dev_xdp_bpf_op(dev, mode);
10507		if (!bpf_op) {
10508			NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
10509			return -EOPNOTSUPP;
10510		}
10511
10512		err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
10513		if (err)
10514			return err;
10515	}
10516
10517	if (link)
10518		dev_xdp_set_link(dev, mode, link);
10519	else
10520		dev_xdp_set_prog(dev, mode, new_prog);
10521	if (cur_prog)
10522		bpf_prog_put(cur_prog);
10523
10524	return 0;
10525}
10526
10527static int dev_xdp_attach_link(struct net_device *dev,
10528			       struct netlink_ext_ack *extack,
10529			       struct bpf_xdp_link *link)
10530{
10531	return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
10532}
10533
10534static int dev_xdp_detach_link(struct net_device *dev,
10535			       struct netlink_ext_ack *extack,
10536			       struct bpf_xdp_link *link)
10537{
10538	enum bpf_xdp_mode mode;
10539	bpf_op_t bpf_op;
10540
10541	ASSERT_RTNL();
10542
10543	mode = dev_xdp_mode(dev, link->flags);
10544	if (dev_xdp_link(dev, mode) != link)
10545		return -EINVAL;
10546
10547	bpf_op = dev_xdp_bpf_op(dev, mode);
10548	WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
10549	dev_xdp_set_link(dev, mode, NULL);
10550	return 0;
10551}
10552
10553static void bpf_xdp_link_release(struct bpf_link *link)
10554{
10555	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
10556
10557	rtnl_lock();
10558
10559	/* if racing with net_device's tear down, xdp_link->dev might be
10560	 * already NULL, in which case link was already auto-detached
10561	 */
10562	if (xdp_link->dev) {
10563		netdev_lock_ops(xdp_link->dev);
10564		WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
10565		netdev_unlock_ops(xdp_link->dev);
10566		xdp_link->dev = NULL;
10567	}
10568
10569	rtnl_unlock();
10570}
10571
10572static int bpf_xdp_link_detach(struct bpf_link *link)
10573{
10574	bpf_xdp_link_release(link);
10575	return 0;
10576}
10577
10578static void bpf_xdp_link_dealloc(struct bpf_link *link)
10579{
10580	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
10581
10582	kfree(xdp_link);
10583}
10584
10585static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
10586				     struct seq_file *seq)
10587{
10588	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
10589	u32 ifindex = 0;
10590
10591	rtnl_lock();
10592	if (xdp_link->dev)
10593		ifindex = xdp_link->dev->ifindex;
10594	rtnl_unlock();
10595
10596	seq_printf(seq, "ifindex:\t%u\n", ifindex);
10597}
10598
10599static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
10600				       struct bpf_link_info *info)
10601{
10602	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
10603	u32 ifindex = 0;
10604
10605	rtnl_lock();
10606	if (xdp_link->dev)
10607		ifindex = xdp_link->dev->ifindex;
10608	rtnl_unlock();
10609
10610	info->xdp.ifindex = ifindex;
10611	return 0;
10612}
10613
10614static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
10615			       struct bpf_prog *old_prog)
10616{
10617	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
10618	enum bpf_xdp_mode mode;
10619	bpf_op_t bpf_op;
10620	int err = 0;
10621
10622	rtnl_lock();
10623
10624	/* link might have been auto-released already, so fail */
10625	if (!xdp_link->dev) {
10626		err = -ENOLINK;
10627		goto out_unlock;
10628	}
10629
10630	if (old_prog && link->prog != old_prog) {
10631		err = -EPERM;
10632		goto out_unlock;
10633	}
10634	old_prog = link->prog;
10635	if (old_prog->type != new_prog->type ||
10636	    old_prog->expected_attach_type != new_prog->expected_attach_type) {
10637		err = -EINVAL;
10638		goto out_unlock;
10639	}
10640
10641	if (old_prog == new_prog) {
10642		/* no-op, don't disturb drivers */
10643		bpf_prog_put(new_prog);
10644		goto out_unlock;
10645	}
10646
10647	netdev_lock_ops(xdp_link->dev);
10648	mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
10649	bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
10650	err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
10651			      xdp_link->flags, new_prog);
10652	netdev_unlock_ops(xdp_link->dev);
10653	if (err)
10654		goto out_unlock;
10655
10656	old_prog = xchg(&link->prog, new_prog);
10657	bpf_prog_put(old_prog);
10658
10659out_unlock:
10660	rtnl_unlock();
10661	return err;
10662}
10663
10664static const struct bpf_link_ops bpf_xdp_link_lops = {
10665	.release = bpf_xdp_link_release,
10666	.dealloc = bpf_xdp_link_dealloc,
10667	.detach = bpf_xdp_link_detach,
10668	.show_fdinfo = bpf_xdp_link_show_fdinfo,
10669	.fill_link_info = bpf_xdp_link_fill_link_info,
10670	.update_prog = bpf_xdp_link_update,
10671};
10672
10673int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
10674{
10675	struct net *net = current->nsproxy->net_ns;
10676	struct bpf_link_primer link_primer;
10677	struct netlink_ext_ack extack = {};
10678	struct bpf_xdp_link *link;
10679	struct net_device *dev;
10680	int err, fd;
10681
10682	rtnl_lock();
10683	dev = dev_get_by_index(net, attr->link_create.target_ifindex);
10684	if (!dev) {
10685		rtnl_unlock();
10686		return -EINVAL;
10687	}
10688
10689	link = kzalloc(sizeof(*link), GFP_USER);
10690	if (!link) {
10691		err = -ENOMEM;
10692		goto unlock;
10693	}
10694
10695	bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog,
10696		      attr->link_create.attach_type);
10697	link->dev = dev;
10698	link->flags = attr->link_create.flags;
10699
10700	err = bpf_link_prime(&link->link, &link_primer);
10701	if (err) {
10702		kfree(link);
10703		goto unlock;
10704	}
10705
10706	netdev_lock_ops(dev);
10707	err = dev_xdp_attach_link(dev, &extack, link);
10708	netdev_unlock_ops(dev);
10709	rtnl_unlock();
10710
10711	if (err) {
10712		link->dev = NULL;
10713		bpf_link_cleanup(&link_primer);
10714		trace_bpf_xdp_link_attach_failed(extack._msg);
10715		goto out_put_dev;
10716	}
10717
10718	fd = bpf_link_settle(&link_primer);
10719	/* link itself doesn't hold dev's refcnt to not complicate shutdown */
10720	dev_put(dev);
10721	return fd;
10722
10723unlock:
10724	rtnl_unlock();
10725
10726out_put_dev:
10727	dev_put(dev);
10728	return err;
10729}
10730
10731/**
10732 *	dev_change_xdp_fd - set or clear a bpf program for a device rx path
10733 *	@dev: device
10734 *	@extack: netlink extended ack
10735 *	@fd: new program fd or negative value to clear
10736 *	@expected_fd: old program fd that userspace expects to replace or clear
10737 *	@flags: xdp-related flags
10738 *
10739 *	Set or clear a bpf program for a device
10740 */
10741int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
10742		      int fd, int expected_fd, u32 flags)
10743{
10744	enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
10745	struct bpf_prog *new_prog = NULL, *old_prog = NULL;
10746	int err;
10747
10748	ASSERT_RTNL();
10749
10750	if (fd >= 0) {
10751		new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
10752						 mode != XDP_MODE_SKB);
10753		if (IS_ERR(new_prog))
10754			return PTR_ERR(new_prog);
10755	}
10756
10757	if (expected_fd >= 0) {
10758		old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
10759						 mode != XDP_MODE_SKB);
10760		if (IS_ERR(old_prog)) {
10761			err = PTR_ERR(old_prog);
10762			old_prog = NULL;
10763			goto err_out;
10764		}
10765	}
10766
10767	err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
10768
10769err_out:
10770	if (err && new_prog)
10771		bpf_prog_put(new_prog);
10772	if (old_prog)
10773		bpf_prog_put(old_prog);
10774	return err;
10775}
10776
10777u32 dev_get_min_mp_channel_count(const struct net_device *dev)
10778{
10779	int i;
10780
10781	netdev_ops_assert_locked(dev);
10782
10783	for (i = dev->real_num_rx_queues - 1; i >= 0; i--)
10784		if (dev->_rx[i].mp_params.mp_priv)
10785			/* The channel count is the idx plus 1. */
10786			return i + 1;
10787
10788	return 0;
10789}
10790
10791/**
10792 * dev_index_reserve() - allocate an ifindex in a namespace
10793 * @net: the applicable net namespace
10794 * @ifindex: requested ifindex, pass %0 to get one allocated
10795 *
10796 * Allocate a ifindex for a new device. Caller must either use the ifindex
10797 * to store the device (via list_netdevice()) or call dev_index_release()
10798 * to give the index up.
10799 *
10800 * Return: a suitable unique value for a new device interface number or -errno.
10801 */
10802static int dev_index_reserve(struct net *net, u32 ifindex)
10803{
10804	int err;
10805
10806	if (ifindex > INT_MAX) {
10807		DEBUG_NET_WARN_ON_ONCE(1);
10808		return -EINVAL;
10809	}
10810
10811	if (!ifindex)
10812		err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL,
10813				      xa_limit_31b, &net->ifindex, GFP_KERNEL);
10814	else
10815		err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL);
10816	if (err < 0)
10817		return err;
10818
10819	return ifindex;
10820}
10821
10822static void dev_index_release(struct net *net, int ifindex)
10823{
10824	/* Expect only unused indexes, unlist_netdevice() removes the used */
10825	WARN_ON(xa_erase(&net->dev_by_index, ifindex));
10826}
10827
10828static bool from_cleanup_net(void)
10829{
10830#ifdef CONFIG_NET_NS
10831	return current == READ_ONCE(cleanup_net_task);
10832#else
10833	return false;
10834#endif
10835}
10836
10837/* Delayed registration/unregisteration */
10838LIST_HEAD(net_todo_list);
10839DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
10840atomic_t dev_unreg_count = ATOMIC_INIT(0);
10841
10842static void net_set_todo(struct net_device *dev)
10843{
10844	list_add_tail(&dev->todo_list, &net_todo_list);
10845}
10846
10847static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
10848	struct net_device *upper, netdev_features_t features)
10849{
10850	netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
10851	netdev_features_t feature;
10852	int feature_bit;
10853
10854	for_each_netdev_feature(upper_disables, feature_bit) {
10855		feature = __NETIF_F_BIT(feature_bit);
10856		if (!(upper->wanted_features & feature)
10857		    && (features & feature)) {
10858			netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
10859				   &feature, upper->name);
10860			features &= ~feature;
10861		}
10862	}
10863
10864	return features;
10865}
10866
10867static void netdev_sync_lower_features(struct net_device *upper,
10868	struct net_device *lower, netdev_features_t features)
10869{
10870	netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
10871	netdev_features_t feature;
10872	int feature_bit;
10873
10874	for_each_netdev_feature(upper_disables, feature_bit) {
10875		feature = __NETIF_F_BIT(feature_bit);
10876		if (!(features & feature) && (lower->features & feature)) {
10877			netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
10878				   &feature, lower->name);
10879			netdev_lock_ops(lower);
10880			lower->wanted_features &= ~feature;
10881			__netdev_update_features(lower);
10882
10883			if (unlikely(lower->features & feature))
10884				netdev_WARN(upper, "failed to disable %pNF on %s!\n",
10885					    &feature, lower->name);
10886			else
10887				netdev_features_change(lower);
10888			netdev_unlock_ops(lower);
10889		}
10890	}
10891}
10892
10893static bool netdev_has_ip_or_hw_csum(netdev_features_t features)
10894{
10895	netdev_features_t ip_csum_mask = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
10896	bool ip_csum = (features & ip_csum_mask) == ip_csum_mask;
10897	bool hw_csum = features & NETIF_F_HW_CSUM;
10898
10899	return ip_csum || hw_csum;
10900}
10901
10902static netdev_features_t netdev_fix_features(struct net_device *dev,
10903	netdev_features_t features)
10904{
10905	/* Fix illegal checksum combinations */
10906	if ((features & NETIF_F_HW_CSUM) &&
10907	    (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
10908		netdev_warn(dev, "mixed HW and IP checksum settings.\n");
10909		features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
10910	}
10911
10912	/* TSO requires that SG is present as well. */
10913	if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
10914		netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
10915		features &= ~NETIF_F_ALL_TSO;
10916	}
10917
10918	if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
10919					!(features & NETIF_F_IP_CSUM)) {
10920		netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
10921		features &= ~NETIF_F_TSO;
10922		features &= ~NETIF_F_TSO_ECN;
10923	}
10924
10925	if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
10926					 !(features & NETIF_F_IPV6_CSUM)) {
10927		netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
10928		features &= ~NETIF_F_TSO6;
10929	}
10930
10931	/* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
10932	if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
10933		features &= ~NETIF_F_TSO_MANGLEID;
10934
10935	/* TSO ECN requires that TSO is present as well. */
10936	if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
10937		features &= ~NETIF_F_TSO_ECN;
10938
10939	/* Software GSO depends on SG. */
10940	if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
10941		netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
10942		features &= ~NETIF_F_GSO;
10943	}
10944
10945	/* GSO partial features require GSO partial be set */
10946	if ((features & dev->gso_partial_features) &&
10947	    !(features & NETIF_F_GSO_PARTIAL)) {
10948		netdev_dbg(dev,
10949			   "Dropping partially supported GSO features since no GSO partial.\n");
10950		features &= ~dev->gso_partial_features;
10951	}
10952
10953	if (!(features & NETIF_F_RXCSUM)) {
10954		/* NETIF_F_GRO_HW implies doing RXCSUM since every packet
10955		 * successfully merged by hardware must also have the
10956		 * checksum verified by hardware.  If the user does not
10957		 * want to enable RXCSUM, logically, we should disable GRO_HW.
10958		 */
10959		if (features & NETIF_F_GRO_HW) {
10960			netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
10961			features &= ~NETIF_F_GRO_HW;
10962		}
10963	}
10964
10965	/* LRO/HW-GRO features cannot be combined with RX-FCS */
10966	if (features & NETIF_F_RXFCS) {
10967		if (features & NETIF_F_LRO) {
10968			netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
10969			features &= ~NETIF_F_LRO;
10970		}
10971
10972		if (features & NETIF_F_GRO_HW) {
10973			netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
10974			features &= ~NETIF_F_GRO_HW;
10975		}
10976	}
10977
10978	if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
10979		netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
10980		features &= ~NETIF_F_LRO;
10981	}
10982
10983	if ((features & NETIF_F_HW_TLS_TX) && !netdev_has_ip_or_hw_csum(features)) {
10984		netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
10985		features &= ~NETIF_F_HW_TLS_TX;
10986	}
10987
10988	if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
10989		netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
10990		features &= ~NETIF_F_HW_TLS_RX;
10991	}
10992
10993	if ((features & NETIF_F_GSO_UDP_L4) && !netdev_has_ip_or_hw_csum(features)) {
10994		netdev_dbg(dev, "Dropping USO feature since no CSUM feature.\n");
10995		features &= ~NETIF_F_GSO_UDP_L4;
10996	}
10997
10998	return features;
10999}
11000
11001int __netdev_update_features(struct net_device *dev)
11002{
11003	struct net_device *upper, *lower;
11004	netdev_features_t features;
11005	struct list_head *iter;
11006	int err = -1;
11007
11008	ASSERT_RTNL();
11009	netdev_ops_assert_locked(dev);
11010
11011	features = netdev_get_wanted_features(dev);
11012
11013	if (dev->netdev_ops->ndo_fix_features)
11014		features = dev->netdev_ops->ndo_fix_features(dev, features);
11015
11016	/* driver might be less strict about feature dependencies */
11017	features = netdev_fix_features(dev, features);
11018
11019	/* some features can't be enabled if they're off on an upper device */
11020	netdev_for_each_upper_dev_rcu(dev, upper, iter)
11021		features = netdev_sync_upper_features(dev, upper, features);
11022
11023	if (dev->features == features)
11024		goto sync_lower;
11025
11026	netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
11027		&dev->features, &features);
11028
11029	if (dev->netdev_ops->ndo_set_features)
11030		err = dev->netdev_ops->ndo_set_features(dev, features);
11031	else
11032		err = 0;
11033
11034	if (unlikely(err < 0)) {
11035		netdev_err(dev,
11036			"set_features() failed (%d); wanted %pNF, left %pNF\n",
11037			err, &features, &dev->features);
11038		/* return non-0 since some features might have changed and
11039		 * it's better to fire a spurious notification than miss it
11040		 */
11041		return -1;
11042	}
11043
11044sync_lower:
11045	/* some features must be disabled on lower devices when disabled
11046	 * on an upper device (think: bonding master or bridge)
11047	 */
11048	netdev_for_each_lower_dev(dev, lower, iter)
11049		netdev_sync_lower_features(dev, lower, features);
11050
11051	if (!err) {
11052		netdev_features_t diff = features ^ dev->features;
11053
11054		if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
11055			/* udp_tunnel_{get,drop}_rx_info both need
11056			 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
11057			 * device, or they won't do anything.
11058			 * Thus we need to update dev->features
11059			 * *before* calling udp_tunnel_get_rx_info,
11060			 * but *after* calling udp_tunnel_drop_rx_info.
11061			 */
11062			udp_tunnel_nic_lock(dev);
11063			if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
11064				dev->features = features;
11065				udp_tunnel_get_rx_info(dev);
11066			} else {
11067				udp_tunnel_drop_rx_info(dev);
11068			}
11069			udp_tunnel_nic_unlock(dev);
11070		}
11071
11072		if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
11073			if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
11074				dev->features = features;
11075				err |= vlan_get_rx_ctag_filter_info(dev);
11076			} else {
11077				vlan_drop_rx_ctag_filter_info(dev);
11078			}
11079		}
11080
11081		if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
11082			if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
11083				dev->features = features;
11084				err |= vlan_get_rx_stag_filter_info(dev);
11085			} else {
11086				vlan_drop_rx_stag_filter_info(dev);
11087			}
11088		}
11089
11090		dev->features = features;
11091	}
11092
11093	return err < 0 ? 0 : 1;
11094}
11095
11096/**
11097 *	netdev_update_features - recalculate device features
11098 *	@dev: the device to check
11099 *
11100 *	Recalculate dev->features set and send notifications if it
11101 *	has changed. Should be called after driver or hardware dependent
11102 *	conditions might have changed that influence the features.
11103 */
11104void netdev_update_features(struct net_device *dev)
11105{
11106	if (__netdev_update_features(dev))
11107		netdev_features_change(dev);
11108}
11109EXPORT_SYMBOL(netdev_update_features);
11110
11111/**
11112 *	netdev_change_features - recalculate device features
11113 *	@dev: the device to check
11114 *
11115 *	Recalculate dev->features set and send notifications even
11116 *	if they have not changed. Should be called instead of
11117 *	netdev_update_features() if also dev->vlan_features might
11118 *	have changed to allow the changes to be propagated to stacked
11119 *	VLAN devices.
11120 */
11121void netdev_change_features(struct net_device *dev)
11122{
11123	__netdev_update_features(dev);
11124	netdev_features_change(dev);
11125}
11126EXPORT_SYMBOL(netdev_change_features);
11127
11128/**
11129 *	netif_stacked_transfer_operstate -	transfer operstate
11130 *	@rootdev: the root or lower level device to transfer state from
11131 *	@dev: the device to transfer operstate to
11132 *
11133 *	Transfer operational state from root to device. This is normally
11134 *	called when a stacking relationship exists between the root
11135 *	device and the device(a leaf device).
11136 */
11137void netif_stacked_transfer_operstate(const struct net_device *rootdev,
11138					struct net_device *dev)
11139{
11140	if (rootdev->operstate == IF_OPER_DORMANT)
11141		netif_dormant_on(dev);
11142	else
11143		netif_dormant_off(dev);
11144
11145	if (rootdev->operstate == IF_OPER_TESTING)
11146		netif_testing_on(dev);
11147	else
11148		netif_testing_off(dev);
11149
11150	if (netif_carrier_ok(rootdev))
11151		netif_carrier_on(dev);
11152	else
11153		netif_carrier_off(dev);
11154}
11155EXPORT_SYMBOL(netif_stacked_transfer_operstate);
11156
11157static int netif_alloc_rx_queues(struct net_device *dev)
11158{
11159	unsigned int i, count = dev->num_rx_queues;
11160	struct netdev_rx_queue *rx;
11161	size_t sz = count * sizeof(*rx);
11162	int err = 0;
11163
11164	BUG_ON(count < 1);
11165
11166	rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
11167	if (!rx)
11168		return -ENOMEM;
11169
11170	dev->_rx = rx;
11171
11172	for (i = 0; i < count; i++) {
11173		rx[i].dev = dev;
11174
11175		/* XDP RX-queue setup */
11176		err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
11177		if (err < 0)
11178			goto err_rxq_info;
11179	}
11180	return 0;
11181
11182err_rxq_info:
11183	/* Rollback successful reg's and free other resources */
11184	while (i--)
11185		xdp_rxq_info_unreg(&rx[i].xdp_rxq);
11186	kvfree(dev->_rx);
11187	dev->_rx = NULL;
11188	return err;
11189}
11190
11191static void netif_free_rx_queues(struct net_device *dev)
11192{
11193	unsigned int i, count = dev->num_rx_queues;
11194
11195	/* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
11196	if (!dev->_rx)
11197		return;
11198
11199	for (i = 0; i < count; i++)
11200		xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
11201
11202	kvfree(dev->_rx);
11203}
11204
11205static void netdev_init_one_queue(struct net_device *dev,
11206				  struct netdev_queue *queue, void *_unused)
11207{
11208	/* Initialize queue lock */
11209	spin_lock_init(&queue->_xmit_lock);
11210	netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
11211	queue->xmit_lock_owner = -1;
11212	netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
11213	queue->dev = dev;
11214#ifdef CONFIG_BQL
11215	dql_init(&queue->dql, HZ);
11216#endif
11217}
11218
11219static void netif_free_tx_queues(struct net_device *dev)
11220{
11221	kvfree(dev->_tx);
11222}
11223
11224static int netif_alloc_netdev_queues(struct net_device *dev)
11225{
11226	unsigned int count = dev->num_tx_queues;
11227	struct netdev_queue *tx;
11228	size_t sz = count * sizeof(*tx);
11229
11230	if (count < 1 || count > 0xffff)
11231		return -EINVAL;
11232
11233	tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
11234	if (!tx)
11235		return -ENOMEM;
11236
11237	dev->_tx = tx;
11238
11239	netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
11240	spin_lock_init(&dev->tx_global_lock);
11241
11242	return 0;
11243}
11244
11245void netif_tx_stop_all_queues(struct net_device *dev)
11246{
11247	unsigned int i;
11248
11249	for (i = 0; i < dev->num_tx_queues; i++) {
11250		struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
11251
11252		netif_tx_stop_queue(txq);
11253	}
11254}
11255EXPORT_SYMBOL(netif_tx_stop_all_queues);
11256
11257static int netdev_do_alloc_pcpu_stats(struct net_device *dev)
11258{
11259	void __percpu *v;
11260
11261	/* Drivers implementing ndo_get_peer_dev must support tstat
11262	 * accounting, so that skb_do_redirect() can bump the dev's
11263	 * RX stats upon network namespace switch.
11264	 */
11265	if (dev->netdev_ops->ndo_get_peer_dev &&
11266	    dev->pcpu_stat_type != NETDEV_PCPU_STAT_TSTATS)
11267		return -EOPNOTSUPP;
11268
11269	switch (dev->pcpu_stat_type) {
11270	case NETDEV_PCPU_STAT_NONE:
11271		return 0;
11272	case NETDEV_PCPU_STAT_LSTATS:
11273		v = dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats);
11274		break;
11275	case NETDEV_PCPU_STAT_TSTATS:
11276		v = dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
11277		break;
11278	case NETDEV_PCPU_STAT_DSTATS:
11279		v = dev->dstats = netdev_alloc_pcpu_stats(struct pcpu_dstats);
11280		break;
11281	default:
11282		return -EINVAL;
11283	}
11284
11285	return v ? 0 : -ENOMEM;
11286}
11287
11288static void netdev_do_free_pcpu_stats(struct net_device *dev)
11289{
11290	switch (dev->pcpu_stat_type) {
11291	case NETDEV_PCPU_STAT_NONE:
11292		return;
11293	case NETDEV_PCPU_STAT_LSTATS:
11294		free_percpu(dev->lstats);
11295		break;
11296	case NETDEV_PCPU_STAT_TSTATS:
11297		free_percpu(dev->tstats);
11298		break;
11299	case NETDEV_PCPU_STAT_DSTATS:
11300		free_percpu(dev->dstats);
11301		break;
11302	}
11303}
11304
11305static void netdev_free_phy_link_topology(struct net_device *dev)
11306{
11307	struct phy_link_topology *topo = dev->link_topo;
11308
11309	if (IS_ENABLED(CONFIG_PHYLIB) && topo) {
11310		xa_destroy(&topo->phys);
11311		kfree(topo);
11312		dev->link_topo = NULL;
11313	}
11314}
11315
11316/**
11317 * register_netdevice() - register a network device
11318 * @dev: device to register
11319 *
11320 * Take a prepared network device structure and make it externally accessible.
11321 * A %NETDEV_REGISTER message is sent to the netdev notifier chain.
11322 * Callers must hold the rtnl lock - you may want register_netdev()
11323 * instead of this.
11324 */
11325int register_netdevice(struct net_device *dev)
11326{
11327	int ret;
11328	struct net *net = dev_net(dev);
11329
11330	BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
11331		     NETDEV_FEATURE_COUNT);
11332	BUG_ON(dev_boot_phase);
11333	ASSERT_RTNL();
11334
11335	might_sleep();
11336
11337	/* When net_device's are persistent, this will be fatal. */
11338	BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
11339	BUG_ON(!net);
11340
11341	ret = ethtool_check_ops(dev->ethtool_ops);
11342	if (ret)
11343		return ret;
11344
11345	/* rss ctx ID 0 is reserved for the default context, start from 1 */
11346	xa_init_flags(&dev->ethtool->rss_ctx, XA_FLAGS_ALLOC1);
11347	mutex_init(&dev->ethtool->rss_lock);
11348
11349	spin_lock_init(&dev->addr_list_lock);
11350	netdev_set_addr_lockdep_class(dev);
11351
11352	ret = dev_get_valid_name(net, dev, dev->name);
11353	if (ret < 0)
11354		goto out;
11355
11356	ret = -ENOMEM;
11357	dev->name_node = netdev_name_node_head_alloc(dev);
11358	if (!dev->name_node)
11359		goto out;
11360
11361	/* Init, if this function is available */
11362	if (dev->netdev_ops->ndo_init) {
11363		ret = dev->netdev_ops->ndo_init(dev);
11364		if (ret) {
11365			if (ret > 0)
11366				ret = -EIO;
11367			goto err_free_name;
11368		}
11369	}
11370
11371	if (((dev->hw_features | dev->features) &
11372	     NETIF_F_HW_VLAN_CTAG_FILTER) &&
11373	    (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
11374	     !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
11375		netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
11376		ret = -EINVAL;
11377		goto err_uninit;
11378	}
11379
11380	ret = netdev_do_alloc_pcpu_stats(dev);
11381	if (ret)
11382		goto err_uninit;
11383
11384	ret = dev_index_reserve(net, dev->ifindex);
11385	if (ret < 0)
11386		goto err_free_pcpu;
11387	dev->ifindex = ret;
11388
11389	/* Transfer changeable features to wanted_features and enable
11390	 * software offloads (GSO and GRO).
11391	 */
11392	dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
11393	dev->features |= NETIF_F_SOFT_FEATURES;
11394
11395	if (dev->udp_tunnel_nic_info) {
11396		dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
11397		dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
11398	}
11399
11400	dev->wanted_features = dev->features & dev->hw_features;
11401
11402	if (!(dev->flags & IFF_LOOPBACK))
11403		dev->hw_features |= NETIF_F_NOCACHE_COPY;
11404
11405	/* If IPv4 TCP segmentation offload is supported we should also
11406	 * allow the device to enable segmenting the frame with the option
11407	 * of ignoring a static IP ID value.  This doesn't enable the
11408	 * feature itself but allows the user to enable it later.
11409	 */
11410	if (dev->hw_features & NETIF_F_TSO)
11411		dev->hw_features |= NETIF_F_TSO_MANGLEID;
11412	if (dev->vlan_features & NETIF_F_TSO)
11413		dev->vlan_features |= NETIF_F_TSO_MANGLEID;
11414	if (dev->mpls_features & NETIF_F_TSO)
11415		dev->mpls_features |= NETIF_F_TSO_MANGLEID;
11416	if (dev->hw_enc_features & NETIF_F_TSO)
11417		dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
11418
11419	/* TSO_MANGLEID belongs in mangleid_features by definition */
11420	dev->mangleid_features |= NETIF_F_TSO_MANGLEID;
11421
11422	/* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
11423	 */
11424	dev->vlan_features |= NETIF_F_HIGHDMA;
11425
11426	/* Make NETIF_F_SG inheritable to tunnel devices.
11427	 */
11428	dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
11429
11430	/* Make NETIF_F_SG inheritable to MPLS.
11431	 */
11432	dev->mpls_features |= NETIF_F_SG;
11433
11434	ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
11435	ret = notifier_to_errno(ret);
11436	if (ret)
11437		goto err_ifindex_release;
11438
11439	ret = netdev_register_kobject(dev);
11440
11441	netdev_lock(dev);
11442	WRITE_ONCE(dev->reg_state, ret ? NETREG_UNREGISTERED : NETREG_REGISTERED);
11443	netdev_unlock(dev);
11444
11445	if (ret)
11446		goto err_uninit_notify;
11447
11448	netdev_lock_ops(dev);
11449	__netdev_update_features(dev);
11450	netdev_unlock_ops(dev);
11451
11452	/*
11453	 *	Default initial state at registry is that the
11454	 *	device is present.
11455	 */
11456
11457	set_bit(__LINK_STATE_PRESENT, &dev->state);
11458
11459	linkwatch_init_dev(dev);
11460
11461	dev_init_scheduler(dev);
11462
11463	netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL);
11464	list_netdevice(dev);
11465
11466	add_device_randomness(dev->dev_addr, dev->addr_len);
11467
11468	/* If the device has permanent device address, driver should
11469	 * set dev_addr and also addr_assign_type should be set to
11470	 * NET_ADDR_PERM (default value).
11471	 */
11472	if (dev->addr_assign_type == NET_ADDR_PERM)
11473		memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
11474
11475	/* Notify protocols, that a new device appeared. */
11476	netdev_lock_ops(dev);
11477	ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
11478	netdev_unlock_ops(dev);
11479	ret = notifier_to_errno(ret);
11480	if (ret) {
11481		/* Expect explicit free_netdev() on failure */
11482		dev->needs_free_netdev = false;
11483		unregister_netdevice_queue(dev, NULL);
11484		goto out;
11485	}
11486	/*
11487	 *	Prevent userspace races by waiting until the network
11488	 *	device is fully setup before sending notifications.
11489	 */
11490	if (!(dev->rtnl_link_ops && dev->rtnl_link_initializing))
11491		rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
11492
11493out:
11494	return ret;
11495
11496err_uninit_notify:
11497	call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
11498err_ifindex_release:
11499	dev_index_release(net, dev->ifindex);
11500err_free_pcpu:
11501	netdev_do_free_pcpu_stats(dev);
11502err_uninit:
11503	if (dev->netdev_ops->ndo_uninit)
11504		dev->netdev_ops->ndo_uninit(dev);
11505	if (dev->priv_destructor)
11506		dev->priv_destructor(dev);
11507err_free_name:
11508	netdev_name_node_free(dev->name_node);
11509	goto out;
11510}
11511EXPORT_SYMBOL(register_netdevice);
11512
11513/* Initialize the core of a dummy net device.
11514 * The setup steps dummy netdevs need which normal netdevs get by going
11515 * through register_netdevice().
11516 */
11517static void init_dummy_netdev(struct net_device *dev)
11518{
11519	/* make sure we BUG if trying to hit standard
11520	 * register/unregister code path
11521	 */
11522	dev->reg_state = NETREG_DUMMY;
11523
11524	/* a dummy interface is started by default */
11525	set_bit(__LINK_STATE_PRESENT, &dev->state);
11526	set_bit(__LINK_STATE_START, &dev->state);
11527
11528	/* Note : We dont allocate pcpu_refcnt for dummy devices,
11529	 * because users of this 'device' dont need to change
11530	 * its refcount.
11531	 */
11532}
11533
11534/**
11535 *	register_netdev	- register a network device
11536 *	@dev: device to register
11537 *
11538 *	Take a completed network device structure and add it to the kernel
11539 *	interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
11540 *	chain. 0 is returned on success. A negative errno code is returned
11541 *	on a failure to set up the device, or if the name is a duplicate.
11542 *
11543 *	This is a wrapper around register_netdevice that takes the rtnl semaphore
11544 *	and expands the device name if you passed a format string to
11545 *	alloc_netdev.
11546 */
11547int register_netdev(struct net_device *dev)
11548{
11549	struct net *net = dev_net(dev);
11550	int err;
11551
11552	if (rtnl_net_lock_killable(net))
11553		return -EINTR;
11554
11555	err = register_netdevice(dev);
11556
11557	rtnl_net_unlock(net);
11558
11559	return err;
11560}
11561EXPORT_SYMBOL(register_netdev);
11562
11563int netdev_refcnt_read(const struct net_device *dev)
11564{
11565#ifdef CONFIG_PCPU_DEV_REFCNT
11566	int i, refcnt = 0;
11567
11568	for_each_possible_cpu(i)
11569		refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
11570	return refcnt;
11571#else
11572	return refcount_read(&dev->dev_refcnt);
11573#endif
11574}
11575EXPORT_SYMBOL(netdev_refcnt_read);
11576
11577int netdev_unregister_timeout_secs __read_mostly = 10;
11578
11579#define WAIT_REFS_MIN_MSECS 1
11580#define WAIT_REFS_MAX_MSECS 250
11581/**
11582 * netdev_wait_allrefs_any - wait until all references are gone.
11583 * @list: list of net_devices to wait on
11584 *
11585 * This is called when unregistering network devices.
11586 *
11587 * Any protocol or device that holds a reference should register
11588 * for netdevice notification, and cleanup and put back the
11589 * reference if they receive an UNREGISTER event.
11590 * We can get stuck here if buggy protocols don't correctly
11591 * call dev_put.
11592 */
11593static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
11594{
11595	unsigned long rebroadcast_time, warning_time;
11596	struct net_device *dev;
11597	int wait = 0;
11598
11599	rebroadcast_time = warning_time = jiffies;
11600
11601	list_for_each_entry(dev, list, todo_list)
11602		if (netdev_refcnt_read(dev) == 1)
11603			return dev;
11604
11605	while (true) {
11606		if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
11607			rtnl_lock();
11608
11609			/* Rebroadcast unregister notification */
11610			list_for_each_entry(dev, list, todo_list)
11611				call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11612
11613			__rtnl_unlock();
11614			rcu_barrier();
11615			rtnl_lock();
11616
11617			list_for_each_entry(dev, list, todo_list)
11618				if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
11619					     &dev->state)) {
11620					/* We must not have linkwatch events
11621					 * pending on unregister. If this
11622					 * happens, we simply run the queue
11623					 * unscheduled, resulting in a noop
11624					 * for this device.
11625					 */
11626					linkwatch_run_queue();
11627					break;
11628				}
11629
11630			__rtnl_unlock();
11631
11632			rebroadcast_time = jiffies;
11633		}
11634
11635		rcu_barrier();
11636
11637		if (!wait) {
11638			wait = WAIT_REFS_MIN_MSECS;
11639		} else {
11640			msleep(wait);
11641			wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
11642		}
11643
11644		list_for_each_entry(dev, list, todo_list)
11645			if (netdev_refcnt_read(dev) == 1)
11646				return dev;
11647
11648		if (time_after(jiffies, warning_time +
11649			       READ_ONCE(netdev_unregister_timeout_secs) * HZ)) {
11650			list_for_each_entry(dev, list, todo_list) {
11651				pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
11652					 dev->name, netdev_refcnt_read(dev));
11653				ref_tracker_dir_print(&dev->refcnt_tracker, 10);
11654			}
11655
11656			warning_time = jiffies;
11657		}
11658	}
11659}
11660
11661/* The sequence is:
11662 *
11663 *	rtnl_lock();
11664 *	...
11665 *	register_netdevice(x1);
11666 *	register_netdevice(x2);
11667 *	...
11668 *	unregister_netdevice(y1);
11669 *	unregister_netdevice(y2);
11670 *      ...
11671 *	rtnl_unlock();
11672 *	free_netdev(y1);
11673 *	free_netdev(y2);
11674 *
11675 * We are invoked by rtnl_unlock().
11676 * This allows us to deal with problems:
11677 * 1) We can delete sysfs objects which invoke hotplug
11678 *    without deadlocking with linkwatch via keventd.
11679 * 2) Since we run with the RTNL semaphore not held, we can sleep
11680 *    safely in order to wait for the netdev refcnt to drop to zero.
11681 *
11682 * We must not return until all unregister events added during
11683 * the interval the lock was held have been completed.
11684 */
11685void netdev_run_todo(void)
11686{
11687	struct net_device *dev, *tmp;
11688	struct list_head list;
11689	int cnt;
11690#ifdef CONFIG_LOCKDEP
11691	struct list_head unlink_list;
11692
11693	list_replace_init(&net_unlink_list, &unlink_list);
11694
11695	while (!list_empty(&unlink_list)) {
11696		dev = list_first_entry(&unlink_list, struct net_device,
11697				       unlink_list);
11698		list_del_init(&dev->unlink_list);
11699		dev->nested_level = dev->lower_level - 1;
11700	}
11701#endif
11702
11703	/* Snapshot list, allow later requests */
11704	list_replace_init(&net_todo_list, &list);
11705
11706	__rtnl_unlock();
11707
11708	/* Wait for rcu callbacks to finish before next phase */
11709	if (!list_empty(&list))
11710		rcu_barrier();
11711
11712	list_for_each_entry_safe(dev, tmp, &list, todo_list) {
11713		if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
11714			netdev_WARN(dev, "run_todo but not unregistering\n");
11715			list_del(&dev->todo_list);
11716			continue;
11717		}
11718
11719		netdev_lock(dev);
11720		WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERED);
11721		netdev_unlock(dev);
11722		linkwatch_sync_dev(dev);
11723	}
11724
11725	cnt = 0;
11726	while (!list_empty(&list)) {
11727		dev = netdev_wait_allrefs_any(&list);
11728		list_del(&dev->todo_list);
11729
11730		/* paranoia */
11731		BUG_ON(netdev_refcnt_read(dev) != 1);
11732		BUG_ON(!list_empty(&dev->ptype_all));
11733		BUG_ON(!list_empty(&dev->ptype_specific));
11734		WARN_ON(rcu_access_pointer(dev->ip_ptr));
11735		WARN_ON(rcu_access_pointer(dev->ip6_ptr));
11736
11737		netdev_do_free_pcpu_stats(dev);
11738		if (dev->priv_destructor)
11739			dev->priv_destructor(dev);
11740		if (dev->needs_free_netdev)
11741			free_netdev(dev);
11742
11743		cnt++;
11744
11745		/* Free network device */
11746		kobject_put(&dev->dev.kobj);
11747	}
11748	if (cnt && atomic_sub_and_test(cnt, &dev_unreg_count))
11749		wake_up(&netdev_unregistering_wq);
11750}
11751
11752/* Collate per-cpu network dstats statistics
11753 *
11754 * Read per-cpu network statistics from dev->dstats and populate the related
11755 * fields in @s.
11756 */
11757static void dev_fetch_dstats(struct rtnl_link_stats64 *s,
11758			     const struct pcpu_dstats __percpu *dstats)
11759{
11760	int cpu;
11761
11762	for_each_possible_cpu(cpu) {
11763		u64 rx_packets, rx_bytes, rx_drops;
11764		u64 tx_packets, tx_bytes, tx_drops;
11765		const struct pcpu_dstats *stats;
11766		unsigned int start;
11767
11768		stats = per_cpu_ptr(dstats, cpu);
11769		do {
11770			start = u64_stats_fetch_begin(&stats->syncp);
11771			rx_packets = u64_stats_read(&stats->rx_packets);
11772			rx_bytes   = u64_stats_read(&stats->rx_bytes);
11773			rx_drops   = u64_stats_read(&stats->rx_drops);
11774			tx_packets = u64_stats_read(&stats->tx_packets);
11775			tx_bytes   = u64_stats_read(&stats->tx_bytes);
11776			tx_drops   = u64_stats_read(&stats->tx_drops);
11777		} while (u64_stats_fetch_retry(&stats->syncp, start));
11778
11779		s->rx_packets += rx_packets;
11780		s->rx_bytes   += rx_bytes;
11781		s->rx_dropped += rx_drops;
11782		s->tx_packets += tx_packets;
11783		s->tx_bytes   += tx_bytes;
11784		s->tx_dropped += tx_drops;
11785	}
11786}
11787
11788/* ndo_get_stats64 implementation for dtstats-based accounting.
11789 *
11790 * Populate @s from dev->stats and dev->dstats. This is used internally by the
11791 * core for NETDEV_PCPU_STAT_DSTAT-type stats collection.
11792 */
11793static void dev_get_dstats64(const struct net_device *dev,
11794			     struct rtnl_link_stats64 *s)
11795{
11796	netdev_stats_to_stats64(s, &dev->stats);
11797	dev_fetch_dstats(s, dev->dstats);
11798}
11799
11800/* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
11801 * all the same fields in the same order as net_device_stats, with only
11802 * the type differing, but rtnl_link_stats64 may have additional fields
11803 * at the end for newer counters.
11804 */
11805void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
11806			     const struct net_device_stats *netdev_stats)
11807{
11808	size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t);
11809	const atomic_long_t *src = (atomic_long_t *)netdev_stats;
11810	u64 *dst = (u64 *)stats64;
11811
11812	BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
11813	for (i = 0; i < n; i++)
11814		dst[i] = (unsigned long)atomic_long_read(&src[i]);
11815	/* zero out counters that only exist in rtnl_link_stats64 */
11816	memset((char *)stats64 + n * sizeof(u64), 0,
11817	       sizeof(*stats64) - n * sizeof(u64));
11818}
11819EXPORT_SYMBOL(netdev_stats_to_stats64);
11820
11821static __cold struct net_device_core_stats __percpu *netdev_core_stats_alloc(
11822		struct net_device *dev)
11823{
11824	struct net_device_core_stats __percpu *p;
11825
11826	p = alloc_percpu_gfp(struct net_device_core_stats,
11827			     GFP_ATOMIC | __GFP_NOWARN);
11828
11829	if (p && cmpxchg(&dev->core_stats, NULL, p))
11830		free_percpu(p);
11831
11832	/* This READ_ONCE() pairs with the cmpxchg() above */
11833	return READ_ONCE(dev->core_stats);
11834}
11835
11836noinline void netdev_core_stats_inc(struct net_device *dev, u32 offset)
11837{
11838	/* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
11839	struct net_device_core_stats __percpu *p = READ_ONCE(dev->core_stats);
11840	unsigned long __percpu *field;
11841
11842	if (unlikely(!p)) {
11843		p = netdev_core_stats_alloc(dev);
11844		if (!p)
11845			return;
11846	}
11847
11848	field = (unsigned long __percpu *)((void __percpu *)p + offset);
11849	this_cpu_inc(*field);
11850}
11851EXPORT_SYMBOL_GPL(netdev_core_stats_inc);
11852
11853/**
11854 *	dev_get_stats	- get network device statistics
11855 *	@dev: device to get statistics from
11856 *	@storage: place to store stats
11857 *
11858 *	Get network statistics from device. Return @storage.
11859 *	The device driver may provide its own method by setting
11860 *	dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
11861 *	otherwise the internal statistics structure is used.
11862 */
11863struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
11864					struct rtnl_link_stats64 *storage)
11865{
11866	const struct net_device_ops *ops = dev->netdev_ops;
11867	const struct net_device_core_stats __percpu *p;
11868
11869	/*
11870	 * IPv{4,6} and udp tunnels share common stat helpers and use
11871	 * different stat type (NETDEV_PCPU_STAT_TSTATS vs
11872	 * NETDEV_PCPU_STAT_DSTATS). Ensure the accounting is consistent.
11873	 */
11874	BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, rx_bytes) !=
11875		     offsetof(struct pcpu_dstats, rx_bytes));
11876	BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, rx_packets) !=
11877		     offsetof(struct pcpu_dstats, rx_packets));
11878	BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, tx_bytes) !=
11879		     offsetof(struct pcpu_dstats, tx_bytes));
11880	BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, tx_packets) !=
11881		     offsetof(struct pcpu_dstats, tx_packets));
11882
11883	if (ops->ndo_get_stats64) {
11884		memset(storage, 0, sizeof(*storage));
11885		ops->ndo_get_stats64(dev, storage);
11886	} else if (ops->ndo_get_stats) {
11887		netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
11888	} else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_TSTATS) {
11889		dev_get_tstats64(dev, storage);
11890	} else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_DSTATS) {
11891		dev_get_dstats64(dev, storage);
11892	} else {
11893		netdev_stats_to_stats64(storage, &dev->stats);
11894	}
11895
11896	/* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
11897	p = READ_ONCE(dev->core_stats);
11898	if (p) {
11899		const struct net_device_core_stats *core_stats;
11900		int i;
11901
11902		for_each_possible_cpu(i) {
11903			core_stats = per_cpu_ptr(p, i);
11904			storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
11905			storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
11906			storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
11907			storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped);
11908		}
11909	}
11910	return storage;
11911}
11912EXPORT_SYMBOL(dev_get_stats);
11913
11914/**
11915 *	dev_fetch_sw_netstats - get per-cpu network device statistics
11916 *	@s: place to store stats
11917 *	@netstats: per-cpu network stats to read from
11918 *
11919 *	Read per-cpu network statistics and populate the related fields in @s.
11920 */
11921void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
11922			   const struct pcpu_sw_netstats __percpu *netstats)
11923{
11924	int cpu;
11925
11926	for_each_possible_cpu(cpu) {
11927		u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
11928		const struct pcpu_sw_netstats *stats;
11929		unsigned int start;
11930
11931		stats = per_cpu_ptr(netstats, cpu);
11932		do {
11933			start = u64_stats_fetch_begin(&stats->syncp);
11934			rx_packets = u64_stats_read(&stats->rx_packets);
11935			rx_bytes   = u64_stats_read(&stats->rx_bytes);
11936			tx_packets = u64_stats_read(&stats->tx_packets);
11937			tx_bytes   = u64_stats_read(&stats->tx_bytes);
11938		} while (u64_stats_fetch_retry(&stats->syncp, start));
11939
11940		s->rx_packets += rx_packets;
11941		s->rx_bytes   += rx_bytes;
11942		s->tx_packets += tx_packets;
11943		s->tx_bytes   += tx_bytes;
11944	}
11945}
11946EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
11947
11948/**
11949 *	dev_get_tstats64 - ndo_get_stats64 implementation
11950 *	@dev: device to get statistics from
11951 *	@s: place to store stats
11952 *
11953 *	Populate @s from dev->stats and dev->tstats. Can be used as
11954 *	ndo_get_stats64() callback.
11955 */
11956void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
11957{
11958	netdev_stats_to_stats64(s, &dev->stats);
11959	dev_fetch_sw_netstats(s, dev->tstats);
11960}
11961EXPORT_SYMBOL_GPL(dev_get_tstats64);
11962
11963struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
11964{
11965	struct netdev_queue *queue = dev_ingress_queue(dev);
11966
11967#ifdef CONFIG_NET_CLS_ACT
11968	if (queue)
11969		return queue;
11970	queue = kzalloc(sizeof(*queue), GFP_KERNEL);
11971	if (!queue)
11972		return NULL;
11973	netdev_init_one_queue(dev, queue, NULL);
11974	RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
11975	RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc);
11976	rcu_assign_pointer(dev->ingress_queue, queue);
11977#endif
11978	return queue;
11979}
11980
11981static const struct ethtool_ops default_ethtool_ops;
11982
11983void netdev_set_default_ethtool_ops(struct net_device *dev,
11984				    const struct ethtool_ops *ops)
11985{
11986	if (dev->ethtool_ops == &default_ethtool_ops)
11987		dev->ethtool_ops = ops;
11988}
11989EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
11990
11991/**
11992 * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default
11993 * @dev: netdev to enable the IRQ coalescing on
11994 *
11995 * Sets a conservative default for SW IRQ coalescing. Users can use
11996 * sysfs attributes to override the default values.
11997 */
11998void netdev_sw_irq_coalesce_default_on(struct net_device *dev)
11999{
12000	WARN_ON(dev->reg_state == NETREG_REGISTERED);
12001
12002	if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
12003		netdev_set_gro_flush_timeout(dev, 20000);
12004		netdev_set_defer_hard_irqs(dev, 1);
12005	}
12006}
12007EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on);
12008
12009/**
12010 * alloc_netdev_mqs - allocate network device
12011 * @sizeof_priv: size of private data to allocate space for
12012 * @name: device name format string
12013 * @name_assign_type: origin of device name
12014 * @setup: callback to initialize device
12015 * @txqs: the number of TX subqueues to allocate
12016 * @rxqs: the number of RX subqueues to allocate
12017 *
12018 * Allocates a struct net_device with private data area for driver use
12019 * and performs basic initialization.  Also allocates subqueue structs
12020 * for each queue on the device.
12021 */
12022struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
12023		unsigned char name_assign_type,
12024		void (*setup)(struct net_device *),
12025		unsigned int txqs, unsigned int rxqs)
12026{
12027	struct net_device *dev;
12028	size_t napi_config_sz;
12029	unsigned int maxqs;
12030
12031	BUG_ON(strlen(name) >= sizeof(dev->name));
12032
12033	if (txqs < 1) {
12034		pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
12035		return NULL;
12036	}
12037
12038	if (rxqs < 1) {
12039		pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
12040		return NULL;
12041	}
12042
12043	maxqs = max(txqs, rxqs);
12044
12045	dev = kvzalloc(struct_size(dev, priv, sizeof_priv),
12046		       GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
12047	if (!dev)
12048		return NULL;
12049
12050	dev->priv_len = sizeof_priv;
12051
12052	ref_tracker_dir_init(&dev->refcnt_tracker, 128, "netdev");
12053#ifdef CONFIG_PCPU_DEV_REFCNT
12054	dev->pcpu_refcnt = alloc_percpu(int);
12055	if (!dev->pcpu_refcnt)
12056		goto free_dev;
12057	__dev_hold(dev);
12058#else
12059	refcount_set(&dev->dev_refcnt, 1);
12060#endif
12061
12062	if (dev_addr_init(dev))
12063		goto free_pcpu;
12064
12065	dev_mc_init(dev);
12066	dev_uc_init(dev);
12067
12068	dev_net_set(dev, &init_net);
12069
12070	dev->gso_max_size = GSO_LEGACY_MAX_SIZE;
12071	dev->xdp_zc_max_segs = 1;
12072	dev->gso_max_segs = GSO_MAX_SEGS;
12073	dev->gro_max_size = GRO_LEGACY_MAX_SIZE;
12074	dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE;
12075	dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE;
12076	dev->tso_max_size = TSO_LEGACY_MAX_SIZE;
12077	dev->tso_max_segs = TSO_MAX_SEGS;
12078	dev->upper_level = 1;
12079	dev->lower_level = 1;
12080#ifdef CONFIG_LOCKDEP
12081	dev->nested_level = 0;
12082	INIT_LIST_HEAD(&dev->unlink_list);
12083#endif
12084
12085	INIT_LIST_HEAD(&dev->napi_list);
12086	INIT_LIST_HEAD(&dev->unreg_list);
12087	INIT_LIST_HEAD(&dev->close_list);
12088	INIT_LIST_HEAD(&dev->link_watch_list);
12089	INIT_LIST_HEAD(&dev->adj_list.upper);
12090	INIT_LIST_HEAD(&dev->adj_list.lower);
12091	INIT_LIST_HEAD(&dev->ptype_all);
12092	INIT_LIST_HEAD(&dev->ptype_specific);
12093	INIT_LIST_HEAD(&dev->net_notifier_list);
12094#ifdef CONFIG_NET_SCHED
12095	hash_init(dev->qdisc_hash);
12096#endif
12097
12098	mutex_init(&dev->lock);
12099
12100	dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
12101	setup(dev);
12102
12103	if (!dev->tx_queue_len) {
12104		dev->priv_flags |= IFF_NO_QUEUE;
12105		dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
12106	}
12107
12108	dev->num_tx_queues = txqs;
12109	dev->real_num_tx_queues = txqs;
12110	if (netif_alloc_netdev_queues(dev))
12111		goto free_all;
12112
12113	dev->num_rx_queues = rxqs;
12114	dev->real_num_rx_queues = rxqs;
12115	if (netif_alloc_rx_queues(dev))
12116		goto free_all;
12117	dev->ethtool = kzalloc(sizeof(*dev->ethtool), GFP_KERNEL_ACCOUNT);
12118	if (!dev->ethtool)
12119		goto free_all;
12120
12121	dev->cfg = kzalloc(sizeof(*dev->cfg), GFP_KERNEL_ACCOUNT);
12122	if (!dev->cfg)
12123		goto free_all;
12124	dev->cfg_pending = dev->cfg;
12125
12126	dev->num_napi_configs = maxqs;
12127	napi_config_sz = array_size(maxqs, sizeof(*dev->napi_config));
12128	dev->napi_config = kvzalloc(napi_config_sz, GFP_KERNEL_ACCOUNT);
12129	if (!dev->napi_config)
12130		goto free_all;
12131
12132	strscpy(dev->name, name);
12133	dev->name_assign_type = name_assign_type;
12134	dev->group = INIT_NETDEV_GROUP;
12135	if (!dev->ethtool_ops)
12136		dev->ethtool_ops = &default_ethtool_ops;
12137
12138	nf_hook_netdev_init(dev);
12139
12140	return dev;
12141
12142free_all:
12143	free_netdev(dev);
12144	return NULL;
12145
12146free_pcpu:
12147#ifdef CONFIG_PCPU_DEV_REFCNT
12148	free_percpu(dev->pcpu_refcnt);
12149free_dev:
12150#endif
12151	kvfree(dev);
12152	return NULL;
12153}
12154EXPORT_SYMBOL(alloc_netdev_mqs);
12155
12156static void netdev_napi_exit(struct net_device *dev)
12157{
12158	if (!list_empty(&dev->napi_list)) {
12159		struct napi_struct *p, *n;
12160
12161		netdev_lock(dev);
12162		list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
12163			__netif_napi_del_locked(p);
12164		netdev_unlock(dev);
12165
12166		synchronize_net();
12167	}
12168
12169	kvfree(dev->napi_config);
12170}
12171
12172/**
12173 * free_netdev - free network device
12174 * @dev: device
12175 *
12176 * This function does the last stage of destroying an allocated device
12177 * interface. The reference to the device object is released. If this
12178 * is the last reference then it will be freed.Must be called in process
12179 * context.
12180 */
12181void free_netdev(struct net_device *dev)
12182{
12183	might_sleep();
12184
12185	/* When called immediately after register_netdevice() failed the unwind
12186	 * handling may still be dismantling the device. Handle that case by
12187	 * deferring the free.
12188	 */
12189	if (dev->reg_state == NETREG_UNREGISTERING) {
12190		ASSERT_RTNL();
12191		dev->needs_free_netdev = true;
12192		return;
12193	}
12194
12195	WARN_ON(dev->cfg != dev->cfg_pending);
12196	kfree(dev->cfg);
12197	kfree(dev->ethtool);
12198	netif_free_tx_queues(dev);
12199	netif_free_rx_queues(dev);
12200
12201	kfree(rcu_dereference_protected(dev->ingress_queue, 1));
12202
12203	/* Flush device addresses */
12204	dev_addr_flush(dev);
12205
12206	netdev_napi_exit(dev);
12207
12208	netif_del_cpu_rmap(dev);
12209
12210	ref_tracker_dir_exit(&dev->refcnt_tracker);
12211#ifdef CONFIG_PCPU_DEV_REFCNT
12212	free_percpu(dev->pcpu_refcnt);
12213	dev->pcpu_refcnt = NULL;
12214#endif
12215	free_percpu(dev->core_stats);
12216	dev->core_stats = NULL;
12217	free_percpu(dev->xdp_bulkq);
12218	dev->xdp_bulkq = NULL;
12219
12220	netdev_free_phy_link_topology(dev);
12221
12222	mutex_destroy(&dev->lock);
12223
12224	/*  Compatibility with error handling in drivers */
12225	if (dev->reg_state == NETREG_UNINITIALIZED ||
12226	    dev->reg_state == NETREG_DUMMY) {
12227		kvfree(dev);
12228		return;
12229	}
12230
12231	BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
12232	WRITE_ONCE(dev->reg_state, NETREG_RELEASED);
12233
12234	/* will free via device release */
12235	put_device(&dev->dev);
12236}
12237EXPORT_SYMBOL(free_netdev);
12238
12239/**
12240 * alloc_netdev_dummy - Allocate and initialize a dummy net device.
12241 * @sizeof_priv: size of private data to allocate space for
12242 *
12243 * Return: the allocated net_device on success, NULL otherwise
12244 */
12245struct net_device *alloc_netdev_dummy(int sizeof_priv)
12246{
12247	return alloc_netdev(sizeof_priv, "dummy#", NET_NAME_UNKNOWN,
12248			    init_dummy_netdev);
12249}
12250EXPORT_SYMBOL_GPL(alloc_netdev_dummy);
12251
12252/**
12253 *	synchronize_net -  Synchronize with packet receive processing
12254 *
12255 *	Wait for packets currently being received to be done.
12256 *	Does not block later packets from starting.
12257 */
12258void synchronize_net(void)
12259{
12260	might_sleep();
12261	if (from_cleanup_net() || rtnl_is_locked())
12262		synchronize_rcu_expedited();
12263	else
12264		synchronize_rcu();
12265}
12266EXPORT_SYMBOL(synchronize_net);
12267
12268static void netdev_rss_contexts_free(struct net_device *dev)
12269{
12270	struct ethtool_rxfh_context *ctx;
12271	unsigned long context;
12272
12273	mutex_lock(&dev->ethtool->rss_lock);
12274	xa_for_each(&dev->ethtool->rss_ctx, context, ctx) {
12275		xa_erase(&dev->ethtool->rss_ctx, context);
12276		dev->ethtool_ops->remove_rxfh_context(dev, ctx, context, NULL);
12277		kfree(ctx);
12278	}
12279	xa_destroy(&dev->ethtool->rss_ctx);
12280	mutex_unlock(&dev->ethtool->rss_lock);
12281}
12282
12283/**
12284 *	unregister_netdevice_queue - remove device from the kernel
12285 *	@dev: device
12286 *	@head: list
12287 *
12288 *	This function shuts down a device interface and removes it
12289 *	from the kernel tables.
12290 *	If head not NULL, device is queued to be unregistered later.
12291 *
12292 *	Callers must hold the rtnl semaphore.  You may want
12293 *	unregister_netdev() instead of this.
12294 */
12295
12296void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
12297{
12298	ASSERT_RTNL();
12299
12300	if (head) {
12301		list_move_tail(&dev->unreg_list, head);
12302	} else {
12303		LIST_HEAD(single);
12304
12305		list_add(&dev->unreg_list, &single);
12306		unregister_netdevice_many(&single);
12307	}
12308}
12309EXPORT_SYMBOL(unregister_netdevice_queue);
12310
12311static void dev_memory_provider_uninstall(struct net_device *dev)
12312{
12313	unsigned int i;
12314
12315	for (i = 0; i < dev->real_num_rx_queues; i++) {
12316		struct netdev_rx_queue *rxq = &dev->_rx[i];
12317		struct pp_memory_provider_params *p = &rxq->mp_params;
12318
12319		if (p->mp_ops && p->mp_ops->uninstall)
12320			p->mp_ops->uninstall(rxq->mp_params.mp_priv, rxq);
12321	}
12322}
12323
12324/* devices must be UP and netdev_lock()'d */
12325static void netif_close_many_and_unlock(struct list_head *close_head)
12326{
12327	struct net_device *dev, *tmp;
12328
12329	netif_close_many(close_head, false);
12330
12331	/* ... now unlock them */
12332	list_for_each_entry_safe(dev, tmp, close_head, close_list) {
12333		netdev_unlock(dev);
12334		list_del_init(&dev->close_list);
12335	}
12336}
12337
12338static void netif_close_many_and_unlock_cond(struct list_head *close_head)
12339{
12340#ifdef CONFIG_LOCKDEP
12341	/* We can only track up to MAX_LOCK_DEPTH locks per task.
12342	 *
12343	 * Reserve half the available slots for additional locks possibly
12344	 * taken by notifiers and (soft)irqs.
12345	 */
12346	unsigned int limit = MAX_LOCK_DEPTH / 2;
12347
12348	if (lockdep_depth(current) > limit)
12349		netif_close_many_and_unlock(close_head);
12350#endif
12351}
12352
12353void unregister_netdevice_many_notify(struct list_head *head,
12354				      u32 portid, const struct nlmsghdr *nlh)
12355{
12356	struct net_device *dev, *tmp;
12357	LIST_HEAD(close_head);
12358	int cnt = 0;
12359
12360	BUG_ON(dev_boot_phase);
12361	ASSERT_RTNL();
12362
12363	if (list_empty(head))
12364		return;
12365
12366	list_for_each_entry_safe(dev, tmp, head, unreg_list) {
12367		/* Some devices call without registering
12368		 * for initialization unwind. Remove those
12369		 * devices and proceed with the remaining.
12370		 */
12371		if (dev->reg_state == NETREG_UNINITIALIZED) {
12372			pr_debug("unregister_netdevice: device %s/%p never was registered\n",
12373				 dev->name, dev);
12374
12375			WARN_ON(1);
12376			list_del(&dev->unreg_list);
12377			continue;
12378		}
12379		dev->dismantle = true;
12380		BUG_ON(dev->reg_state != NETREG_REGISTERED);
12381	}
12382
12383	/* If device is running, close it first. Start with ops locked... */
12384	list_for_each_entry(dev, head, unreg_list) {
12385		if (!(dev->flags & IFF_UP))
12386			continue;
12387		if (netdev_need_ops_lock(dev)) {
12388			list_add_tail(&dev->close_list, &close_head);
12389			netdev_lock(dev);
12390		}
12391		netif_close_many_and_unlock_cond(&close_head);
12392	}
12393	netif_close_many_and_unlock(&close_head);
12394	/* ... now go over the rest. */
12395	list_for_each_entry(dev, head, unreg_list) {
12396		if (!netdev_need_ops_lock(dev))
12397			list_add_tail(&dev->close_list, &close_head);
12398	}
12399	netif_close_many(&close_head, true);
12400
12401	list_for_each_entry(dev, head, unreg_list) {
12402		/* And unlink it from device chain. */
12403		unlist_netdevice(dev);
12404		netdev_lock(dev);
12405		WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERING);
12406		netdev_unlock(dev);
12407	}
12408	flush_all_backlogs();
12409
12410	synchronize_net();
12411
12412	list_for_each_entry(dev, head, unreg_list) {
12413		struct sk_buff *skb = NULL;
12414
12415		/* Shutdown queueing discipline. */
12416		netdev_lock_ops(dev);
12417		dev_shutdown(dev);
12418		dev_tcx_uninstall(dev);
12419		dev_xdp_uninstall(dev);
12420		dev_memory_provider_uninstall(dev);
12421		netdev_unlock_ops(dev);
12422		bpf_dev_bound_netdev_unregister(dev);
12423
12424		netdev_offload_xstats_disable_all(dev);
12425
12426		/* Notify protocols, that we are about to destroy
12427		 * this device. They should clean all the things.
12428		 */
12429		call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
12430
12431		if (!(dev->rtnl_link_ops && dev->rtnl_link_initializing))
12432			skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
12433						     GFP_KERNEL, NULL, 0,
12434						     portid, nlh);
12435
12436		/*
12437		 *	Flush the unicast and multicast chains
12438		 */
12439		dev_uc_flush(dev);
12440		dev_mc_flush(dev);
12441
12442		netdev_name_node_alt_flush(dev);
12443		netdev_name_node_free(dev->name_node);
12444
12445		netdev_rss_contexts_free(dev);
12446
12447		call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
12448
12449		if (dev->netdev_ops->ndo_uninit)
12450			dev->netdev_ops->ndo_uninit(dev);
12451
12452		mutex_destroy(&dev->ethtool->rss_lock);
12453
12454		net_shaper_flush_netdev(dev);
12455
12456		if (skb)
12457			rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh);
12458
12459		/* Notifier chain MUST detach us all upper devices. */
12460		WARN_ON(netdev_has_any_upper_dev(dev));
12461		WARN_ON(netdev_has_any_lower_dev(dev));
12462
12463		/* Remove entries from kobject tree */
12464		netdev_unregister_kobject(dev);
12465#ifdef CONFIG_XPS
12466		/* Remove XPS queueing entries */
12467		netif_reset_xps_queues_gt(dev, 0);
12468#endif
12469	}
12470
12471	synchronize_net();
12472
12473	list_for_each_entry(dev, head, unreg_list) {
12474		netdev_put(dev, &dev->dev_registered_tracker);
12475		net_set_todo(dev);
12476		cnt++;
12477	}
12478	atomic_add(cnt, &dev_unreg_count);
12479
12480	list_del(head);
12481}
12482
12483/**
12484 *	unregister_netdevice_many - unregister many devices
12485 *	@head: list of devices
12486 *
12487 *  Note: As most callers use a stack allocated list_head,
12488 *  we force a list_del() to make sure stack won't be corrupted later.
12489 */
12490void unregister_netdevice_many(struct list_head *head)
12491{
12492	unregister_netdevice_many_notify(head, 0, NULL);
12493}
12494EXPORT_SYMBOL(unregister_netdevice_many);
12495
12496/**
12497 *	unregister_netdev - remove device from the kernel
12498 *	@dev: device
12499 *
12500 *	This function shuts down a device interface and removes it
12501 *	from the kernel tables.
12502 *
12503 *	This is just a wrapper for unregister_netdevice that takes
12504 *	the rtnl semaphore.  In general you want to use this and not
12505 *	unregister_netdevice.
12506 */
12507void unregister_netdev(struct net_device *dev)
12508{
12509	rtnl_net_dev_lock(dev);
12510	unregister_netdevice(dev);
12511	rtnl_net_dev_unlock(dev);
12512}
12513EXPORT_SYMBOL(unregister_netdev);
12514
12515int __dev_change_net_namespace(struct net_device *dev, struct net *net,
12516			       const char *pat, int new_ifindex,
12517			       struct netlink_ext_ack *extack)
12518{
12519	struct netdev_name_node *name_node;
12520	struct net *net_old = dev_net(dev);
12521	char new_name[IFNAMSIZ] = {};
12522	int err, new_nsid;
12523
12524	ASSERT_RTNL();
12525
12526	/* Don't allow namespace local devices to be moved. */
12527	err = -EINVAL;
12528	if (dev->netns_immutable) {
12529		NL_SET_ERR_MSG(extack, "The interface netns is immutable");
12530		goto out;
12531	}
12532
12533	/* Ensure the device has been registered */
12534	if (dev->reg_state != NETREG_REGISTERED) {
12535		NL_SET_ERR_MSG(extack, "The interface isn't registered");
12536		goto out;
12537	}
12538
12539	/* Get out if there is nothing todo */
12540	err = 0;
12541	if (net_eq(net_old, net))
12542		goto out;
12543
12544	/* Pick the destination device name, and ensure
12545	 * we can use it in the destination network namespace.
12546	 */
12547	err = -EEXIST;
12548	if (netdev_name_in_use(net, dev->name)) {
12549		/* We get here if we can't use the current device name */
12550		if (!pat) {
12551			NL_SET_ERR_MSG(extack,
12552				       "An interface with the same name exists in the target netns");
12553			goto out;
12554		}
12555		err = dev_prep_valid_name(net, dev, pat, new_name, EEXIST);
12556		if (err < 0) {
12557			NL_SET_ERR_MSG_FMT(extack,
12558					   "Unable to use '%s' for the new interface name in the target netns",
12559					   pat);
12560			goto out;
12561		}
12562	}
12563	/* Check that none of the altnames conflicts. */
12564	err = -EEXIST;
12565	netdev_for_each_altname(dev, name_node) {
12566		if (netdev_name_in_use(net, name_node->name)) {
12567			NL_SET_ERR_MSG_FMT(extack,
12568					   "An interface with the altname %s exists in the target netns",
12569					   name_node->name);
12570			goto out;
12571		}
12572	}
12573
12574	/* Check that new_ifindex isn't used yet. */
12575	if (new_ifindex) {
12576		err = dev_index_reserve(net, new_ifindex);
12577		if (err < 0) {
12578			NL_SET_ERR_MSG_FMT(extack,
12579					   "The ifindex %d is not available in the target netns",
12580					   new_ifindex);
12581			goto out;
12582		}
12583	} else {
12584		/* If there is an ifindex conflict assign a new one */
12585		err = dev_index_reserve(net, dev->ifindex);
12586		if (err == -EBUSY)
12587			err = dev_index_reserve(net, 0);
12588		if (err < 0) {
12589			NL_SET_ERR_MSG(extack,
12590				       "Unable to allocate a new ifindex in the target netns");
12591			goto out;
12592		}
12593		new_ifindex = err;
12594	}
12595
12596	/*
12597	 * And now a mini version of register_netdevice unregister_netdevice.
12598	 */
12599
12600	netdev_lock_ops(dev);
12601	/* If device is running close it first. */
12602	netif_close(dev);
12603	/* And unlink it from device chain */
12604	unlist_netdevice(dev);
12605
12606	if (!netdev_need_ops_lock(dev))
12607		netdev_lock(dev);
12608	dev->moving_ns = true;
12609	netdev_unlock(dev);
12610
12611	synchronize_net();
12612
12613	/* Shutdown queueing discipline. */
12614	netdev_lock_ops(dev);
12615	dev_shutdown(dev);
12616	netdev_unlock_ops(dev);
12617
12618	/* Notify protocols, that we are about to destroy
12619	 * this device. They should clean all the things.
12620	 *
12621	 * Note that dev->reg_state stays at NETREG_REGISTERED.
12622	 * This is wanted because this way 8021q and macvlan know
12623	 * the device is just moving and can keep their slaves up.
12624	 */
12625	call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
12626	rcu_barrier();
12627
12628	new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
12629
12630	rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
12631			    new_ifindex);
12632
12633	/*
12634	 *	Flush the unicast and multicast chains
12635	 */
12636	dev_uc_flush(dev);
12637	dev_mc_flush(dev);
12638
12639	/* Send a netdev-removed uevent to the old namespace */
12640	kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
12641	netdev_adjacent_del_links(dev);
12642
12643	/* Move per-net netdevice notifiers that are following the netdevice */
12644	move_netdevice_notifiers_dev_net(dev, net);
12645
12646	/* Actually switch the network namespace */
12647	netdev_lock(dev);
12648	dev_net_set(dev, net);
12649	netdev_unlock(dev);
12650	dev->ifindex = new_ifindex;
12651
12652	if (new_name[0]) {
12653		/* Rename the netdev to prepared name */
12654		write_seqlock_bh(&netdev_rename_lock);
12655		strscpy(dev->name, new_name, IFNAMSIZ);
12656		write_sequnlock_bh(&netdev_rename_lock);
12657	}
12658
12659	/* Fixup kobjects */
12660	dev_set_uevent_suppress(&dev->dev, 1);
12661	err = device_rename(&dev->dev, dev->name);
12662	dev_set_uevent_suppress(&dev->dev, 0);
12663	WARN_ON(err);
12664
12665	/* Send a netdev-add uevent to the new namespace */
12666	kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
12667	netdev_adjacent_add_links(dev);
12668
12669	/* Adapt owner in case owning user namespace of target network
12670	 * namespace is different from the original one.
12671	 */
12672	err = netdev_change_owner(dev, net_old, net);
12673	WARN_ON(err);
12674
12675	netdev_lock(dev);
12676	dev->moving_ns = false;
12677	if (!netdev_need_ops_lock(dev))
12678		netdev_unlock(dev);
12679
12680	/* Add the device back in the hashes */
12681	list_netdevice(dev);
12682	/* Notify protocols, that a new device appeared. */
12683	call_netdevice_notifiers(NETDEV_REGISTER, dev);
12684	netdev_unlock_ops(dev);
12685
12686	/*
12687	 *	Prevent userspace races by waiting until the network
12688	 *	device is fully setup before sending notifications.
12689	 */
12690	rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
12691
12692	synchronize_net();
12693	err = 0;
12694out:
12695	return err;
12696}
12697
12698static int dev_cpu_dead(unsigned int oldcpu)
12699{
12700	struct sk_buff **list_skb;
12701	struct sk_buff *skb;
12702	unsigned int cpu;
12703	struct softnet_data *sd, *oldsd, *remsd = NULL;
12704
12705	local_irq_disable();
12706	cpu = smp_processor_id();
12707	sd = &per_cpu(softnet_data, cpu);
12708	oldsd = &per_cpu(softnet_data, oldcpu);
12709
12710	/* Find end of our completion_queue. */
12711	list_skb = &sd->completion_queue;
12712	while (*list_skb)
12713		list_skb = &(*list_skb)->next;
12714	/* Append completion queue from offline CPU. */
12715	*list_skb = oldsd->completion_queue;
12716	oldsd->completion_queue = NULL;
12717
12718	/* Append output queue from offline CPU. */
12719	if (oldsd->output_queue) {
12720		*sd->output_queue_tailp = oldsd->output_queue;
12721		sd->output_queue_tailp = oldsd->output_queue_tailp;
12722		oldsd->output_queue = NULL;
12723		oldsd->output_queue_tailp = &oldsd->output_queue;
12724	}
12725	/* Append NAPI poll list from offline CPU, with one exception :
12726	 * process_backlog() must be called by cpu owning percpu backlog.
12727	 * We properly handle process_queue & input_pkt_queue later.
12728	 */
12729	while (!list_empty(&oldsd->poll_list)) {
12730		struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
12731							    struct napi_struct,
12732							    poll_list);
12733
12734		list_del_init(&napi->poll_list);
12735		if (napi->poll == process_backlog)
12736			napi->state &= NAPIF_STATE_THREADED;
12737		else
12738			____napi_schedule(sd, napi);
12739	}
12740
12741	raise_softirq_irqoff(NET_TX_SOFTIRQ);
12742	local_irq_enable();
12743
12744	if (!use_backlog_threads()) {
12745#ifdef CONFIG_RPS
12746		remsd = oldsd->rps_ipi_list;
12747		oldsd->rps_ipi_list = NULL;
12748#endif
12749		/* send out pending IPI's on offline CPU */
12750		net_rps_send_ipi(remsd);
12751	}
12752
12753	/* Process offline CPU's input_pkt_queue */
12754	while ((skb = __skb_dequeue(&oldsd->process_queue))) {
12755		netif_rx(skb);
12756		rps_input_queue_head_incr(oldsd);
12757	}
12758	while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
12759		netif_rx(skb);
12760		rps_input_queue_head_incr(oldsd);
12761	}
12762
12763	return 0;
12764}
12765
12766/**
12767 *	netdev_increment_features - increment feature set by one
12768 *	@all: current feature set
12769 *	@one: new feature set
12770 *	@mask: mask feature set
12771 *
12772 *	Computes a new feature set after adding a device with feature set
12773 *	@one to the master device with current feature set @all.  Will not
12774 *	enable anything that is off in @mask. Returns the new feature set.
12775 */
12776netdev_features_t netdev_increment_features(netdev_features_t all,
12777	netdev_features_t one, netdev_features_t mask)
12778{
12779	if (mask & NETIF_F_HW_CSUM)
12780		mask |= NETIF_F_CSUM_MASK;
12781	mask |= NETIF_F_VLAN_CHALLENGED;
12782
12783	all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
12784	all &= one | ~NETIF_F_ALL_FOR_ALL;
12785
12786	/* If one device supports hw checksumming, set for all. */
12787	if (all & NETIF_F_HW_CSUM)
12788		all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
12789
12790	return all;
12791}
12792EXPORT_SYMBOL(netdev_increment_features);
12793
12794/**
12795 *	netdev_compute_master_upper_features - compute feature from lowers
12796 *	@dev: the upper device
12797 *	@update_header: whether to update upper device's header_len/headroom/tailroom
12798 *
12799 *	Recompute the upper device's feature based on all lower devices.
12800 */
12801void netdev_compute_master_upper_features(struct net_device *dev, bool update_header)
12802{
12803	unsigned int dst_release_flag = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
12804	netdev_features_t gso_partial_features = MASTER_UPPER_DEV_GSO_PARTIAL_FEATURES;
12805	netdev_features_t xfrm_features = MASTER_UPPER_DEV_XFRM_FEATURES;
12806	netdev_features_t mpls_features = MASTER_UPPER_DEV_MPLS_FEATURES;
12807	netdev_features_t vlan_features = MASTER_UPPER_DEV_VLAN_FEATURES;
12808	netdev_features_t enc_features = MASTER_UPPER_DEV_ENC_FEATURES;
12809	unsigned short max_header_len = ETH_HLEN;
12810	unsigned int tso_max_size = TSO_MAX_SIZE;
12811	unsigned short max_headroom = 0;
12812	unsigned short max_tailroom = 0;
12813	u16 tso_max_segs = TSO_MAX_SEGS;
12814	struct net_device *lower_dev;
12815	struct list_head *iter;
12816
12817	mpls_features = netdev_base_features(mpls_features);
12818	vlan_features = netdev_base_features(vlan_features);
12819	enc_features = netdev_base_features(enc_features);
12820
12821	netdev_for_each_lower_dev(dev, lower_dev, iter) {
12822		gso_partial_features = netdev_increment_features(gso_partial_features,
12823								 lower_dev->gso_partial_features,
12824								 MASTER_UPPER_DEV_GSO_PARTIAL_FEATURES);
12825
12826		vlan_features = netdev_increment_features(vlan_features,
12827							  lower_dev->vlan_features,
12828							  MASTER_UPPER_DEV_VLAN_FEATURES);
12829
12830		enc_features = netdev_increment_features(enc_features,
12831							 lower_dev->hw_enc_features,
12832							 MASTER_UPPER_DEV_ENC_FEATURES);
12833
12834		if (IS_ENABLED(CONFIG_XFRM_OFFLOAD))
12835			xfrm_features = netdev_increment_features(xfrm_features,
12836								  lower_dev->hw_enc_features,
12837								  MASTER_UPPER_DEV_XFRM_FEATURES);
12838
12839		mpls_features = netdev_increment_features(mpls_features,
12840							  lower_dev->mpls_features,
12841							  MASTER_UPPER_DEV_MPLS_FEATURES);
12842
12843		dst_release_flag &= lower_dev->priv_flags;
12844
12845		if (update_header) {
12846			max_header_len = max(max_header_len, lower_dev->hard_header_len);
12847			max_headroom = max(max_headroom, lower_dev->needed_headroom);
12848			max_tailroom = max(max_tailroom, lower_dev->needed_tailroom);
12849		}
12850
12851		tso_max_size = min(tso_max_size, lower_dev->tso_max_size);
12852		tso_max_segs = min(tso_max_segs, lower_dev->tso_max_segs);
12853	}
12854
12855	dev->gso_partial_features = gso_partial_features;
12856	dev->vlan_features = vlan_features;
12857	dev->hw_enc_features = enc_features | NETIF_F_GSO_ENCAP_ALL |
12858			       NETIF_F_HW_VLAN_CTAG_TX |
12859			       NETIF_F_HW_VLAN_STAG_TX;
12860	if (IS_ENABLED(CONFIG_XFRM_OFFLOAD))
12861		dev->hw_enc_features |= xfrm_features;
12862	dev->mpls_features = mpls_features;
12863
12864	dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
12865	if ((dev->priv_flags & IFF_XMIT_DST_RELEASE_PERM) &&
12866	    dst_release_flag == (IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM))
12867		dev->priv_flags |= IFF_XMIT_DST_RELEASE;
12868
12869	if (update_header) {
12870		dev->hard_header_len = max_header_len;
12871		dev->needed_headroom = max_headroom;
12872		dev->needed_tailroom = max_tailroom;
12873	}
12874
12875	netif_set_tso_max_segs(dev, tso_max_segs);
12876	netif_set_tso_max_size(dev, tso_max_size);
12877
12878	netdev_change_features(dev);
12879}
12880EXPORT_SYMBOL(netdev_compute_master_upper_features);
12881
12882static struct hlist_head * __net_init netdev_create_hash(void)
12883{
12884	int i;
12885	struct hlist_head *hash;
12886
12887	hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
12888	if (hash != NULL)
12889		for (i = 0; i < NETDEV_HASHENTRIES; i++)
12890			INIT_HLIST_HEAD(&hash[i]);
12891
12892	return hash;
12893}
12894
12895/* Initialize per network namespace state */
12896static int __net_init netdev_init(struct net *net)
12897{
12898	BUILD_BUG_ON(GRO_HASH_BUCKETS >
12899		     BITS_PER_BYTE * sizeof_field(struct gro_node, bitmask));
12900
12901	INIT_LIST_HEAD(&net->dev_base_head);
12902
12903	net->dev_name_head = netdev_create_hash();
12904	if (net->dev_name_head == NULL)
12905		goto err_name;
12906
12907	net->dev_index_head = netdev_create_hash();
12908	if (net->dev_index_head == NULL)
12909		goto err_idx;
12910
12911	xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1);
12912
12913	RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
12914
12915	return 0;
12916
12917err_idx:
12918	kfree(net->dev_name_head);
12919err_name:
12920	return -ENOMEM;
12921}
12922
12923/**
12924 *	netdev_drivername - network driver for the device
12925 *	@dev: network device
12926 *
12927 *	Determine network driver for device.
12928 */
12929const char *netdev_drivername(const struct net_device *dev)
12930{
12931	const struct device_driver *driver;
12932	const struct device *parent;
12933	const char *empty = "";
12934
12935	parent = dev->dev.parent;
12936	if (!parent)
12937		return empty;
12938
12939	driver = parent->driver;
12940	if (driver && driver->name)
12941		return driver->name;
12942	return empty;
12943}
12944
12945static void __netdev_printk(const char *level, const struct net_device *dev,
12946			    struct va_format *vaf)
12947{
12948	if (dev && dev->dev.parent) {
12949		dev_printk_emit(level[1] - '0',
12950				dev->dev.parent,
12951				"%s %s %s%s: %pV",
12952				dev_driver_string(dev->dev.parent),
12953				dev_name(dev->dev.parent),
12954				netdev_name(dev), netdev_reg_state(dev),
12955				vaf);
12956	} else if (dev) {
12957		printk("%s%s%s: %pV",
12958		       level, netdev_name(dev), netdev_reg_state(dev), vaf);
12959	} else {
12960		printk("%s(NULL net_device): %pV", level, vaf);
12961	}
12962}
12963
12964void netdev_printk(const char *level, const struct net_device *dev,
12965		   const char *format, ...)
12966{
12967	struct va_format vaf;
12968	va_list args;
12969
12970	va_start(args, format);
12971
12972	vaf.fmt = format;
12973	vaf.va = &args;
12974
12975	__netdev_printk(level, dev, &vaf);
12976
12977	va_end(args);
12978}
12979EXPORT_SYMBOL(netdev_printk);
12980
12981#define define_netdev_printk_level(func, level)			\
12982void func(const struct net_device *dev, const char *fmt, ...)	\
12983{								\
12984	struct va_format vaf;					\
12985	va_list args;						\
12986								\
12987	va_start(args, fmt);					\
12988								\
12989	vaf.fmt = fmt;						\
12990	vaf.va = &args;						\
12991								\
12992	__netdev_printk(level, dev, &vaf);			\
12993								\
12994	va_end(args);						\
12995}								\
12996EXPORT_SYMBOL(func);
12997
12998define_netdev_printk_level(netdev_emerg, KERN_EMERG);
12999define_netdev_printk_level(netdev_alert, KERN_ALERT);
13000define_netdev_printk_level(netdev_crit, KERN_CRIT);
13001define_netdev_printk_level(netdev_err, KERN_ERR);
13002define_netdev_printk_level(netdev_warn, KERN_WARNING);
13003define_netdev_printk_level(netdev_notice, KERN_NOTICE);
13004define_netdev_printk_level(netdev_info, KERN_INFO);
13005
13006static void __net_exit netdev_exit(struct net *net)
13007{
13008	kfree(net->dev_name_head);
13009	kfree(net->dev_index_head);
13010	xa_destroy(&net->dev_by_index);
13011	if (net != &init_net)
13012		WARN_ON_ONCE(!list_empty(&net->dev_base_head));
13013}
13014
13015static struct pernet_operations __net_initdata netdev_net_ops = {
13016	.init = netdev_init,
13017	.exit = netdev_exit,
13018};
13019
13020static void __net_exit default_device_exit_net(struct net *net)
13021{
13022	struct netdev_name_node *name_node, *tmp;
13023	struct net_device *dev, *aux;
13024	/*
13025	 * Push all migratable network devices back to the
13026	 * initial network namespace
13027	 */
13028	ASSERT_RTNL();
13029	for_each_netdev_safe(net, dev, aux) {
13030		int err;
13031		char fb_name[IFNAMSIZ];
13032
13033		/* Ignore unmoveable devices (i.e. loopback) */
13034		if (dev->netns_immutable)
13035			continue;
13036
13037		/* Leave virtual devices for the generic cleanup */
13038		if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
13039			continue;
13040
13041		/* Push remaining network devices to init_net */
13042		snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
13043		if (netdev_name_in_use(&init_net, fb_name))
13044			snprintf(fb_name, IFNAMSIZ, "dev%%d");
13045
13046		netdev_for_each_altname_safe(dev, name_node, tmp)
13047			if (netdev_name_in_use(&init_net, name_node->name))
13048				__netdev_name_node_alt_destroy(name_node);
13049
13050		err = dev_change_net_namespace(dev, &init_net, fb_name);
13051		if (err) {
13052			pr_emerg("%s: failed to move %s to init_net: %d\n",
13053				 __func__, dev->name, err);
13054			BUG();
13055		}
13056	}
13057}
13058
13059static void __net_exit default_device_exit_batch(struct list_head *net_list)
13060{
13061	/* At exit all network devices most be removed from a network
13062	 * namespace.  Do this in the reverse order of registration.
13063	 * Do this across as many network namespaces as possible to
13064	 * improve batching efficiency.
13065	 */
13066	struct net_device *dev;
13067	struct net *net;
13068	LIST_HEAD(dev_kill_list);
13069
13070	rtnl_lock();
13071	list_for_each_entry(net, net_list, exit_list) {
13072		default_device_exit_net(net);
13073		cond_resched();
13074	}
13075
13076	list_for_each_entry(net, net_list, exit_list) {
13077		for_each_netdev_reverse(net, dev) {
13078			if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
13079				dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
13080			else
13081				unregister_netdevice_queue(dev, &dev_kill_list);
13082		}
13083	}
13084	unregister_netdevice_many(&dev_kill_list);
13085	rtnl_unlock();
13086}
13087
13088static struct pernet_operations __net_initdata default_device_ops = {
13089	.exit_batch = default_device_exit_batch,
13090};
13091
13092static void __init net_dev_struct_check(void)
13093{
13094	/* TX read-mostly hotpath */
13095	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, priv_flags_fast);
13096	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, netdev_ops);
13097	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, header_ops);
13098	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, _tx);
13099	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, real_num_tx_queues);
13100	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_size);
13101	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_ipv4_max_size);
13102	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_segs);
13103	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_partial_features);
13104	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, num_tc);
13105	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, mtu);
13106	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, needed_headroom);
13107	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tc_to_txq);
13108#ifdef CONFIG_XPS
13109	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, xps_maps);
13110#endif
13111#ifdef CONFIG_NETFILTER_EGRESS
13112	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, nf_hooks_egress);
13113#endif
13114#ifdef CONFIG_NET_XGRESS
13115	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tcx_egress);
13116#endif
13117	CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_tx, 160);
13118
13119	/* TXRX read-mostly hotpath */
13120	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, lstats);
13121	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, state);
13122	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, flags);
13123	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, hard_header_len);
13124	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, features);
13125	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, ip6_ptr);
13126	CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_txrx, 46);
13127
13128	/* RX read-mostly hotpath */
13129	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ptype_specific);
13130	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ifindex);
13131	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, real_num_rx_queues);
13132	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, _rx);
13133	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_max_size);
13134	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_ipv4_max_size);
13135	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler);
13136	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler_data);
13137	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, nd_net);
13138#ifdef CONFIG_NETPOLL
13139	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, npinfo);
13140#endif
13141#ifdef CONFIG_NET_XGRESS
13142	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, tcx_ingress);
13143#endif
13144	CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_rx, 92);
13145}
13146
13147/*
13148 *	Initialize the DEV module. At boot time this walks the device list and
13149 *	unhooks any devices that fail to initialise (normally hardware not
13150 *	present) and leaves us with a valid list of present and active devices.
13151 *
13152 */
13153
13154/* We allocate 256 pages for each CPU if PAGE_SHIFT is 12 */
13155#define SYSTEM_PERCPU_PAGE_POOL_SIZE	((1 << 20) / PAGE_SIZE)
13156
13157static int net_page_pool_create(int cpuid)
13158{
13159#if IS_ENABLED(CONFIG_PAGE_POOL)
13160	struct page_pool_params page_pool_params = {
13161		.pool_size = SYSTEM_PERCPU_PAGE_POOL_SIZE,
13162		.flags = PP_FLAG_SYSTEM_POOL,
13163		.nid = cpu_to_mem(cpuid),
13164	};
13165	struct page_pool *pp_ptr;
13166	int err;
13167
13168	pp_ptr = page_pool_create_percpu(&page_pool_params, cpuid);
13169	if (IS_ERR(pp_ptr))
13170		return -ENOMEM;
13171
13172	err = xdp_reg_page_pool(pp_ptr);
13173	if (err) {
13174		page_pool_destroy(pp_ptr);
13175		return err;
13176	}
13177
13178	per_cpu(system_page_pool.pool, cpuid) = pp_ptr;
13179#endif
13180	return 0;
13181}
13182
13183static int backlog_napi_should_run(unsigned int cpu)
13184{
13185	struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
13186	struct napi_struct *napi = &sd->backlog;
13187
13188	return test_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
13189}
13190
13191static void run_backlog_napi(unsigned int cpu)
13192{
13193	struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
13194
13195	napi_threaded_poll_loop(&sd->backlog, NULL);
13196}
13197
13198static void backlog_napi_setup(unsigned int cpu)
13199{
13200	struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
13201	struct napi_struct *napi = &sd->backlog;
13202
13203	napi->thread = this_cpu_read(backlog_napi);
13204	set_bit(NAPI_STATE_THREADED, &napi->state);
13205}
13206
13207static struct smp_hotplug_thread backlog_threads = {
13208	.store			= &backlog_napi,
13209	.thread_should_run	= backlog_napi_should_run,
13210	.thread_fn		= run_backlog_napi,
13211	.thread_comm		= "backlog_napi/%u",
13212	.setup			= backlog_napi_setup,
13213};
13214
13215/*
13216 *       This is called single threaded during boot, so no need
13217 *       to take the rtnl semaphore.
13218 */
13219static int __init net_dev_init(void)
13220{
13221	int i, rc = -ENOMEM;
13222
13223	BUG_ON(!dev_boot_phase);
13224
13225	net_dev_struct_check();
13226
13227	if (dev_proc_init())
13228		goto out;
13229
13230	if (netdev_kobject_init())
13231		goto out;
13232
13233	for (i = 0; i < PTYPE_HASH_SIZE; i++)
13234		INIT_LIST_HEAD(&ptype_base[i]);
13235
13236	if (register_pernet_subsys(&netdev_net_ops))
13237		goto out;
13238
13239	/*
13240	 *	Initialise the packet receive queues.
13241	 */
13242
13243	flush_backlogs_fallback = flush_backlogs_alloc();
13244	if (!flush_backlogs_fallback)
13245		goto out;
13246
13247	for_each_possible_cpu(i) {
13248		struct softnet_data *sd = &per_cpu(softnet_data, i);
13249
13250		skb_queue_head_init(&sd->input_pkt_queue);
13251		skb_queue_head_init(&sd->process_queue);
13252#ifdef CONFIG_XFRM_OFFLOAD
13253		skb_queue_head_init(&sd->xfrm_backlog);
13254#endif
13255		INIT_LIST_HEAD(&sd->poll_list);
13256		sd->output_queue_tailp = &sd->output_queue;
13257#ifdef CONFIG_RPS
13258		INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
13259		sd->cpu = i;
13260#endif
13261		INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd);
13262
13263		gro_init(&sd->backlog.gro);
13264		sd->backlog.poll = process_backlog;
13265		sd->backlog.weight = weight_p;
13266		INIT_LIST_HEAD(&sd->backlog.poll_list);
13267
13268		if (net_page_pool_create(i))
13269			goto out;
13270	}
13271	net_hotdata.skb_defer_nodes =
13272		 __alloc_percpu(sizeof(struct skb_defer_node) * nr_node_ids,
13273				__alignof__(struct skb_defer_node));
13274	if (!net_hotdata.skb_defer_nodes)
13275		goto out;
13276	if (use_backlog_threads())
13277		smpboot_register_percpu_thread(&backlog_threads);
13278
13279	dev_boot_phase = 0;
13280
13281	/* The loopback device is special if any other network devices
13282	 * is present in a network namespace the loopback device must
13283	 * be present. Since we now dynamically allocate and free the
13284	 * loopback device ensure this invariant is maintained by
13285	 * keeping the loopback device as the first device on the
13286	 * list of network devices.  Ensuring the loopback devices
13287	 * is the first device that appears and the last network device
13288	 * that disappears.
13289	 */
13290	if (register_pernet_device(&loopback_net_ops))
13291		goto out;
13292
13293	if (register_pernet_device(&default_device_ops))
13294		goto out;
13295
13296	open_softirq(NET_TX_SOFTIRQ, net_tx_action);
13297	open_softirq(NET_RX_SOFTIRQ, net_rx_action);
13298
13299	rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
13300				       NULL, dev_cpu_dead);
13301	WARN_ON(rc < 0);
13302	rc = 0;
13303
13304	/* avoid static key IPIs to isolated CPUs */
13305	if (housekeeping_enabled(HK_TYPE_MISC))
13306		net_enable_timestamp();
13307out:
13308	if (rc < 0) {
13309		for_each_possible_cpu(i) {
13310			struct page_pool *pp_ptr;
13311
13312			pp_ptr = per_cpu(system_page_pool.pool, i);
13313			if (!pp_ptr)
13314				continue;
13315
13316			xdp_unreg_page_pool(pp_ptr);
13317			page_pool_destroy(pp_ptr);
13318			per_cpu(system_page_pool.pool, i) = NULL;
13319		}
13320	}
13321
13322	return rc;
13323}
13324
13325subsys_initcall(net_dev_init);
~/ Read-only file preview.