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