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