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