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