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