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