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