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