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