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