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