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