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