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