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