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