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