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