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