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