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