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