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