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