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