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