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