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