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