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