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