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