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