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