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