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