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