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