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