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