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