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