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