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