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