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