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