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