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