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