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