xref: /linux/net/core/dev.c (revision c7170e7672e52cf38f5979416d20b9133a10726e)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *      NET3    Protocol independent device support routines.
4  *
5  *	Derived from the non IP parts of dev.c 1.0.19
6  *              Authors:	Ross Biro
7  *				Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
8  *				Mark Evans, <evansmp@uhura.aston.ac.uk>
9  *
10  *	Additional Authors:
11  *		Florian la Roche <rzsfl@rz.uni-sb.de>
12  *		Alan Cox <gw4pts@gw4pts.ampr.org>
13  *		David Hinds <dahinds@users.sourceforge.net>
14  *		Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
15  *		Adam Sulmicki <adam@cfar.umd.edu>
16  *              Pekka Riikonen <priikone@poesidon.pspt.fi>
17  *
18  *	Changes:
19  *              D.J. Barrow     :       Fixed bug where dev->refcnt gets set
20  *                                      to 2 if register_netdev gets called
21  *                                      before net_dev_init & also removed a
22  *                                      few lines of code in the process.
23  *		Alan Cox	:	device private ioctl copies fields back.
24  *		Alan Cox	:	Transmit queue code does relevant
25  *					stunts to keep the queue safe.
26  *		Alan Cox	:	Fixed double lock.
27  *		Alan Cox	:	Fixed promisc NULL pointer trap
28  *		????????	:	Support the full private ioctl range
29  *		Alan Cox	:	Moved ioctl permission check into
30  *					drivers
31  *		Tim Kordas	:	SIOCADDMULTI/SIOCDELMULTI
32  *		Alan Cox	:	100 backlog just doesn't cut it when
33  *					you start doing multicast video 8)
34  *		Alan Cox	:	Rewrote net_bh and list manager.
35  *              Alan Cox        :       Fix ETH_P_ALL echoback lengths.
36  *		Alan Cox	:	Took out transmit every packet pass
37  *					Saved a few bytes in the ioctl handler
38  *		Alan Cox	:	Network driver sets packet type before
39  *					calling netif_rx. Saves a function
40  *					call a packet.
41  *		Alan Cox	:	Hashed net_bh()
42  *		Richard Kooijman:	Timestamp fixes.
43  *		Alan Cox	:	Wrong field in SIOCGIFDSTADDR
44  *		Alan Cox	:	Device lock protection.
45  *              Alan Cox        :       Fixed nasty side effect of device close
46  *					changes.
47  *		Rudi Cilibrasi	:	Pass the right thing to
48  *					set_mac_address()
49  *		Dave Miller	:	32bit quantity for the device lock to
50  *					make it work out on a Sparc.
51  *		Bjorn Ekwall	:	Added KERNELD hack.
52  *		Alan Cox	:	Cleaned up the backlog initialise.
53  *		Craig Metz	:	SIOCGIFCONF fix if space for under
54  *					1 device.
55  *	    Thomas Bogendoerfer :	Return ENODEV for dev_open, if there
56  *					is no device open function.
57  *		Andi Kleen	:	Fix error reporting for SIOCGIFCONF
58  *	    Michael Chastain	:	Fix signed/unsigned for SIOCGIFCONF
59  *		Cyrus Durgin	:	Cleaned for KMOD
60  *		Adam Sulmicki   :	Bug Fix : Network Device Unload
61  *					A network device unload needs to purge
62  *					the backlog queue.
63  *	Paul Rusty Russell	:	SIOCSIFNAME
64  *              Pekka Riikonen  :	Netdev boot-time settings code
65  *              Andrew Morton   :       Make unregister_netdevice wait
66  *                                      indefinitely on dev->refcnt
67  *              J Hadi Salim    :       - Backlog queue sampling
68  *				        - netif_rx() feedback
69  */
70 
71 #include <linux/uaccess.h>
72 #include <linux/bitmap.h>
73 #include <linux/capability.h>
74 #include <linux/cpu.h>
75 #include <linux/types.h>
76 #include <linux/kernel.h>
77 #include <linux/hash.h>
78 #include <linux/slab.h>
79 #include <linux/sched.h>
80 #include <linux/sched/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 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 (miquels@drinkel.ow.org)
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 #if defined(CONFIG_NET_RX_BUSY_POLL)
6177 
6178 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
6179 {
6180 	if (!skip_schedule) {
6181 		gro_normal_list(napi);
6182 		__napi_schedule(napi);
6183 		return;
6184 	}
6185 
6186 	if (napi->gro_bitmask) {
6187 		/* flush too old packets
6188 		 * If HZ < 1000, flush all packets.
6189 		 */
6190 		napi_gro_flush(napi, HZ >= 1000);
6191 	}
6192 
6193 	gro_normal_list(napi);
6194 	clear_bit(NAPI_STATE_SCHED, &napi->state);
6195 }
6196 
6197 enum {
6198 	NAPI_F_PREFER_BUSY_POLL	= 1,
6199 	NAPI_F_END_ON_RESCHED	= 2,
6200 };
6201 
6202 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock,
6203 			   unsigned flags, u16 budget)
6204 {
6205 	bool skip_schedule = false;
6206 	unsigned long timeout;
6207 	int rc;
6208 
6209 	/* Busy polling means there is a high chance device driver hard irq
6210 	 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6211 	 * set in napi_schedule_prep().
6212 	 * Since we are about to call napi->poll() once more, we can safely
6213 	 * clear NAPI_STATE_MISSED.
6214 	 *
6215 	 * Note: x86 could use a single "lock and ..." instruction
6216 	 * to perform these two clear_bit()
6217 	 */
6218 	clear_bit(NAPI_STATE_MISSED, &napi->state);
6219 	clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6220 
6221 	local_bh_disable();
6222 
6223 	if (flags & NAPI_F_PREFER_BUSY_POLL) {
6224 		napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
6225 		timeout = READ_ONCE(napi->dev->gro_flush_timeout);
6226 		if (napi->defer_hard_irqs_count && timeout) {
6227 			hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
6228 			skip_schedule = true;
6229 		}
6230 	}
6231 
6232 	/* All we really want here is to re-enable device interrupts.
6233 	 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6234 	 */
6235 	rc = napi->poll(napi, budget);
6236 	/* We can't gro_normal_list() here, because napi->poll() might have
6237 	 * rearmed the napi (napi_complete_done()) in which case it could
6238 	 * already be running on another CPU.
6239 	 */
6240 	trace_napi_poll(napi, rc, budget);
6241 	netpoll_poll_unlock(have_poll_lock);
6242 	if (rc == budget)
6243 		__busy_poll_stop(napi, skip_schedule);
6244 	local_bh_enable();
6245 }
6246 
6247 static void __napi_busy_loop(unsigned int napi_id,
6248 		      bool (*loop_end)(void *, unsigned long),
6249 		      void *loop_end_arg, unsigned flags, u16 budget)
6250 {
6251 	unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6252 	int (*napi_poll)(struct napi_struct *napi, int budget);
6253 	void *have_poll_lock = NULL;
6254 	struct napi_struct *napi;
6255 
6256 	WARN_ON_ONCE(!rcu_read_lock_held());
6257 
6258 restart:
6259 	napi_poll = NULL;
6260 
6261 	napi = napi_by_id(napi_id);
6262 	if (!napi)
6263 		return;
6264 
6265 	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6266 		preempt_disable();
6267 	for (;;) {
6268 		int work = 0;
6269 
6270 		local_bh_disable();
6271 		if (!napi_poll) {
6272 			unsigned long val = READ_ONCE(napi->state);
6273 
6274 			/* If multiple threads are competing for this napi,
6275 			 * we avoid dirtying napi->state as much as we can.
6276 			 */
6277 			if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6278 				   NAPIF_STATE_IN_BUSY_POLL)) {
6279 				if (flags & NAPI_F_PREFER_BUSY_POLL)
6280 					set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6281 				goto count;
6282 			}
6283 			if (cmpxchg(&napi->state, val,
6284 				    val | NAPIF_STATE_IN_BUSY_POLL |
6285 					  NAPIF_STATE_SCHED) != val) {
6286 				if (flags & NAPI_F_PREFER_BUSY_POLL)
6287 					set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6288 				goto count;
6289 			}
6290 			have_poll_lock = netpoll_poll_lock(napi);
6291 			napi_poll = napi->poll;
6292 		}
6293 		work = napi_poll(napi, budget);
6294 		trace_napi_poll(napi, work, budget);
6295 		gro_normal_list(napi);
6296 count:
6297 		if (work > 0)
6298 			__NET_ADD_STATS(dev_net(napi->dev),
6299 					LINUX_MIB_BUSYPOLLRXPACKETS, work);
6300 		local_bh_enable();
6301 
6302 		if (!loop_end || loop_end(loop_end_arg, start_time))
6303 			break;
6304 
6305 		if (unlikely(need_resched())) {
6306 			if (flags & NAPI_F_END_ON_RESCHED)
6307 				break;
6308 			if (napi_poll)
6309 				busy_poll_stop(napi, have_poll_lock, flags, budget);
6310 			if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6311 				preempt_enable();
6312 			rcu_read_unlock();
6313 			cond_resched();
6314 			rcu_read_lock();
6315 			if (loop_end(loop_end_arg, start_time))
6316 				return;
6317 			goto restart;
6318 		}
6319 		cpu_relax();
6320 	}
6321 	if (napi_poll)
6322 		busy_poll_stop(napi, have_poll_lock, flags, budget);
6323 	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6324 		preempt_enable();
6325 }
6326 
6327 void napi_busy_loop_rcu(unsigned int napi_id,
6328 			bool (*loop_end)(void *, unsigned long),
6329 			void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6330 {
6331 	unsigned flags = NAPI_F_END_ON_RESCHED;
6332 
6333 	if (prefer_busy_poll)
6334 		flags |= NAPI_F_PREFER_BUSY_POLL;
6335 
6336 	__napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget);
6337 }
6338 
6339 void napi_busy_loop(unsigned int napi_id,
6340 		    bool (*loop_end)(void *, unsigned long),
6341 		    void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6342 {
6343 	unsigned flags = prefer_busy_poll ? NAPI_F_PREFER_BUSY_POLL : 0;
6344 
6345 	rcu_read_lock();
6346 	__napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget);
6347 	rcu_read_unlock();
6348 }
6349 EXPORT_SYMBOL(napi_busy_loop);
6350 
6351 #endif /* CONFIG_NET_RX_BUSY_POLL */
6352 
6353 static void napi_hash_add(struct napi_struct *napi)
6354 {
6355 	if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6356 		return;
6357 
6358 	spin_lock(&napi_hash_lock);
6359 
6360 	/* 0..NR_CPUS range is reserved for sender_cpu use */
6361 	do {
6362 		if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6363 			napi_gen_id = MIN_NAPI_ID;
6364 	} while (napi_by_id(napi_gen_id));
6365 	napi->napi_id = napi_gen_id;
6366 
6367 	hlist_add_head_rcu(&napi->napi_hash_node,
6368 			   &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6369 
6370 	spin_unlock(&napi_hash_lock);
6371 }
6372 
6373 /* Warning : caller is responsible to make sure rcu grace period
6374  * is respected before freeing memory containing @napi
6375  */
6376 static void napi_hash_del(struct napi_struct *napi)
6377 {
6378 	spin_lock(&napi_hash_lock);
6379 
6380 	hlist_del_init_rcu(&napi->napi_hash_node);
6381 
6382 	spin_unlock(&napi_hash_lock);
6383 }
6384 
6385 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6386 {
6387 	struct napi_struct *napi;
6388 
6389 	napi = container_of(timer, struct napi_struct, timer);
6390 
6391 	/* Note : we use a relaxed variant of napi_schedule_prep() not setting
6392 	 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6393 	 */
6394 	if (!napi_disable_pending(napi) &&
6395 	    !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
6396 		clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6397 		__napi_schedule_irqoff(napi);
6398 	}
6399 
6400 	return HRTIMER_NORESTART;
6401 }
6402 
6403 static void init_gro_hash(struct napi_struct *napi)
6404 {
6405 	int i;
6406 
6407 	for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6408 		INIT_LIST_HEAD(&napi->gro_hash[i].list);
6409 		napi->gro_hash[i].count = 0;
6410 	}
6411 	napi->gro_bitmask = 0;
6412 }
6413 
6414 int dev_set_threaded(struct net_device *dev, bool threaded)
6415 {
6416 	struct napi_struct *napi;
6417 	int err = 0;
6418 
6419 	if (dev->threaded == threaded)
6420 		return 0;
6421 
6422 	if (threaded) {
6423 		list_for_each_entry(napi, &dev->napi_list, dev_list) {
6424 			if (!napi->thread) {
6425 				err = napi_kthread_create(napi);
6426 				if (err) {
6427 					threaded = false;
6428 					break;
6429 				}
6430 			}
6431 		}
6432 	}
6433 
6434 	dev->threaded = threaded;
6435 
6436 	/* Make sure kthread is created before THREADED bit
6437 	 * is set.
6438 	 */
6439 	smp_mb__before_atomic();
6440 
6441 	/* Setting/unsetting threaded mode on a napi might not immediately
6442 	 * take effect, if the current napi instance is actively being
6443 	 * polled. In this case, the switch between threaded mode and
6444 	 * softirq mode will happen in the next round of napi_schedule().
6445 	 * This should not cause hiccups/stalls to the live traffic.
6446 	 */
6447 	list_for_each_entry(napi, &dev->napi_list, dev_list)
6448 		assign_bit(NAPI_STATE_THREADED, &napi->state, threaded);
6449 
6450 	return err;
6451 }
6452 EXPORT_SYMBOL(dev_set_threaded);
6453 
6454 /**
6455  * netif_queue_set_napi - Associate queue with the napi
6456  * @dev: device to which NAPI and queue belong
6457  * @queue_index: Index of queue
6458  * @type: queue type as RX or TX
6459  * @napi: NAPI context, pass NULL to clear previously set NAPI
6460  *
6461  * Set queue with its corresponding napi context. This should be done after
6462  * registering the NAPI handler for the queue-vector and the queues have been
6463  * mapped to the corresponding interrupt vector.
6464  */
6465 void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index,
6466 			  enum netdev_queue_type type, struct napi_struct *napi)
6467 {
6468 	struct netdev_rx_queue *rxq;
6469 	struct netdev_queue *txq;
6470 
6471 	if (WARN_ON_ONCE(napi && !napi->dev))
6472 		return;
6473 	if (dev->reg_state >= NETREG_REGISTERED)
6474 		ASSERT_RTNL();
6475 
6476 	switch (type) {
6477 	case NETDEV_QUEUE_TYPE_RX:
6478 		rxq = __netif_get_rx_queue(dev, queue_index);
6479 		rxq->napi = napi;
6480 		return;
6481 	case NETDEV_QUEUE_TYPE_TX:
6482 		txq = netdev_get_tx_queue(dev, queue_index);
6483 		txq->napi = napi;
6484 		return;
6485 	default:
6486 		return;
6487 	}
6488 }
6489 EXPORT_SYMBOL(netif_queue_set_napi);
6490 
6491 void netif_napi_add_weight(struct net_device *dev, struct napi_struct *napi,
6492 			   int (*poll)(struct napi_struct *, int), int weight)
6493 {
6494 	if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6495 		return;
6496 
6497 	INIT_LIST_HEAD(&napi->poll_list);
6498 	INIT_HLIST_NODE(&napi->napi_hash_node);
6499 	hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6500 	napi->timer.function = napi_watchdog;
6501 	init_gro_hash(napi);
6502 	napi->skb = NULL;
6503 	INIT_LIST_HEAD(&napi->rx_list);
6504 	napi->rx_count = 0;
6505 	napi->poll = poll;
6506 	if (weight > NAPI_POLL_WEIGHT)
6507 		netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6508 				weight);
6509 	napi->weight = weight;
6510 	napi->dev = dev;
6511 #ifdef CONFIG_NETPOLL
6512 	napi->poll_owner = -1;
6513 #endif
6514 	napi->list_owner = -1;
6515 	set_bit(NAPI_STATE_SCHED, &napi->state);
6516 	set_bit(NAPI_STATE_NPSVC, &napi->state);
6517 	list_add_rcu(&napi->dev_list, &dev->napi_list);
6518 	napi_hash_add(napi);
6519 	napi_get_frags_check(napi);
6520 	/* Create kthread for this napi if dev->threaded is set.
6521 	 * Clear dev->threaded if kthread creation failed so that
6522 	 * threaded mode will not be enabled in napi_enable().
6523 	 */
6524 	if (dev->threaded && napi_kthread_create(napi))
6525 		dev->threaded = 0;
6526 	netif_napi_set_irq(napi, -1);
6527 }
6528 EXPORT_SYMBOL(netif_napi_add_weight);
6529 
6530 void napi_disable(struct napi_struct *n)
6531 {
6532 	unsigned long val, new;
6533 
6534 	might_sleep();
6535 	set_bit(NAPI_STATE_DISABLE, &n->state);
6536 
6537 	val = READ_ONCE(n->state);
6538 	do {
6539 		while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
6540 			usleep_range(20, 200);
6541 			val = READ_ONCE(n->state);
6542 		}
6543 
6544 		new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
6545 		new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
6546 	} while (!try_cmpxchg(&n->state, &val, new));
6547 
6548 	hrtimer_cancel(&n->timer);
6549 
6550 	clear_bit(NAPI_STATE_DISABLE, &n->state);
6551 }
6552 EXPORT_SYMBOL(napi_disable);
6553 
6554 /**
6555  *	napi_enable - enable NAPI scheduling
6556  *	@n: NAPI context
6557  *
6558  * Resume NAPI from being scheduled on this context.
6559  * Must be paired with napi_disable.
6560  */
6561 void napi_enable(struct napi_struct *n)
6562 {
6563 	unsigned long new, val = READ_ONCE(n->state);
6564 
6565 	do {
6566 		BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
6567 
6568 		new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
6569 		if (n->dev->threaded && n->thread)
6570 			new |= NAPIF_STATE_THREADED;
6571 	} while (!try_cmpxchg(&n->state, &val, new));
6572 }
6573 EXPORT_SYMBOL(napi_enable);
6574 
6575 static void flush_gro_hash(struct napi_struct *napi)
6576 {
6577 	int i;
6578 
6579 	for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6580 		struct sk_buff *skb, *n;
6581 
6582 		list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6583 			kfree_skb(skb);
6584 		napi->gro_hash[i].count = 0;
6585 	}
6586 }
6587 
6588 /* Must be called in process context */
6589 void __netif_napi_del(struct napi_struct *napi)
6590 {
6591 	if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6592 		return;
6593 
6594 	napi_hash_del(napi);
6595 	list_del_rcu(&napi->dev_list);
6596 	napi_free_frags(napi);
6597 
6598 	flush_gro_hash(napi);
6599 	napi->gro_bitmask = 0;
6600 
6601 	if (napi->thread) {
6602 		kthread_stop(napi->thread);
6603 		napi->thread = NULL;
6604 	}
6605 }
6606 EXPORT_SYMBOL(__netif_napi_del);
6607 
6608 static int __napi_poll(struct napi_struct *n, bool *repoll)
6609 {
6610 	int work, weight;
6611 
6612 	weight = n->weight;
6613 
6614 	/* This NAPI_STATE_SCHED test is for avoiding a race
6615 	 * with netpoll's poll_napi().  Only the entity which
6616 	 * obtains the lock and sees NAPI_STATE_SCHED set will
6617 	 * actually make the ->poll() call.  Therefore we avoid
6618 	 * accidentally calling ->poll() when NAPI is not scheduled.
6619 	 */
6620 	work = 0;
6621 	if (napi_is_scheduled(n)) {
6622 		work = n->poll(n, weight);
6623 		trace_napi_poll(n, work, weight);
6624 
6625 		xdp_do_check_flushed(n);
6626 	}
6627 
6628 	if (unlikely(work > weight))
6629 		netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6630 				n->poll, work, weight);
6631 
6632 	if (likely(work < weight))
6633 		return work;
6634 
6635 	/* Drivers must not modify the NAPI state if they
6636 	 * consume the entire weight.  In such cases this code
6637 	 * still "owns" the NAPI instance and therefore can
6638 	 * move the instance around on the list at-will.
6639 	 */
6640 	if (unlikely(napi_disable_pending(n))) {
6641 		napi_complete(n);
6642 		return work;
6643 	}
6644 
6645 	/* The NAPI context has more processing work, but busy-polling
6646 	 * is preferred. Exit early.
6647 	 */
6648 	if (napi_prefer_busy_poll(n)) {
6649 		if (napi_complete_done(n, work)) {
6650 			/* If timeout is not set, we need to make sure
6651 			 * that the NAPI is re-scheduled.
6652 			 */
6653 			napi_schedule(n);
6654 		}
6655 		return work;
6656 	}
6657 
6658 	if (n->gro_bitmask) {
6659 		/* flush too old packets
6660 		 * If HZ < 1000, flush all packets.
6661 		 */
6662 		napi_gro_flush(n, HZ >= 1000);
6663 	}
6664 
6665 	gro_normal_list(n);
6666 
6667 	/* Some drivers may have called napi_schedule
6668 	 * prior to exhausting their budget.
6669 	 */
6670 	if (unlikely(!list_empty(&n->poll_list))) {
6671 		pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6672 			     n->dev ? n->dev->name : "backlog");
6673 		return work;
6674 	}
6675 
6676 	*repoll = true;
6677 
6678 	return work;
6679 }
6680 
6681 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6682 {
6683 	bool do_repoll = false;
6684 	void *have;
6685 	int work;
6686 
6687 	list_del_init(&n->poll_list);
6688 
6689 	have = netpoll_poll_lock(n);
6690 
6691 	work = __napi_poll(n, &do_repoll);
6692 
6693 	if (do_repoll)
6694 		list_add_tail(&n->poll_list, repoll);
6695 
6696 	netpoll_poll_unlock(have);
6697 
6698 	return work;
6699 }
6700 
6701 static int napi_thread_wait(struct napi_struct *napi)
6702 {
6703 	bool woken = false;
6704 
6705 	set_current_state(TASK_INTERRUPTIBLE);
6706 
6707 	while (!kthread_should_stop()) {
6708 		/* Testing SCHED_THREADED bit here to make sure the current
6709 		 * kthread owns this napi and could poll on this napi.
6710 		 * Testing SCHED bit is not enough because SCHED bit might be
6711 		 * set by some other busy poll thread or by napi_disable().
6712 		 */
6713 		if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state) || woken) {
6714 			WARN_ON(!list_empty(&napi->poll_list));
6715 			__set_current_state(TASK_RUNNING);
6716 			return 0;
6717 		}
6718 
6719 		schedule();
6720 		/* woken being true indicates this thread owns this napi. */
6721 		woken = true;
6722 		set_current_state(TASK_INTERRUPTIBLE);
6723 	}
6724 	__set_current_state(TASK_RUNNING);
6725 
6726 	return -1;
6727 }
6728 
6729 static void skb_defer_free_flush(struct softnet_data *sd)
6730 {
6731 	struct sk_buff *skb, *next;
6732 
6733 	/* Paired with WRITE_ONCE() in skb_attempt_defer_free() */
6734 	if (!READ_ONCE(sd->defer_list))
6735 		return;
6736 
6737 	spin_lock(&sd->defer_lock);
6738 	skb = sd->defer_list;
6739 	sd->defer_list = NULL;
6740 	sd->defer_count = 0;
6741 	spin_unlock(&sd->defer_lock);
6742 
6743 	while (skb != NULL) {
6744 		next = skb->next;
6745 		napi_consume_skb(skb, 1);
6746 		skb = next;
6747 	}
6748 }
6749 
6750 static int napi_threaded_poll(void *data)
6751 {
6752 	struct napi_struct *napi = data;
6753 	struct softnet_data *sd;
6754 	void *have;
6755 
6756 	while (!napi_thread_wait(napi)) {
6757 		for (;;) {
6758 			bool repoll = false;
6759 
6760 			local_bh_disable();
6761 			sd = this_cpu_ptr(&softnet_data);
6762 			sd->in_napi_threaded_poll = true;
6763 
6764 			have = netpoll_poll_lock(napi);
6765 			__napi_poll(napi, &repoll);
6766 			netpoll_poll_unlock(have);
6767 
6768 			sd->in_napi_threaded_poll = false;
6769 			barrier();
6770 
6771 			if (sd_has_rps_ipi_waiting(sd)) {
6772 				local_irq_disable();
6773 				net_rps_action_and_irq_enable(sd);
6774 			}
6775 			skb_defer_free_flush(sd);
6776 			local_bh_enable();
6777 
6778 			if (!repoll)
6779 				break;
6780 
6781 			cond_resched();
6782 		}
6783 	}
6784 	return 0;
6785 }
6786 
6787 static __latent_entropy void net_rx_action(struct softirq_action *h)
6788 {
6789 	struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6790 	unsigned long time_limit = jiffies +
6791 		usecs_to_jiffies(READ_ONCE(netdev_budget_usecs));
6792 	int budget = READ_ONCE(netdev_budget);
6793 	LIST_HEAD(list);
6794 	LIST_HEAD(repoll);
6795 
6796 start:
6797 	sd->in_net_rx_action = true;
6798 	local_irq_disable();
6799 	list_splice_init(&sd->poll_list, &list);
6800 	local_irq_enable();
6801 
6802 	for (;;) {
6803 		struct napi_struct *n;
6804 
6805 		skb_defer_free_flush(sd);
6806 
6807 		if (list_empty(&list)) {
6808 			if (list_empty(&repoll)) {
6809 				sd->in_net_rx_action = false;
6810 				barrier();
6811 				/* We need to check if ____napi_schedule()
6812 				 * had refilled poll_list while
6813 				 * sd->in_net_rx_action was true.
6814 				 */
6815 				if (!list_empty(&sd->poll_list))
6816 					goto start;
6817 				if (!sd_has_rps_ipi_waiting(sd))
6818 					goto end;
6819 			}
6820 			break;
6821 		}
6822 
6823 		n = list_first_entry(&list, struct napi_struct, poll_list);
6824 		budget -= napi_poll(n, &repoll);
6825 
6826 		/* If softirq window is exhausted then punt.
6827 		 * Allow this to run for 2 jiffies since which will allow
6828 		 * an average latency of 1.5/HZ.
6829 		 */
6830 		if (unlikely(budget <= 0 ||
6831 			     time_after_eq(jiffies, time_limit))) {
6832 			sd->time_squeeze++;
6833 			break;
6834 		}
6835 	}
6836 
6837 	local_irq_disable();
6838 
6839 	list_splice_tail_init(&sd->poll_list, &list);
6840 	list_splice_tail(&repoll, &list);
6841 	list_splice(&list, &sd->poll_list);
6842 	if (!list_empty(&sd->poll_list))
6843 		__raise_softirq_irqoff(NET_RX_SOFTIRQ);
6844 	else
6845 		sd->in_net_rx_action = false;
6846 
6847 	net_rps_action_and_irq_enable(sd);
6848 end:;
6849 }
6850 
6851 struct netdev_adjacent {
6852 	struct net_device *dev;
6853 	netdevice_tracker dev_tracker;
6854 
6855 	/* upper master flag, there can only be one master device per list */
6856 	bool master;
6857 
6858 	/* lookup ignore flag */
6859 	bool ignore;
6860 
6861 	/* counter for the number of times this device was added to us */
6862 	u16 ref_nr;
6863 
6864 	/* private field for the users */
6865 	void *private;
6866 
6867 	struct list_head list;
6868 	struct rcu_head rcu;
6869 };
6870 
6871 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6872 						 struct list_head *adj_list)
6873 {
6874 	struct netdev_adjacent *adj;
6875 
6876 	list_for_each_entry(adj, adj_list, list) {
6877 		if (adj->dev == adj_dev)
6878 			return adj;
6879 	}
6880 	return NULL;
6881 }
6882 
6883 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6884 				    struct netdev_nested_priv *priv)
6885 {
6886 	struct net_device *dev = (struct net_device *)priv->data;
6887 
6888 	return upper_dev == dev;
6889 }
6890 
6891 /**
6892  * netdev_has_upper_dev - Check if device is linked to an upper device
6893  * @dev: device
6894  * @upper_dev: upper device to check
6895  *
6896  * Find out if a device is linked to specified upper device and return true
6897  * in case it is. Note that this checks only immediate upper device,
6898  * not through a complete stack of devices. The caller must hold the RTNL lock.
6899  */
6900 bool netdev_has_upper_dev(struct net_device *dev,
6901 			  struct net_device *upper_dev)
6902 {
6903 	struct netdev_nested_priv priv = {
6904 		.data = (void *)upper_dev,
6905 	};
6906 
6907 	ASSERT_RTNL();
6908 
6909 	return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6910 					     &priv);
6911 }
6912 EXPORT_SYMBOL(netdev_has_upper_dev);
6913 
6914 /**
6915  * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
6916  * @dev: device
6917  * @upper_dev: upper device to check
6918  *
6919  * Find out if a device is linked to specified upper device and return true
6920  * in case it is. Note that this checks the entire upper device chain.
6921  * The caller must hold rcu lock.
6922  */
6923 
6924 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6925 				  struct net_device *upper_dev)
6926 {
6927 	struct netdev_nested_priv priv = {
6928 		.data = (void *)upper_dev,
6929 	};
6930 
6931 	return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6932 					       &priv);
6933 }
6934 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6935 
6936 /**
6937  * netdev_has_any_upper_dev - Check if device is linked to some device
6938  * @dev: device
6939  *
6940  * Find out if a device is linked to an upper device and return true in case
6941  * it is. The caller must hold the RTNL lock.
6942  */
6943 bool netdev_has_any_upper_dev(struct net_device *dev)
6944 {
6945 	ASSERT_RTNL();
6946 
6947 	return !list_empty(&dev->adj_list.upper);
6948 }
6949 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6950 
6951 /**
6952  * netdev_master_upper_dev_get - Get master upper device
6953  * @dev: device
6954  *
6955  * Find a master upper device and return pointer to it or NULL in case
6956  * it's not there. The caller must hold the RTNL lock.
6957  */
6958 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6959 {
6960 	struct netdev_adjacent *upper;
6961 
6962 	ASSERT_RTNL();
6963 
6964 	if (list_empty(&dev->adj_list.upper))
6965 		return NULL;
6966 
6967 	upper = list_first_entry(&dev->adj_list.upper,
6968 				 struct netdev_adjacent, list);
6969 	if (likely(upper->master))
6970 		return upper->dev;
6971 	return NULL;
6972 }
6973 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6974 
6975 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
6976 {
6977 	struct netdev_adjacent *upper;
6978 
6979 	ASSERT_RTNL();
6980 
6981 	if (list_empty(&dev->adj_list.upper))
6982 		return NULL;
6983 
6984 	upper = list_first_entry(&dev->adj_list.upper,
6985 				 struct netdev_adjacent, list);
6986 	if (likely(upper->master) && !upper->ignore)
6987 		return upper->dev;
6988 	return NULL;
6989 }
6990 
6991 /**
6992  * netdev_has_any_lower_dev - Check if device is linked to some device
6993  * @dev: device
6994  *
6995  * Find out if a device is linked to a lower device and return true in case
6996  * it is. The caller must hold the RTNL lock.
6997  */
6998 static bool netdev_has_any_lower_dev(struct net_device *dev)
6999 {
7000 	ASSERT_RTNL();
7001 
7002 	return !list_empty(&dev->adj_list.lower);
7003 }
7004 
7005 void *netdev_adjacent_get_private(struct list_head *adj_list)
7006 {
7007 	struct netdev_adjacent *adj;
7008 
7009 	adj = list_entry(adj_list, struct netdev_adjacent, list);
7010 
7011 	return adj->private;
7012 }
7013 EXPORT_SYMBOL(netdev_adjacent_get_private);
7014 
7015 /**
7016  * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
7017  * @dev: device
7018  * @iter: list_head ** of the current position
7019  *
7020  * Gets the next device from the dev's upper list, starting from iter
7021  * position. The caller must hold RCU read lock.
7022  */
7023 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
7024 						 struct list_head **iter)
7025 {
7026 	struct netdev_adjacent *upper;
7027 
7028 	WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7029 
7030 	upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7031 
7032 	if (&upper->list == &dev->adj_list.upper)
7033 		return NULL;
7034 
7035 	*iter = &upper->list;
7036 
7037 	return upper->dev;
7038 }
7039 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
7040 
7041 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
7042 						  struct list_head **iter,
7043 						  bool *ignore)
7044 {
7045 	struct netdev_adjacent *upper;
7046 
7047 	upper = list_entry((*iter)->next, struct netdev_adjacent, list);
7048 
7049 	if (&upper->list == &dev->adj_list.upper)
7050 		return NULL;
7051 
7052 	*iter = &upper->list;
7053 	*ignore = upper->ignore;
7054 
7055 	return upper->dev;
7056 }
7057 
7058 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
7059 						    struct list_head **iter)
7060 {
7061 	struct netdev_adjacent *upper;
7062 
7063 	WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7064 
7065 	upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7066 
7067 	if (&upper->list == &dev->adj_list.upper)
7068 		return NULL;
7069 
7070 	*iter = &upper->list;
7071 
7072 	return upper->dev;
7073 }
7074 
7075 static int __netdev_walk_all_upper_dev(struct net_device *dev,
7076 				       int (*fn)(struct net_device *dev,
7077 					 struct netdev_nested_priv *priv),
7078 				       struct netdev_nested_priv *priv)
7079 {
7080 	struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7081 	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7082 	int ret, cur = 0;
7083 	bool ignore;
7084 
7085 	now = dev;
7086 	iter = &dev->adj_list.upper;
7087 
7088 	while (1) {
7089 		if (now != dev) {
7090 			ret = fn(now, priv);
7091 			if (ret)
7092 				return ret;
7093 		}
7094 
7095 		next = NULL;
7096 		while (1) {
7097 			udev = __netdev_next_upper_dev(now, &iter, &ignore);
7098 			if (!udev)
7099 				break;
7100 			if (ignore)
7101 				continue;
7102 
7103 			next = udev;
7104 			niter = &udev->adj_list.upper;
7105 			dev_stack[cur] = now;
7106 			iter_stack[cur++] = iter;
7107 			break;
7108 		}
7109 
7110 		if (!next) {
7111 			if (!cur)
7112 				return 0;
7113 			next = dev_stack[--cur];
7114 			niter = iter_stack[cur];
7115 		}
7116 
7117 		now = next;
7118 		iter = niter;
7119 	}
7120 
7121 	return 0;
7122 }
7123 
7124 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
7125 				  int (*fn)(struct net_device *dev,
7126 					    struct netdev_nested_priv *priv),
7127 				  struct netdev_nested_priv *priv)
7128 {
7129 	struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7130 	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7131 	int ret, cur = 0;
7132 
7133 	now = dev;
7134 	iter = &dev->adj_list.upper;
7135 
7136 	while (1) {
7137 		if (now != dev) {
7138 			ret = fn(now, priv);
7139 			if (ret)
7140 				return ret;
7141 		}
7142 
7143 		next = NULL;
7144 		while (1) {
7145 			udev = netdev_next_upper_dev_rcu(now, &iter);
7146 			if (!udev)
7147 				break;
7148 
7149 			next = udev;
7150 			niter = &udev->adj_list.upper;
7151 			dev_stack[cur] = now;
7152 			iter_stack[cur++] = iter;
7153 			break;
7154 		}
7155 
7156 		if (!next) {
7157 			if (!cur)
7158 				return 0;
7159 			next = dev_stack[--cur];
7160 			niter = iter_stack[cur];
7161 		}
7162 
7163 		now = next;
7164 		iter = niter;
7165 	}
7166 
7167 	return 0;
7168 }
7169 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7170 
7171 static bool __netdev_has_upper_dev(struct net_device *dev,
7172 				   struct net_device *upper_dev)
7173 {
7174 	struct netdev_nested_priv priv = {
7175 		.flags = 0,
7176 		.data = (void *)upper_dev,
7177 	};
7178 
7179 	ASSERT_RTNL();
7180 
7181 	return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7182 					   &priv);
7183 }
7184 
7185 /**
7186  * netdev_lower_get_next_private - Get the next ->private from the
7187  *				   lower neighbour list
7188  * @dev: device
7189  * @iter: list_head ** of the current position
7190  *
7191  * Gets the next netdev_adjacent->private from the dev's lower neighbour
7192  * list, starting from iter position. The caller must hold either hold the
7193  * RTNL lock or its own locking that guarantees that the neighbour lower
7194  * list will remain unchanged.
7195  */
7196 void *netdev_lower_get_next_private(struct net_device *dev,
7197 				    struct list_head **iter)
7198 {
7199 	struct netdev_adjacent *lower;
7200 
7201 	lower = list_entry(*iter, struct netdev_adjacent, list);
7202 
7203 	if (&lower->list == &dev->adj_list.lower)
7204 		return NULL;
7205 
7206 	*iter = lower->list.next;
7207 
7208 	return lower->private;
7209 }
7210 EXPORT_SYMBOL(netdev_lower_get_next_private);
7211 
7212 /**
7213  * netdev_lower_get_next_private_rcu - Get the next ->private from the
7214  *				       lower neighbour list, RCU
7215  *				       variant
7216  * @dev: device
7217  * @iter: list_head ** of the current position
7218  *
7219  * Gets the next netdev_adjacent->private from the dev's lower neighbour
7220  * list, starting from iter position. The caller must hold RCU read lock.
7221  */
7222 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
7223 					struct list_head **iter)
7224 {
7225 	struct netdev_adjacent *lower;
7226 
7227 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
7228 
7229 	lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7230 
7231 	if (&lower->list == &dev->adj_list.lower)
7232 		return NULL;
7233 
7234 	*iter = &lower->list;
7235 
7236 	return lower->private;
7237 }
7238 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7239 
7240 /**
7241  * netdev_lower_get_next - Get the next device from the lower neighbour
7242  *                         list
7243  * @dev: device
7244  * @iter: list_head ** of the current position
7245  *
7246  * Gets the next netdev_adjacent from the dev's lower neighbour
7247  * list, starting from iter position. The caller must hold RTNL lock or
7248  * its own locking that guarantees that the neighbour lower
7249  * list will remain unchanged.
7250  */
7251 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7252 {
7253 	struct netdev_adjacent *lower;
7254 
7255 	lower = list_entry(*iter, struct netdev_adjacent, list);
7256 
7257 	if (&lower->list == &dev->adj_list.lower)
7258 		return NULL;
7259 
7260 	*iter = lower->list.next;
7261 
7262 	return lower->dev;
7263 }
7264 EXPORT_SYMBOL(netdev_lower_get_next);
7265 
7266 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7267 						struct list_head **iter)
7268 {
7269 	struct netdev_adjacent *lower;
7270 
7271 	lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7272 
7273 	if (&lower->list == &dev->adj_list.lower)
7274 		return NULL;
7275 
7276 	*iter = &lower->list;
7277 
7278 	return lower->dev;
7279 }
7280 
7281 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7282 						  struct list_head **iter,
7283 						  bool *ignore)
7284 {
7285 	struct netdev_adjacent *lower;
7286 
7287 	lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7288 
7289 	if (&lower->list == &dev->adj_list.lower)
7290 		return NULL;
7291 
7292 	*iter = &lower->list;
7293 	*ignore = lower->ignore;
7294 
7295 	return lower->dev;
7296 }
7297 
7298 int netdev_walk_all_lower_dev(struct net_device *dev,
7299 			      int (*fn)(struct net_device *dev,
7300 					struct netdev_nested_priv *priv),
7301 			      struct netdev_nested_priv *priv)
7302 {
7303 	struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7304 	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7305 	int ret, cur = 0;
7306 
7307 	now = dev;
7308 	iter = &dev->adj_list.lower;
7309 
7310 	while (1) {
7311 		if (now != dev) {
7312 			ret = fn(now, priv);
7313 			if (ret)
7314 				return ret;
7315 		}
7316 
7317 		next = NULL;
7318 		while (1) {
7319 			ldev = netdev_next_lower_dev(now, &iter);
7320 			if (!ldev)
7321 				break;
7322 
7323 			next = ldev;
7324 			niter = &ldev->adj_list.lower;
7325 			dev_stack[cur] = now;
7326 			iter_stack[cur++] = iter;
7327 			break;
7328 		}
7329 
7330 		if (!next) {
7331 			if (!cur)
7332 				return 0;
7333 			next = dev_stack[--cur];
7334 			niter = iter_stack[cur];
7335 		}
7336 
7337 		now = next;
7338 		iter = niter;
7339 	}
7340 
7341 	return 0;
7342 }
7343 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7344 
7345 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7346 				       int (*fn)(struct net_device *dev,
7347 					 struct netdev_nested_priv *priv),
7348 				       struct netdev_nested_priv *priv)
7349 {
7350 	struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7351 	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7352 	int ret, cur = 0;
7353 	bool ignore;
7354 
7355 	now = dev;
7356 	iter = &dev->adj_list.lower;
7357 
7358 	while (1) {
7359 		if (now != dev) {
7360 			ret = fn(now, priv);
7361 			if (ret)
7362 				return ret;
7363 		}
7364 
7365 		next = NULL;
7366 		while (1) {
7367 			ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7368 			if (!ldev)
7369 				break;
7370 			if (ignore)
7371 				continue;
7372 
7373 			next = ldev;
7374 			niter = &ldev->adj_list.lower;
7375 			dev_stack[cur] = now;
7376 			iter_stack[cur++] = iter;
7377 			break;
7378 		}
7379 
7380 		if (!next) {
7381 			if (!cur)
7382 				return 0;
7383 			next = dev_stack[--cur];
7384 			niter = iter_stack[cur];
7385 		}
7386 
7387 		now = next;
7388 		iter = niter;
7389 	}
7390 
7391 	return 0;
7392 }
7393 
7394 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7395 					     struct list_head **iter)
7396 {
7397 	struct netdev_adjacent *lower;
7398 
7399 	lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7400 	if (&lower->list == &dev->adj_list.lower)
7401 		return NULL;
7402 
7403 	*iter = &lower->list;
7404 
7405 	return lower->dev;
7406 }
7407 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7408 
7409 static u8 __netdev_upper_depth(struct net_device *dev)
7410 {
7411 	struct net_device *udev;
7412 	struct list_head *iter;
7413 	u8 max_depth = 0;
7414 	bool ignore;
7415 
7416 	for (iter = &dev->adj_list.upper,
7417 	     udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7418 	     udev;
7419 	     udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7420 		if (ignore)
7421 			continue;
7422 		if (max_depth < udev->upper_level)
7423 			max_depth = udev->upper_level;
7424 	}
7425 
7426 	return max_depth;
7427 }
7428 
7429 static u8 __netdev_lower_depth(struct net_device *dev)
7430 {
7431 	struct net_device *ldev;
7432 	struct list_head *iter;
7433 	u8 max_depth = 0;
7434 	bool ignore;
7435 
7436 	for (iter = &dev->adj_list.lower,
7437 	     ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7438 	     ldev;
7439 	     ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7440 		if (ignore)
7441 			continue;
7442 		if (max_depth < ldev->lower_level)
7443 			max_depth = ldev->lower_level;
7444 	}
7445 
7446 	return max_depth;
7447 }
7448 
7449 static int __netdev_update_upper_level(struct net_device *dev,
7450 				       struct netdev_nested_priv *__unused)
7451 {
7452 	dev->upper_level = __netdev_upper_depth(dev) + 1;
7453 	return 0;
7454 }
7455 
7456 #ifdef CONFIG_LOCKDEP
7457 static LIST_HEAD(net_unlink_list);
7458 
7459 static void net_unlink_todo(struct net_device *dev)
7460 {
7461 	if (list_empty(&dev->unlink_list))
7462 		list_add_tail(&dev->unlink_list, &net_unlink_list);
7463 }
7464 #endif
7465 
7466 static int __netdev_update_lower_level(struct net_device *dev,
7467 				       struct netdev_nested_priv *priv)
7468 {
7469 	dev->lower_level = __netdev_lower_depth(dev) + 1;
7470 
7471 #ifdef CONFIG_LOCKDEP
7472 	if (!priv)
7473 		return 0;
7474 
7475 	if (priv->flags & NESTED_SYNC_IMM)
7476 		dev->nested_level = dev->lower_level - 1;
7477 	if (priv->flags & NESTED_SYNC_TODO)
7478 		net_unlink_todo(dev);
7479 #endif
7480 	return 0;
7481 }
7482 
7483 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7484 				  int (*fn)(struct net_device *dev,
7485 					    struct netdev_nested_priv *priv),
7486 				  struct netdev_nested_priv *priv)
7487 {
7488 	struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7489 	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7490 	int ret, cur = 0;
7491 
7492 	now = dev;
7493 	iter = &dev->adj_list.lower;
7494 
7495 	while (1) {
7496 		if (now != dev) {
7497 			ret = fn(now, priv);
7498 			if (ret)
7499 				return ret;
7500 		}
7501 
7502 		next = NULL;
7503 		while (1) {
7504 			ldev = netdev_next_lower_dev_rcu(now, &iter);
7505 			if (!ldev)
7506 				break;
7507 
7508 			next = ldev;
7509 			niter = &ldev->adj_list.lower;
7510 			dev_stack[cur] = now;
7511 			iter_stack[cur++] = iter;
7512 			break;
7513 		}
7514 
7515 		if (!next) {
7516 			if (!cur)
7517 				return 0;
7518 			next = dev_stack[--cur];
7519 			niter = iter_stack[cur];
7520 		}
7521 
7522 		now = next;
7523 		iter = niter;
7524 	}
7525 
7526 	return 0;
7527 }
7528 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7529 
7530 /**
7531  * netdev_lower_get_first_private_rcu - Get the first ->private from the
7532  *				       lower neighbour list, RCU
7533  *				       variant
7534  * @dev: device
7535  *
7536  * Gets the first netdev_adjacent->private from the dev's lower neighbour
7537  * list. The caller must hold RCU read lock.
7538  */
7539 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7540 {
7541 	struct netdev_adjacent *lower;
7542 
7543 	lower = list_first_or_null_rcu(&dev->adj_list.lower,
7544 			struct netdev_adjacent, list);
7545 	if (lower)
7546 		return lower->private;
7547 	return NULL;
7548 }
7549 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7550 
7551 /**
7552  * netdev_master_upper_dev_get_rcu - Get master upper device
7553  * @dev: device
7554  *
7555  * Find a master upper device and return pointer to it or NULL in case
7556  * it's not there. The caller must hold the RCU read lock.
7557  */
7558 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7559 {
7560 	struct netdev_adjacent *upper;
7561 
7562 	upper = list_first_or_null_rcu(&dev->adj_list.upper,
7563 				       struct netdev_adjacent, list);
7564 	if (upper && likely(upper->master))
7565 		return upper->dev;
7566 	return NULL;
7567 }
7568 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7569 
7570 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7571 			      struct net_device *adj_dev,
7572 			      struct list_head *dev_list)
7573 {
7574 	char linkname[IFNAMSIZ+7];
7575 
7576 	sprintf(linkname, dev_list == &dev->adj_list.upper ?
7577 		"upper_%s" : "lower_%s", adj_dev->name);
7578 	return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7579 				 linkname);
7580 }
7581 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7582 			       char *name,
7583 			       struct list_head *dev_list)
7584 {
7585 	char linkname[IFNAMSIZ+7];
7586 
7587 	sprintf(linkname, dev_list == &dev->adj_list.upper ?
7588 		"upper_%s" : "lower_%s", name);
7589 	sysfs_remove_link(&(dev->dev.kobj), linkname);
7590 }
7591 
7592 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7593 						 struct net_device *adj_dev,
7594 						 struct list_head *dev_list)
7595 {
7596 	return (dev_list == &dev->adj_list.upper ||
7597 		dev_list == &dev->adj_list.lower) &&
7598 		net_eq(dev_net(dev), dev_net(adj_dev));
7599 }
7600 
7601 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7602 					struct net_device *adj_dev,
7603 					struct list_head *dev_list,
7604 					void *private, bool master)
7605 {
7606 	struct netdev_adjacent *adj;
7607 	int ret;
7608 
7609 	adj = __netdev_find_adj(adj_dev, dev_list);
7610 
7611 	if (adj) {
7612 		adj->ref_nr += 1;
7613 		pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7614 			 dev->name, adj_dev->name, adj->ref_nr);
7615 
7616 		return 0;
7617 	}
7618 
7619 	adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7620 	if (!adj)
7621 		return -ENOMEM;
7622 
7623 	adj->dev = adj_dev;
7624 	adj->master = master;
7625 	adj->ref_nr = 1;
7626 	adj->private = private;
7627 	adj->ignore = false;
7628 	netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL);
7629 
7630 	pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7631 		 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7632 
7633 	if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7634 		ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7635 		if (ret)
7636 			goto free_adj;
7637 	}
7638 
7639 	/* Ensure that master link is always the first item in list. */
7640 	if (master) {
7641 		ret = sysfs_create_link(&(dev->dev.kobj),
7642 					&(adj_dev->dev.kobj), "master");
7643 		if (ret)
7644 			goto remove_symlinks;
7645 
7646 		list_add_rcu(&adj->list, dev_list);
7647 	} else {
7648 		list_add_tail_rcu(&adj->list, dev_list);
7649 	}
7650 
7651 	return 0;
7652 
7653 remove_symlinks:
7654 	if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7655 		netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7656 free_adj:
7657 	netdev_put(adj_dev, &adj->dev_tracker);
7658 	kfree(adj);
7659 
7660 	return ret;
7661 }
7662 
7663 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7664 					 struct net_device *adj_dev,
7665 					 u16 ref_nr,
7666 					 struct list_head *dev_list)
7667 {
7668 	struct netdev_adjacent *adj;
7669 
7670 	pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7671 		 dev->name, adj_dev->name, ref_nr);
7672 
7673 	adj = __netdev_find_adj(adj_dev, dev_list);
7674 
7675 	if (!adj) {
7676 		pr_err("Adjacency does not exist for device %s from %s\n",
7677 		       dev->name, adj_dev->name);
7678 		WARN_ON(1);
7679 		return;
7680 	}
7681 
7682 	if (adj->ref_nr > ref_nr) {
7683 		pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7684 			 dev->name, adj_dev->name, ref_nr,
7685 			 adj->ref_nr - ref_nr);
7686 		adj->ref_nr -= ref_nr;
7687 		return;
7688 	}
7689 
7690 	if (adj->master)
7691 		sysfs_remove_link(&(dev->dev.kobj), "master");
7692 
7693 	if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7694 		netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7695 
7696 	list_del_rcu(&adj->list);
7697 	pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7698 		 adj_dev->name, dev->name, adj_dev->name);
7699 	netdev_put(adj_dev, &adj->dev_tracker);
7700 	kfree_rcu(adj, rcu);
7701 }
7702 
7703 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7704 					    struct net_device *upper_dev,
7705 					    struct list_head *up_list,
7706 					    struct list_head *down_list,
7707 					    void *private, bool master)
7708 {
7709 	int ret;
7710 
7711 	ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7712 					   private, master);
7713 	if (ret)
7714 		return ret;
7715 
7716 	ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7717 					   private, false);
7718 	if (ret) {
7719 		__netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7720 		return ret;
7721 	}
7722 
7723 	return 0;
7724 }
7725 
7726 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7727 					       struct net_device *upper_dev,
7728 					       u16 ref_nr,
7729 					       struct list_head *up_list,
7730 					       struct list_head *down_list)
7731 {
7732 	__netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7733 	__netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7734 }
7735 
7736 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7737 						struct net_device *upper_dev,
7738 						void *private, bool master)
7739 {
7740 	return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7741 						&dev->adj_list.upper,
7742 						&upper_dev->adj_list.lower,
7743 						private, master);
7744 }
7745 
7746 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7747 						   struct net_device *upper_dev)
7748 {
7749 	__netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7750 					   &dev->adj_list.upper,
7751 					   &upper_dev->adj_list.lower);
7752 }
7753 
7754 static int __netdev_upper_dev_link(struct net_device *dev,
7755 				   struct net_device *upper_dev, bool master,
7756 				   void *upper_priv, void *upper_info,
7757 				   struct netdev_nested_priv *priv,
7758 				   struct netlink_ext_ack *extack)
7759 {
7760 	struct netdev_notifier_changeupper_info changeupper_info = {
7761 		.info = {
7762 			.dev = dev,
7763 			.extack = extack,
7764 		},
7765 		.upper_dev = upper_dev,
7766 		.master = master,
7767 		.linking = true,
7768 		.upper_info = upper_info,
7769 	};
7770 	struct net_device *master_dev;
7771 	int ret = 0;
7772 
7773 	ASSERT_RTNL();
7774 
7775 	if (dev == upper_dev)
7776 		return -EBUSY;
7777 
7778 	/* To prevent loops, check if dev is not upper device to upper_dev. */
7779 	if (__netdev_has_upper_dev(upper_dev, dev))
7780 		return -EBUSY;
7781 
7782 	if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7783 		return -EMLINK;
7784 
7785 	if (!master) {
7786 		if (__netdev_has_upper_dev(dev, upper_dev))
7787 			return -EEXIST;
7788 	} else {
7789 		master_dev = __netdev_master_upper_dev_get(dev);
7790 		if (master_dev)
7791 			return master_dev == upper_dev ? -EEXIST : -EBUSY;
7792 	}
7793 
7794 	ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7795 					    &changeupper_info.info);
7796 	ret = notifier_to_errno(ret);
7797 	if (ret)
7798 		return ret;
7799 
7800 	ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7801 						   master);
7802 	if (ret)
7803 		return ret;
7804 
7805 	ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7806 					    &changeupper_info.info);
7807 	ret = notifier_to_errno(ret);
7808 	if (ret)
7809 		goto rollback;
7810 
7811 	__netdev_update_upper_level(dev, NULL);
7812 	__netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7813 
7814 	__netdev_update_lower_level(upper_dev, priv);
7815 	__netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7816 				    priv);
7817 
7818 	return 0;
7819 
7820 rollback:
7821 	__netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7822 
7823 	return ret;
7824 }
7825 
7826 /**
7827  * netdev_upper_dev_link - Add a link to the upper device
7828  * @dev: device
7829  * @upper_dev: new upper device
7830  * @extack: netlink extended ack
7831  *
7832  * Adds a link to device which is upper to this one. The caller must hold
7833  * the RTNL lock. On a failure a negative errno code is returned.
7834  * On success the reference counts are adjusted and the function
7835  * returns zero.
7836  */
7837 int netdev_upper_dev_link(struct net_device *dev,
7838 			  struct net_device *upper_dev,
7839 			  struct netlink_ext_ack *extack)
7840 {
7841 	struct netdev_nested_priv priv = {
7842 		.flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7843 		.data = NULL,
7844 	};
7845 
7846 	return __netdev_upper_dev_link(dev, upper_dev, false,
7847 				       NULL, NULL, &priv, extack);
7848 }
7849 EXPORT_SYMBOL(netdev_upper_dev_link);
7850 
7851 /**
7852  * netdev_master_upper_dev_link - Add a master link to the upper device
7853  * @dev: device
7854  * @upper_dev: new upper device
7855  * @upper_priv: upper device private
7856  * @upper_info: upper info to be passed down via notifier
7857  * @extack: netlink extended ack
7858  *
7859  * Adds a link to device which is upper to this one. In this case, only
7860  * one master upper device can be linked, although other non-master devices
7861  * might be linked as well. The caller must hold the RTNL lock.
7862  * On a failure a negative errno code is returned. On success the reference
7863  * counts are adjusted and the function returns zero.
7864  */
7865 int netdev_master_upper_dev_link(struct net_device *dev,
7866 				 struct net_device *upper_dev,
7867 				 void *upper_priv, void *upper_info,
7868 				 struct netlink_ext_ack *extack)
7869 {
7870 	struct netdev_nested_priv priv = {
7871 		.flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7872 		.data = NULL,
7873 	};
7874 
7875 	return __netdev_upper_dev_link(dev, upper_dev, true,
7876 				       upper_priv, upper_info, &priv, extack);
7877 }
7878 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7879 
7880 static void __netdev_upper_dev_unlink(struct net_device *dev,
7881 				      struct net_device *upper_dev,
7882 				      struct netdev_nested_priv *priv)
7883 {
7884 	struct netdev_notifier_changeupper_info changeupper_info = {
7885 		.info = {
7886 			.dev = dev,
7887 		},
7888 		.upper_dev = upper_dev,
7889 		.linking = false,
7890 	};
7891 
7892 	ASSERT_RTNL();
7893 
7894 	changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7895 
7896 	call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7897 				      &changeupper_info.info);
7898 
7899 	__netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7900 
7901 	call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7902 				      &changeupper_info.info);
7903 
7904 	__netdev_update_upper_level(dev, NULL);
7905 	__netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7906 
7907 	__netdev_update_lower_level(upper_dev, priv);
7908 	__netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7909 				    priv);
7910 }
7911 
7912 /**
7913  * netdev_upper_dev_unlink - Removes a link to upper device
7914  * @dev: device
7915  * @upper_dev: new upper device
7916  *
7917  * Removes a link to device which is upper to this one. The caller must hold
7918  * the RTNL lock.
7919  */
7920 void netdev_upper_dev_unlink(struct net_device *dev,
7921 			     struct net_device *upper_dev)
7922 {
7923 	struct netdev_nested_priv priv = {
7924 		.flags = NESTED_SYNC_TODO,
7925 		.data = NULL,
7926 	};
7927 
7928 	__netdev_upper_dev_unlink(dev, upper_dev, &priv);
7929 }
7930 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7931 
7932 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7933 				      struct net_device *lower_dev,
7934 				      bool val)
7935 {
7936 	struct netdev_adjacent *adj;
7937 
7938 	adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
7939 	if (adj)
7940 		adj->ignore = val;
7941 
7942 	adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
7943 	if (adj)
7944 		adj->ignore = val;
7945 }
7946 
7947 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
7948 					struct net_device *lower_dev)
7949 {
7950 	__netdev_adjacent_dev_set(upper_dev, lower_dev, true);
7951 }
7952 
7953 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
7954 				       struct net_device *lower_dev)
7955 {
7956 	__netdev_adjacent_dev_set(upper_dev, lower_dev, false);
7957 }
7958 
7959 int netdev_adjacent_change_prepare(struct net_device *old_dev,
7960 				   struct net_device *new_dev,
7961 				   struct net_device *dev,
7962 				   struct netlink_ext_ack *extack)
7963 {
7964 	struct netdev_nested_priv priv = {
7965 		.flags = 0,
7966 		.data = NULL,
7967 	};
7968 	int err;
7969 
7970 	if (!new_dev)
7971 		return 0;
7972 
7973 	if (old_dev && new_dev != old_dev)
7974 		netdev_adjacent_dev_disable(dev, old_dev);
7975 	err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
7976 				      extack);
7977 	if (err) {
7978 		if (old_dev && new_dev != old_dev)
7979 			netdev_adjacent_dev_enable(dev, old_dev);
7980 		return err;
7981 	}
7982 
7983 	return 0;
7984 }
7985 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
7986 
7987 void netdev_adjacent_change_commit(struct net_device *old_dev,
7988 				   struct net_device *new_dev,
7989 				   struct net_device *dev)
7990 {
7991 	struct netdev_nested_priv priv = {
7992 		.flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7993 		.data = NULL,
7994 	};
7995 
7996 	if (!new_dev || !old_dev)
7997 		return;
7998 
7999 	if (new_dev == old_dev)
8000 		return;
8001 
8002 	netdev_adjacent_dev_enable(dev, old_dev);
8003 	__netdev_upper_dev_unlink(old_dev, dev, &priv);
8004 }
8005 EXPORT_SYMBOL(netdev_adjacent_change_commit);
8006 
8007 void netdev_adjacent_change_abort(struct net_device *old_dev,
8008 				  struct net_device *new_dev,
8009 				  struct net_device *dev)
8010 {
8011 	struct netdev_nested_priv priv = {
8012 		.flags = 0,
8013 		.data = NULL,
8014 	};
8015 
8016 	if (!new_dev)
8017 		return;
8018 
8019 	if (old_dev && new_dev != old_dev)
8020 		netdev_adjacent_dev_enable(dev, old_dev);
8021 
8022 	__netdev_upper_dev_unlink(new_dev, dev, &priv);
8023 }
8024 EXPORT_SYMBOL(netdev_adjacent_change_abort);
8025 
8026 /**
8027  * netdev_bonding_info_change - Dispatch event about slave change
8028  * @dev: device
8029  * @bonding_info: info to dispatch
8030  *
8031  * Send NETDEV_BONDING_INFO to netdev notifiers with info.
8032  * The caller must hold the RTNL lock.
8033  */
8034 void netdev_bonding_info_change(struct net_device *dev,
8035 				struct netdev_bonding_info *bonding_info)
8036 {
8037 	struct netdev_notifier_bonding_info info = {
8038 		.info.dev = dev,
8039 	};
8040 
8041 	memcpy(&info.bonding_info, bonding_info,
8042 	       sizeof(struct netdev_bonding_info));
8043 	call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
8044 				      &info.info);
8045 }
8046 EXPORT_SYMBOL(netdev_bonding_info_change);
8047 
8048 static int netdev_offload_xstats_enable_l3(struct net_device *dev,
8049 					   struct netlink_ext_ack *extack)
8050 {
8051 	struct netdev_notifier_offload_xstats_info info = {
8052 		.info.dev = dev,
8053 		.info.extack = extack,
8054 		.type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
8055 	};
8056 	int err;
8057 	int rc;
8058 
8059 	dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
8060 					 GFP_KERNEL);
8061 	if (!dev->offload_xstats_l3)
8062 		return -ENOMEM;
8063 
8064 	rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
8065 						  NETDEV_OFFLOAD_XSTATS_DISABLE,
8066 						  &info.info);
8067 	err = notifier_to_errno(rc);
8068 	if (err)
8069 		goto free_stats;
8070 
8071 	return 0;
8072 
8073 free_stats:
8074 	kfree(dev->offload_xstats_l3);
8075 	dev->offload_xstats_l3 = NULL;
8076 	return err;
8077 }
8078 
8079 int netdev_offload_xstats_enable(struct net_device *dev,
8080 				 enum netdev_offload_xstats_type type,
8081 				 struct netlink_ext_ack *extack)
8082 {
8083 	ASSERT_RTNL();
8084 
8085 	if (netdev_offload_xstats_enabled(dev, type))
8086 		return -EALREADY;
8087 
8088 	switch (type) {
8089 	case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8090 		return netdev_offload_xstats_enable_l3(dev, extack);
8091 	}
8092 
8093 	WARN_ON(1);
8094 	return -EINVAL;
8095 }
8096 EXPORT_SYMBOL(netdev_offload_xstats_enable);
8097 
8098 static void netdev_offload_xstats_disable_l3(struct net_device *dev)
8099 {
8100 	struct netdev_notifier_offload_xstats_info info = {
8101 		.info.dev = dev,
8102 		.type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
8103 	};
8104 
8105 	call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
8106 				      &info.info);
8107 	kfree(dev->offload_xstats_l3);
8108 	dev->offload_xstats_l3 = NULL;
8109 }
8110 
8111 int netdev_offload_xstats_disable(struct net_device *dev,
8112 				  enum netdev_offload_xstats_type type)
8113 {
8114 	ASSERT_RTNL();
8115 
8116 	if (!netdev_offload_xstats_enabled(dev, type))
8117 		return -EALREADY;
8118 
8119 	switch (type) {
8120 	case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8121 		netdev_offload_xstats_disable_l3(dev);
8122 		return 0;
8123 	}
8124 
8125 	WARN_ON(1);
8126 	return -EINVAL;
8127 }
8128 EXPORT_SYMBOL(netdev_offload_xstats_disable);
8129 
8130 static void netdev_offload_xstats_disable_all(struct net_device *dev)
8131 {
8132 	netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
8133 }
8134 
8135 static struct rtnl_hw_stats64 *
8136 netdev_offload_xstats_get_ptr(const struct net_device *dev,
8137 			      enum netdev_offload_xstats_type type)
8138 {
8139 	switch (type) {
8140 	case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8141 		return dev->offload_xstats_l3;
8142 	}
8143 
8144 	WARN_ON(1);
8145 	return NULL;
8146 }
8147 
8148 bool netdev_offload_xstats_enabled(const struct net_device *dev,
8149 				   enum netdev_offload_xstats_type type)
8150 {
8151 	ASSERT_RTNL();
8152 
8153 	return netdev_offload_xstats_get_ptr(dev, type);
8154 }
8155 EXPORT_SYMBOL(netdev_offload_xstats_enabled);
8156 
8157 struct netdev_notifier_offload_xstats_ru {
8158 	bool used;
8159 };
8160 
8161 struct netdev_notifier_offload_xstats_rd {
8162 	struct rtnl_hw_stats64 stats;
8163 	bool used;
8164 };
8165 
8166 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
8167 				  const struct rtnl_hw_stats64 *src)
8168 {
8169 	dest->rx_packets	  += src->rx_packets;
8170 	dest->tx_packets	  += src->tx_packets;
8171 	dest->rx_bytes		  += src->rx_bytes;
8172 	dest->tx_bytes		  += src->tx_bytes;
8173 	dest->rx_errors		  += src->rx_errors;
8174 	dest->tx_errors		  += src->tx_errors;
8175 	dest->rx_dropped	  += src->rx_dropped;
8176 	dest->tx_dropped	  += src->tx_dropped;
8177 	dest->multicast		  += src->multicast;
8178 }
8179 
8180 static int netdev_offload_xstats_get_used(struct net_device *dev,
8181 					  enum netdev_offload_xstats_type type,
8182 					  bool *p_used,
8183 					  struct netlink_ext_ack *extack)
8184 {
8185 	struct netdev_notifier_offload_xstats_ru report_used = {};
8186 	struct netdev_notifier_offload_xstats_info info = {
8187 		.info.dev = dev,
8188 		.info.extack = extack,
8189 		.type = type,
8190 		.report_used = &report_used,
8191 	};
8192 	int rc;
8193 
8194 	WARN_ON(!netdev_offload_xstats_enabled(dev, type));
8195 	rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
8196 					   &info.info);
8197 	*p_used = report_used.used;
8198 	return notifier_to_errno(rc);
8199 }
8200 
8201 static int netdev_offload_xstats_get_stats(struct net_device *dev,
8202 					   enum netdev_offload_xstats_type type,
8203 					   struct rtnl_hw_stats64 *p_stats,
8204 					   bool *p_used,
8205 					   struct netlink_ext_ack *extack)
8206 {
8207 	struct netdev_notifier_offload_xstats_rd report_delta = {};
8208 	struct netdev_notifier_offload_xstats_info info = {
8209 		.info.dev = dev,
8210 		.info.extack = extack,
8211 		.type = type,
8212 		.report_delta = &report_delta,
8213 	};
8214 	struct rtnl_hw_stats64 *stats;
8215 	int rc;
8216 
8217 	stats = netdev_offload_xstats_get_ptr(dev, type);
8218 	if (WARN_ON(!stats))
8219 		return -EINVAL;
8220 
8221 	rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
8222 					   &info.info);
8223 
8224 	/* Cache whatever we got, even if there was an error, otherwise the
8225 	 * successful stats retrievals would get lost.
8226 	 */
8227 	netdev_hw_stats64_add(stats, &report_delta.stats);
8228 
8229 	if (p_stats)
8230 		*p_stats = *stats;
8231 	*p_used = report_delta.used;
8232 
8233 	return notifier_to_errno(rc);
8234 }
8235 
8236 int netdev_offload_xstats_get(struct net_device *dev,
8237 			      enum netdev_offload_xstats_type type,
8238 			      struct rtnl_hw_stats64 *p_stats, bool *p_used,
8239 			      struct netlink_ext_ack *extack)
8240 {
8241 	ASSERT_RTNL();
8242 
8243 	if (p_stats)
8244 		return netdev_offload_xstats_get_stats(dev, type, p_stats,
8245 						       p_used, extack);
8246 	else
8247 		return netdev_offload_xstats_get_used(dev, type, p_used,
8248 						      extack);
8249 }
8250 EXPORT_SYMBOL(netdev_offload_xstats_get);
8251 
8252 void
8253 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
8254 				   const struct rtnl_hw_stats64 *stats)
8255 {
8256 	report_delta->used = true;
8257 	netdev_hw_stats64_add(&report_delta->stats, stats);
8258 }
8259 EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
8260 
8261 void
8262 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
8263 {
8264 	report_used->used = true;
8265 }
8266 EXPORT_SYMBOL(netdev_offload_xstats_report_used);
8267 
8268 void netdev_offload_xstats_push_delta(struct net_device *dev,
8269 				      enum netdev_offload_xstats_type type,
8270 				      const struct rtnl_hw_stats64 *p_stats)
8271 {
8272 	struct rtnl_hw_stats64 *stats;
8273 
8274 	ASSERT_RTNL();
8275 
8276 	stats = netdev_offload_xstats_get_ptr(dev, type);
8277 	if (WARN_ON(!stats))
8278 		return;
8279 
8280 	netdev_hw_stats64_add(stats, p_stats);
8281 }
8282 EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
8283 
8284 /**
8285  * netdev_get_xmit_slave - Get the xmit slave of master device
8286  * @dev: device
8287  * @skb: The packet
8288  * @all_slaves: assume all the slaves are active
8289  *
8290  * The reference counters are not incremented so the caller must be
8291  * careful with locks. The caller must hold RCU lock.
8292  * %NULL is returned if no slave is found.
8293  */
8294 
8295 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8296 					 struct sk_buff *skb,
8297 					 bool all_slaves)
8298 {
8299 	const struct net_device_ops *ops = dev->netdev_ops;
8300 
8301 	if (!ops->ndo_get_xmit_slave)
8302 		return NULL;
8303 	return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8304 }
8305 EXPORT_SYMBOL(netdev_get_xmit_slave);
8306 
8307 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
8308 						  struct sock *sk)
8309 {
8310 	const struct net_device_ops *ops = dev->netdev_ops;
8311 
8312 	if (!ops->ndo_sk_get_lower_dev)
8313 		return NULL;
8314 	return ops->ndo_sk_get_lower_dev(dev, sk);
8315 }
8316 
8317 /**
8318  * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
8319  * @dev: device
8320  * @sk: the socket
8321  *
8322  * %NULL is returned if no lower device is found.
8323  */
8324 
8325 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
8326 					    struct sock *sk)
8327 {
8328 	struct net_device *lower;
8329 
8330 	lower = netdev_sk_get_lower_dev(dev, sk);
8331 	while (lower) {
8332 		dev = lower;
8333 		lower = netdev_sk_get_lower_dev(dev, sk);
8334 	}
8335 
8336 	return dev;
8337 }
8338 EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
8339 
8340 static void netdev_adjacent_add_links(struct net_device *dev)
8341 {
8342 	struct netdev_adjacent *iter;
8343 
8344 	struct net *net = dev_net(dev);
8345 
8346 	list_for_each_entry(iter, &dev->adj_list.upper, list) {
8347 		if (!net_eq(net, dev_net(iter->dev)))
8348 			continue;
8349 		netdev_adjacent_sysfs_add(iter->dev, dev,
8350 					  &iter->dev->adj_list.lower);
8351 		netdev_adjacent_sysfs_add(dev, iter->dev,
8352 					  &dev->adj_list.upper);
8353 	}
8354 
8355 	list_for_each_entry(iter, &dev->adj_list.lower, list) {
8356 		if (!net_eq(net, dev_net(iter->dev)))
8357 			continue;
8358 		netdev_adjacent_sysfs_add(iter->dev, dev,
8359 					  &iter->dev->adj_list.upper);
8360 		netdev_adjacent_sysfs_add(dev, iter->dev,
8361 					  &dev->adj_list.lower);
8362 	}
8363 }
8364 
8365 static void netdev_adjacent_del_links(struct net_device *dev)
8366 {
8367 	struct netdev_adjacent *iter;
8368 
8369 	struct net *net = dev_net(dev);
8370 
8371 	list_for_each_entry(iter, &dev->adj_list.upper, list) {
8372 		if (!net_eq(net, dev_net(iter->dev)))
8373 			continue;
8374 		netdev_adjacent_sysfs_del(iter->dev, dev->name,
8375 					  &iter->dev->adj_list.lower);
8376 		netdev_adjacent_sysfs_del(dev, iter->dev->name,
8377 					  &dev->adj_list.upper);
8378 	}
8379 
8380 	list_for_each_entry(iter, &dev->adj_list.lower, list) {
8381 		if (!net_eq(net, dev_net(iter->dev)))
8382 			continue;
8383 		netdev_adjacent_sysfs_del(iter->dev, dev->name,
8384 					  &iter->dev->adj_list.upper);
8385 		netdev_adjacent_sysfs_del(dev, iter->dev->name,
8386 					  &dev->adj_list.lower);
8387 	}
8388 }
8389 
8390 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8391 {
8392 	struct netdev_adjacent *iter;
8393 
8394 	struct net *net = dev_net(dev);
8395 
8396 	list_for_each_entry(iter, &dev->adj_list.upper, list) {
8397 		if (!net_eq(net, dev_net(iter->dev)))
8398 			continue;
8399 		netdev_adjacent_sysfs_del(iter->dev, oldname,
8400 					  &iter->dev->adj_list.lower);
8401 		netdev_adjacent_sysfs_add(iter->dev, dev,
8402 					  &iter->dev->adj_list.lower);
8403 	}
8404 
8405 	list_for_each_entry(iter, &dev->adj_list.lower, list) {
8406 		if (!net_eq(net, dev_net(iter->dev)))
8407 			continue;
8408 		netdev_adjacent_sysfs_del(iter->dev, oldname,
8409 					  &iter->dev->adj_list.upper);
8410 		netdev_adjacent_sysfs_add(iter->dev, dev,
8411 					  &iter->dev->adj_list.upper);
8412 	}
8413 }
8414 
8415 void *netdev_lower_dev_get_private(struct net_device *dev,
8416 				   struct net_device *lower_dev)
8417 {
8418 	struct netdev_adjacent *lower;
8419 
8420 	if (!lower_dev)
8421 		return NULL;
8422 	lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8423 	if (!lower)
8424 		return NULL;
8425 
8426 	return lower->private;
8427 }
8428 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8429 
8430 
8431 /**
8432  * netdev_lower_state_changed - Dispatch event about lower device state change
8433  * @lower_dev: device
8434  * @lower_state_info: state to dispatch
8435  *
8436  * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8437  * The caller must hold the RTNL lock.
8438  */
8439 void netdev_lower_state_changed(struct net_device *lower_dev,
8440 				void *lower_state_info)
8441 {
8442 	struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8443 		.info.dev = lower_dev,
8444 	};
8445 
8446 	ASSERT_RTNL();
8447 	changelowerstate_info.lower_state_info = lower_state_info;
8448 	call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8449 				      &changelowerstate_info.info);
8450 }
8451 EXPORT_SYMBOL(netdev_lower_state_changed);
8452 
8453 static void dev_change_rx_flags(struct net_device *dev, int flags)
8454 {
8455 	const struct net_device_ops *ops = dev->netdev_ops;
8456 
8457 	if (ops->ndo_change_rx_flags)
8458 		ops->ndo_change_rx_flags(dev, flags);
8459 }
8460 
8461 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8462 {
8463 	unsigned int old_flags = dev->flags;
8464 	kuid_t uid;
8465 	kgid_t gid;
8466 
8467 	ASSERT_RTNL();
8468 
8469 	dev->flags |= IFF_PROMISC;
8470 	dev->promiscuity += inc;
8471 	if (dev->promiscuity == 0) {
8472 		/*
8473 		 * Avoid overflow.
8474 		 * If inc causes overflow, untouch promisc and return error.
8475 		 */
8476 		if (inc < 0)
8477 			dev->flags &= ~IFF_PROMISC;
8478 		else {
8479 			dev->promiscuity -= inc;
8480 			netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
8481 			return -EOVERFLOW;
8482 		}
8483 	}
8484 	if (dev->flags != old_flags) {
8485 		netdev_info(dev, "%s promiscuous mode\n",
8486 			    dev->flags & IFF_PROMISC ? "entered" : "left");
8487 		if (audit_enabled) {
8488 			current_uid_gid(&uid, &gid);
8489 			audit_log(audit_context(), GFP_ATOMIC,
8490 				  AUDIT_ANOM_PROMISCUOUS,
8491 				  "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8492 				  dev->name, (dev->flags & IFF_PROMISC),
8493 				  (old_flags & IFF_PROMISC),
8494 				  from_kuid(&init_user_ns, audit_get_loginuid(current)),
8495 				  from_kuid(&init_user_ns, uid),
8496 				  from_kgid(&init_user_ns, gid),
8497 				  audit_get_sessionid(current));
8498 		}
8499 
8500 		dev_change_rx_flags(dev, IFF_PROMISC);
8501 	}
8502 	if (notify)
8503 		__dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL);
8504 	return 0;
8505 }
8506 
8507 /**
8508  *	dev_set_promiscuity	- update promiscuity count on a device
8509  *	@dev: device
8510  *	@inc: modifier
8511  *
8512  *	Add or remove promiscuity from a device. While the count in the device
8513  *	remains above zero the interface remains promiscuous. Once it hits zero
8514  *	the device reverts back to normal filtering operation. A negative inc
8515  *	value is used to drop promiscuity on the device.
8516  *	Return 0 if successful or a negative errno code on error.
8517  */
8518 int dev_set_promiscuity(struct net_device *dev, int inc)
8519 {
8520 	unsigned int old_flags = dev->flags;
8521 	int err;
8522 
8523 	err = __dev_set_promiscuity(dev, inc, true);
8524 	if (err < 0)
8525 		return err;
8526 	if (dev->flags != old_flags)
8527 		dev_set_rx_mode(dev);
8528 	return err;
8529 }
8530 EXPORT_SYMBOL(dev_set_promiscuity);
8531 
8532 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8533 {
8534 	unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8535 
8536 	ASSERT_RTNL();
8537 
8538 	dev->flags |= IFF_ALLMULTI;
8539 	dev->allmulti += inc;
8540 	if (dev->allmulti == 0) {
8541 		/*
8542 		 * Avoid overflow.
8543 		 * If inc causes overflow, untouch allmulti and return error.
8544 		 */
8545 		if (inc < 0)
8546 			dev->flags &= ~IFF_ALLMULTI;
8547 		else {
8548 			dev->allmulti -= inc;
8549 			netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
8550 			return -EOVERFLOW;
8551 		}
8552 	}
8553 	if (dev->flags ^ old_flags) {
8554 		netdev_info(dev, "%s allmulticast mode\n",
8555 			    dev->flags & IFF_ALLMULTI ? "entered" : "left");
8556 		dev_change_rx_flags(dev, IFF_ALLMULTI);
8557 		dev_set_rx_mode(dev);
8558 		if (notify)
8559 			__dev_notify_flags(dev, old_flags,
8560 					   dev->gflags ^ old_gflags, 0, NULL);
8561 	}
8562 	return 0;
8563 }
8564 
8565 /**
8566  *	dev_set_allmulti	- update allmulti count on a device
8567  *	@dev: device
8568  *	@inc: modifier
8569  *
8570  *	Add or remove reception of all multicast frames to a device. While the
8571  *	count in the device remains above zero the interface remains listening
8572  *	to all interfaces. Once it hits zero the device reverts back to normal
8573  *	filtering operation. A negative @inc value is used to drop the counter
8574  *	when releasing a resource needing all multicasts.
8575  *	Return 0 if successful or a negative errno code on error.
8576  */
8577 
8578 int dev_set_allmulti(struct net_device *dev, int inc)
8579 {
8580 	return __dev_set_allmulti(dev, inc, true);
8581 }
8582 EXPORT_SYMBOL(dev_set_allmulti);
8583 
8584 /*
8585  *	Upload unicast and multicast address lists to device and
8586  *	configure RX filtering. When the device doesn't support unicast
8587  *	filtering it is put in promiscuous mode while unicast addresses
8588  *	are present.
8589  */
8590 void __dev_set_rx_mode(struct net_device *dev)
8591 {
8592 	const struct net_device_ops *ops = dev->netdev_ops;
8593 
8594 	/* dev_open will call this function so the list will stay sane. */
8595 	if (!(dev->flags&IFF_UP))
8596 		return;
8597 
8598 	if (!netif_device_present(dev))
8599 		return;
8600 
8601 	if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8602 		/* Unicast addresses changes may only happen under the rtnl,
8603 		 * therefore calling __dev_set_promiscuity here is safe.
8604 		 */
8605 		if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8606 			__dev_set_promiscuity(dev, 1, false);
8607 			dev->uc_promisc = true;
8608 		} else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8609 			__dev_set_promiscuity(dev, -1, false);
8610 			dev->uc_promisc = false;
8611 		}
8612 	}
8613 
8614 	if (ops->ndo_set_rx_mode)
8615 		ops->ndo_set_rx_mode(dev);
8616 }
8617 
8618 void dev_set_rx_mode(struct net_device *dev)
8619 {
8620 	netif_addr_lock_bh(dev);
8621 	__dev_set_rx_mode(dev);
8622 	netif_addr_unlock_bh(dev);
8623 }
8624 
8625 /**
8626  *	dev_get_flags - get flags reported to userspace
8627  *	@dev: device
8628  *
8629  *	Get the combination of flag bits exported through APIs to userspace.
8630  */
8631 unsigned int dev_get_flags(const struct net_device *dev)
8632 {
8633 	unsigned int flags;
8634 
8635 	flags = (dev->flags & ~(IFF_PROMISC |
8636 				IFF_ALLMULTI |
8637 				IFF_RUNNING |
8638 				IFF_LOWER_UP |
8639 				IFF_DORMANT)) |
8640 		(dev->gflags & (IFF_PROMISC |
8641 				IFF_ALLMULTI));
8642 
8643 	if (netif_running(dev)) {
8644 		if (netif_oper_up(dev))
8645 			flags |= IFF_RUNNING;
8646 		if (netif_carrier_ok(dev))
8647 			flags |= IFF_LOWER_UP;
8648 		if (netif_dormant(dev))
8649 			flags |= IFF_DORMANT;
8650 	}
8651 
8652 	return flags;
8653 }
8654 EXPORT_SYMBOL(dev_get_flags);
8655 
8656 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8657 		       struct netlink_ext_ack *extack)
8658 {
8659 	unsigned int old_flags = dev->flags;
8660 	int ret;
8661 
8662 	ASSERT_RTNL();
8663 
8664 	/*
8665 	 *	Set the flags on our device.
8666 	 */
8667 
8668 	dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8669 			       IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8670 			       IFF_AUTOMEDIA)) |
8671 		     (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8672 				    IFF_ALLMULTI));
8673 
8674 	/*
8675 	 *	Load in the correct multicast list now the flags have changed.
8676 	 */
8677 
8678 	if ((old_flags ^ flags) & IFF_MULTICAST)
8679 		dev_change_rx_flags(dev, IFF_MULTICAST);
8680 
8681 	dev_set_rx_mode(dev);
8682 
8683 	/*
8684 	 *	Have we downed the interface. We handle IFF_UP ourselves
8685 	 *	according to user attempts to set it, rather than blindly
8686 	 *	setting it.
8687 	 */
8688 
8689 	ret = 0;
8690 	if ((old_flags ^ flags) & IFF_UP) {
8691 		if (old_flags & IFF_UP)
8692 			__dev_close(dev);
8693 		else
8694 			ret = __dev_open(dev, extack);
8695 	}
8696 
8697 	if ((flags ^ dev->gflags) & IFF_PROMISC) {
8698 		int inc = (flags & IFF_PROMISC) ? 1 : -1;
8699 		unsigned int old_flags = dev->flags;
8700 
8701 		dev->gflags ^= IFF_PROMISC;
8702 
8703 		if (__dev_set_promiscuity(dev, inc, false) >= 0)
8704 			if (dev->flags != old_flags)
8705 				dev_set_rx_mode(dev);
8706 	}
8707 
8708 	/* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8709 	 * is important. Some (broken) drivers set IFF_PROMISC, when
8710 	 * IFF_ALLMULTI is requested not asking us and not reporting.
8711 	 */
8712 	if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8713 		int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8714 
8715 		dev->gflags ^= IFF_ALLMULTI;
8716 		__dev_set_allmulti(dev, inc, false);
8717 	}
8718 
8719 	return ret;
8720 }
8721 
8722 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8723 			unsigned int gchanges, u32 portid,
8724 			const struct nlmsghdr *nlh)
8725 {
8726 	unsigned int changes = dev->flags ^ old_flags;
8727 
8728 	if (gchanges)
8729 		rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh);
8730 
8731 	if (changes & IFF_UP) {
8732 		if (dev->flags & IFF_UP)
8733 			call_netdevice_notifiers(NETDEV_UP, dev);
8734 		else
8735 			call_netdevice_notifiers(NETDEV_DOWN, dev);
8736 	}
8737 
8738 	if (dev->flags & IFF_UP &&
8739 	    (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8740 		struct netdev_notifier_change_info change_info = {
8741 			.info = {
8742 				.dev = dev,
8743 			},
8744 			.flags_changed = changes,
8745 		};
8746 
8747 		call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8748 	}
8749 }
8750 
8751 /**
8752  *	dev_change_flags - change device settings
8753  *	@dev: device
8754  *	@flags: device state flags
8755  *	@extack: netlink extended ack
8756  *
8757  *	Change settings on device based state flags. The flags are
8758  *	in the userspace exported format.
8759  */
8760 int dev_change_flags(struct net_device *dev, unsigned int flags,
8761 		     struct netlink_ext_ack *extack)
8762 {
8763 	int ret;
8764 	unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8765 
8766 	ret = __dev_change_flags(dev, flags, extack);
8767 	if (ret < 0)
8768 		return ret;
8769 
8770 	changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8771 	__dev_notify_flags(dev, old_flags, changes, 0, NULL);
8772 	return ret;
8773 }
8774 EXPORT_SYMBOL(dev_change_flags);
8775 
8776 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8777 {
8778 	const struct net_device_ops *ops = dev->netdev_ops;
8779 
8780 	if (ops->ndo_change_mtu)
8781 		return ops->ndo_change_mtu(dev, new_mtu);
8782 
8783 	/* Pairs with all the lockless reads of dev->mtu in the stack */
8784 	WRITE_ONCE(dev->mtu, new_mtu);
8785 	return 0;
8786 }
8787 EXPORT_SYMBOL(__dev_set_mtu);
8788 
8789 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8790 		     struct netlink_ext_ack *extack)
8791 {
8792 	/* MTU must be positive, and in range */
8793 	if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8794 		NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8795 		return -EINVAL;
8796 	}
8797 
8798 	if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8799 		NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8800 		return -EINVAL;
8801 	}
8802 	return 0;
8803 }
8804 
8805 /**
8806  *	dev_set_mtu_ext - Change maximum transfer unit
8807  *	@dev: device
8808  *	@new_mtu: new transfer unit
8809  *	@extack: netlink extended ack
8810  *
8811  *	Change the maximum transfer size of the network device.
8812  */
8813 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8814 		    struct netlink_ext_ack *extack)
8815 {
8816 	int err, orig_mtu;
8817 
8818 	if (new_mtu == dev->mtu)
8819 		return 0;
8820 
8821 	err = dev_validate_mtu(dev, new_mtu, extack);
8822 	if (err)
8823 		return err;
8824 
8825 	if (!netif_device_present(dev))
8826 		return -ENODEV;
8827 
8828 	err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8829 	err = notifier_to_errno(err);
8830 	if (err)
8831 		return err;
8832 
8833 	orig_mtu = dev->mtu;
8834 	err = __dev_set_mtu(dev, new_mtu);
8835 
8836 	if (!err) {
8837 		err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8838 						   orig_mtu);
8839 		err = notifier_to_errno(err);
8840 		if (err) {
8841 			/* setting mtu back and notifying everyone again,
8842 			 * so that they have a chance to revert changes.
8843 			 */
8844 			__dev_set_mtu(dev, orig_mtu);
8845 			call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8846 						     new_mtu);
8847 		}
8848 	}
8849 	return err;
8850 }
8851 
8852 int dev_set_mtu(struct net_device *dev, int new_mtu)
8853 {
8854 	struct netlink_ext_ack extack;
8855 	int err;
8856 
8857 	memset(&extack, 0, sizeof(extack));
8858 	err = dev_set_mtu_ext(dev, new_mtu, &extack);
8859 	if (err && extack._msg)
8860 		net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8861 	return err;
8862 }
8863 EXPORT_SYMBOL(dev_set_mtu);
8864 
8865 /**
8866  *	dev_change_tx_queue_len - Change TX queue length of a netdevice
8867  *	@dev: device
8868  *	@new_len: new tx queue length
8869  */
8870 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8871 {
8872 	unsigned int orig_len = dev->tx_queue_len;
8873 	int res;
8874 
8875 	if (new_len != (unsigned int)new_len)
8876 		return -ERANGE;
8877 
8878 	if (new_len != orig_len) {
8879 		dev->tx_queue_len = new_len;
8880 		res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8881 		res = notifier_to_errno(res);
8882 		if (res)
8883 			goto err_rollback;
8884 		res = dev_qdisc_change_tx_queue_len(dev);
8885 		if (res)
8886 			goto err_rollback;
8887 	}
8888 
8889 	return 0;
8890 
8891 err_rollback:
8892 	netdev_err(dev, "refused to change device tx_queue_len\n");
8893 	dev->tx_queue_len = orig_len;
8894 	return res;
8895 }
8896 
8897 /**
8898  *	dev_set_group - Change group this device belongs to
8899  *	@dev: device
8900  *	@new_group: group this device should belong to
8901  */
8902 void dev_set_group(struct net_device *dev, int new_group)
8903 {
8904 	dev->group = new_group;
8905 }
8906 
8907 /**
8908  *	dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8909  *	@dev: device
8910  *	@addr: new address
8911  *	@extack: netlink extended ack
8912  */
8913 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8914 			      struct netlink_ext_ack *extack)
8915 {
8916 	struct netdev_notifier_pre_changeaddr_info info = {
8917 		.info.dev = dev,
8918 		.info.extack = extack,
8919 		.dev_addr = addr,
8920 	};
8921 	int rc;
8922 
8923 	rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8924 	return notifier_to_errno(rc);
8925 }
8926 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8927 
8928 /**
8929  *	dev_set_mac_address - Change Media Access Control Address
8930  *	@dev: device
8931  *	@sa: new address
8932  *	@extack: netlink extended ack
8933  *
8934  *	Change the hardware (MAC) address of the device
8935  */
8936 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8937 			struct netlink_ext_ack *extack)
8938 {
8939 	const struct net_device_ops *ops = dev->netdev_ops;
8940 	int err;
8941 
8942 	if (!ops->ndo_set_mac_address)
8943 		return -EOPNOTSUPP;
8944 	if (sa->sa_family != dev->type)
8945 		return -EINVAL;
8946 	if (!netif_device_present(dev))
8947 		return -ENODEV;
8948 	err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8949 	if (err)
8950 		return err;
8951 	if (memcmp(dev->dev_addr, sa->sa_data, dev->addr_len)) {
8952 		err = ops->ndo_set_mac_address(dev, sa);
8953 		if (err)
8954 			return err;
8955 	}
8956 	dev->addr_assign_type = NET_ADDR_SET;
8957 	call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8958 	add_device_randomness(dev->dev_addr, dev->addr_len);
8959 	return 0;
8960 }
8961 EXPORT_SYMBOL(dev_set_mac_address);
8962 
8963 DECLARE_RWSEM(dev_addr_sem);
8964 
8965 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
8966 			     struct netlink_ext_ack *extack)
8967 {
8968 	int ret;
8969 
8970 	down_write(&dev_addr_sem);
8971 	ret = dev_set_mac_address(dev, sa, extack);
8972 	up_write(&dev_addr_sem);
8973 	return ret;
8974 }
8975 EXPORT_SYMBOL(dev_set_mac_address_user);
8976 
8977 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
8978 {
8979 	size_t size = sizeof(sa->sa_data_min);
8980 	struct net_device *dev;
8981 	int ret = 0;
8982 
8983 	down_read(&dev_addr_sem);
8984 	rcu_read_lock();
8985 
8986 	dev = dev_get_by_name_rcu(net, dev_name);
8987 	if (!dev) {
8988 		ret = -ENODEV;
8989 		goto unlock;
8990 	}
8991 	if (!dev->addr_len)
8992 		memset(sa->sa_data, 0, size);
8993 	else
8994 		memcpy(sa->sa_data, dev->dev_addr,
8995 		       min_t(size_t, size, dev->addr_len));
8996 	sa->sa_family = dev->type;
8997 
8998 unlock:
8999 	rcu_read_unlock();
9000 	up_read(&dev_addr_sem);
9001 	return ret;
9002 }
9003 EXPORT_SYMBOL(dev_get_mac_address);
9004 
9005 /**
9006  *	dev_change_carrier - Change device carrier
9007  *	@dev: device
9008  *	@new_carrier: new value
9009  *
9010  *	Change device carrier
9011  */
9012 int dev_change_carrier(struct net_device *dev, bool new_carrier)
9013 {
9014 	const struct net_device_ops *ops = dev->netdev_ops;
9015 
9016 	if (!ops->ndo_change_carrier)
9017 		return -EOPNOTSUPP;
9018 	if (!netif_device_present(dev))
9019 		return -ENODEV;
9020 	return ops->ndo_change_carrier(dev, new_carrier);
9021 }
9022 
9023 /**
9024  *	dev_get_phys_port_id - Get device physical port ID
9025  *	@dev: device
9026  *	@ppid: port ID
9027  *
9028  *	Get device physical port ID
9029  */
9030 int dev_get_phys_port_id(struct net_device *dev,
9031 			 struct netdev_phys_item_id *ppid)
9032 {
9033 	const struct net_device_ops *ops = dev->netdev_ops;
9034 
9035 	if (!ops->ndo_get_phys_port_id)
9036 		return -EOPNOTSUPP;
9037 	return ops->ndo_get_phys_port_id(dev, ppid);
9038 }
9039 
9040 /**
9041  *	dev_get_phys_port_name - Get device physical port name
9042  *	@dev: device
9043  *	@name: port name
9044  *	@len: limit of bytes to copy to name
9045  *
9046  *	Get device physical port name
9047  */
9048 int dev_get_phys_port_name(struct net_device *dev,
9049 			   char *name, size_t len)
9050 {
9051 	const struct net_device_ops *ops = dev->netdev_ops;
9052 	int err;
9053 
9054 	if (ops->ndo_get_phys_port_name) {
9055 		err = ops->ndo_get_phys_port_name(dev, name, len);
9056 		if (err != -EOPNOTSUPP)
9057 			return err;
9058 	}
9059 	return devlink_compat_phys_port_name_get(dev, name, len);
9060 }
9061 
9062 /**
9063  *	dev_get_port_parent_id - Get the device's port parent identifier
9064  *	@dev: network device
9065  *	@ppid: pointer to a storage for the port's parent identifier
9066  *	@recurse: allow/disallow recursion to lower devices
9067  *
9068  *	Get the devices's port parent identifier
9069  */
9070 int dev_get_port_parent_id(struct net_device *dev,
9071 			   struct netdev_phys_item_id *ppid,
9072 			   bool recurse)
9073 {
9074 	const struct net_device_ops *ops = dev->netdev_ops;
9075 	struct netdev_phys_item_id first = { };
9076 	struct net_device *lower_dev;
9077 	struct list_head *iter;
9078 	int err;
9079 
9080 	if (ops->ndo_get_port_parent_id) {
9081 		err = ops->ndo_get_port_parent_id(dev, ppid);
9082 		if (err != -EOPNOTSUPP)
9083 			return err;
9084 	}
9085 
9086 	err = devlink_compat_switch_id_get(dev, ppid);
9087 	if (!recurse || err != -EOPNOTSUPP)
9088 		return err;
9089 
9090 	netdev_for_each_lower_dev(dev, lower_dev, iter) {
9091 		err = dev_get_port_parent_id(lower_dev, ppid, true);
9092 		if (err)
9093 			break;
9094 		if (!first.id_len)
9095 			first = *ppid;
9096 		else if (memcmp(&first, ppid, sizeof(*ppid)))
9097 			return -EOPNOTSUPP;
9098 	}
9099 
9100 	return err;
9101 }
9102 EXPORT_SYMBOL(dev_get_port_parent_id);
9103 
9104 /**
9105  *	netdev_port_same_parent_id - Indicate if two network devices have
9106  *	the same port parent identifier
9107  *	@a: first network device
9108  *	@b: second network device
9109  */
9110 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
9111 {
9112 	struct netdev_phys_item_id a_id = { };
9113 	struct netdev_phys_item_id b_id = { };
9114 
9115 	if (dev_get_port_parent_id(a, &a_id, true) ||
9116 	    dev_get_port_parent_id(b, &b_id, true))
9117 		return false;
9118 
9119 	return netdev_phys_item_id_same(&a_id, &b_id);
9120 }
9121 EXPORT_SYMBOL(netdev_port_same_parent_id);
9122 
9123 static void netdev_dpll_pin_assign(struct net_device *dev, struct dpll_pin *dpll_pin)
9124 {
9125 #if IS_ENABLED(CONFIG_DPLL)
9126 	rtnl_lock();
9127 	dev->dpll_pin = dpll_pin;
9128 	rtnl_unlock();
9129 #endif
9130 }
9131 
9132 void netdev_dpll_pin_set(struct net_device *dev, struct dpll_pin *dpll_pin)
9133 {
9134 	WARN_ON(!dpll_pin);
9135 	netdev_dpll_pin_assign(dev, dpll_pin);
9136 }
9137 EXPORT_SYMBOL(netdev_dpll_pin_set);
9138 
9139 void netdev_dpll_pin_clear(struct net_device *dev)
9140 {
9141 	netdev_dpll_pin_assign(dev, NULL);
9142 }
9143 EXPORT_SYMBOL(netdev_dpll_pin_clear);
9144 
9145 /**
9146  *	dev_change_proto_down - set carrier according to proto_down.
9147  *
9148  *	@dev: device
9149  *	@proto_down: new value
9150  */
9151 int dev_change_proto_down(struct net_device *dev, bool proto_down)
9152 {
9153 	if (!(dev->priv_flags & IFF_CHANGE_PROTO_DOWN))
9154 		return -EOPNOTSUPP;
9155 	if (!netif_device_present(dev))
9156 		return -ENODEV;
9157 	if (proto_down)
9158 		netif_carrier_off(dev);
9159 	else
9160 		netif_carrier_on(dev);
9161 	dev->proto_down = proto_down;
9162 	return 0;
9163 }
9164 
9165 /**
9166  *	dev_change_proto_down_reason - proto down reason
9167  *
9168  *	@dev: device
9169  *	@mask: proto down mask
9170  *	@value: proto down value
9171  */
9172 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
9173 				  u32 value)
9174 {
9175 	int b;
9176 
9177 	if (!mask) {
9178 		dev->proto_down_reason = value;
9179 	} else {
9180 		for_each_set_bit(b, &mask, 32) {
9181 			if (value & (1 << b))
9182 				dev->proto_down_reason |= BIT(b);
9183 			else
9184 				dev->proto_down_reason &= ~BIT(b);
9185 		}
9186 	}
9187 }
9188 
9189 struct bpf_xdp_link {
9190 	struct bpf_link link;
9191 	struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
9192 	int flags;
9193 };
9194 
9195 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
9196 {
9197 	if (flags & XDP_FLAGS_HW_MODE)
9198 		return XDP_MODE_HW;
9199 	if (flags & XDP_FLAGS_DRV_MODE)
9200 		return XDP_MODE_DRV;
9201 	if (flags & XDP_FLAGS_SKB_MODE)
9202 		return XDP_MODE_SKB;
9203 	return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
9204 }
9205 
9206 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
9207 {
9208 	switch (mode) {
9209 	case XDP_MODE_SKB:
9210 		return generic_xdp_install;
9211 	case XDP_MODE_DRV:
9212 	case XDP_MODE_HW:
9213 		return dev->netdev_ops->ndo_bpf;
9214 	default:
9215 		return NULL;
9216 	}
9217 }
9218 
9219 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
9220 					 enum bpf_xdp_mode mode)
9221 {
9222 	return dev->xdp_state[mode].link;
9223 }
9224 
9225 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
9226 				     enum bpf_xdp_mode mode)
9227 {
9228 	struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
9229 
9230 	if (link)
9231 		return link->link.prog;
9232 	return dev->xdp_state[mode].prog;
9233 }
9234 
9235 u8 dev_xdp_prog_count(struct net_device *dev)
9236 {
9237 	u8 count = 0;
9238 	int i;
9239 
9240 	for (i = 0; i < __MAX_XDP_MODE; i++)
9241 		if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
9242 			count++;
9243 	return count;
9244 }
9245 EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
9246 
9247 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
9248 {
9249 	struct bpf_prog *prog = dev_xdp_prog(dev, mode);
9250 
9251 	return prog ? prog->aux->id : 0;
9252 }
9253 
9254 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
9255 			     struct bpf_xdp_link *link)
9256 {
9257 	dev->xdp_state[mode].link = link;
9258 	dev->xdp_state[mode].prog = NULL;
9259 }
9260 
9261 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
9262 			     struct bpf_prog *prog)
9263 {
9264 	dev->xdp_state[mode].link = NULL;
9265 	dev->xdp_state[mode].prog = prog;
9266 }
9267 
9268 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
9269 			   bpf_op_t bpf_op, struct netlink_ext_ack *extack,
9270 			   u32 flags, struct bpf_prog *prog)
9271 {
9272 	struct netdev_bpf xdp;
9273 	int err;
9274 
9275 	memset(&xdp, 0, sizeof(xdp));
9276 	xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
9277 	xdp.extack = extack;
9278 	xdp.flags = flags;
9279 	xdp.prog = prog;
9280 
9281 	/* Drivers assume refcnt is already incremented (i.e, prog pointer is
9282 	 * "moved" into driver), so they don't increment it on their own, but
9283 	 * they do decrement refcnt when program is detached or replaced.
9284 	 * Given net_device also owns link/prog, we need to bump refcnt here
9285 	 * to prevent drivers from underflowing it.
9286 	 */
9287 	if (prog)
9288 		bpf_prog_inc(prog);
9289 	err = bpf_op(dev, &xdp);
9290 	if (err) {
9291 		if (prog)
9292 			bpf_prog_put(prog);
9293 		return err;
9294 	}
9295 
9296 	if (mode != XDP_MODE_HW)
9297 		bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9298 
9299 	return 0;
9300 }
9301 
9302 static void dev_xdp_uninstall(struct net_device *dev)
9303 {
9304 	struct bpf_xdp_link *link;
9305 	struct bpf_prog *prog;
9306 	enum bpf_xdp_mode mode;
9307 	bpf_op_t bpf_op;
9308 
9309 	ASSERT_RTNL();
9310 
9311 	for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9312 		prog = dev_xdp_prog(dev, mode);
9313 		if (!prog)
9314 			continue;
9315 
9316 		bpf_op = dev_xdp_bpf_op(dev, mode);
9317 		if (!bpf_op)
9318 			continue;
9319 
9320 		WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9321 
9322 		/* auto-detach link from net device */
9323 		link = dev_xdp_link(dev, mode);
9324 		if (link)
9325 			link->dev = NULL;
9326 		else
9327 			bpf_prog_put(prog);
9328 
9329 		dev_xdp_set_link(dev, mode, NULL);
9330 	}
9331 }
9332 
9333 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9334 			  struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9335 			  struct bpf_prog *old_prog, u32 flags)
9336 {
9337 	unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9338 	struct bpf_prog *cur_prog;
9339 	struct net_device *upper;
9340 	struct list_head *iter;
9341 	enum bpf_xdp_mode mode;
9342 	bpf_op_t bpf_op;
9343 	int err;
9344 
9345 	ASSERT_RTNL();
9346 
9347 	/* either link or prog attachment, never both */
9348 	if (link && (new_prog || old_prog))
9349 		return -EINVAL;
9350 	/* link supports only XDP mode flags */
9351 	if (link && (flags & ~XDP_FLAGS_MODES)) {
9352 		NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9353 		return -EINVAL;
9354 	}
9355 	/* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9356 	if (num_modes > 1) {
9357 		NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9358 		return -EINVAL;
9359 	}
9360 	/* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9361 	if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9362 		NL_SET_ERR_MSG(extack,
9363 			       "More than one program loaded, unset mode is ambiguous");
9364 		return -EINVAL;
9365 	}
9366 	/* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9367 	if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9368 		NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9369 		return -EINVAL;
9370 	}
9371 
9372 	mode = dev_xdp_mode(dev, flags);
9373 	/* can't replace attached link */
9374 	if (dev_xdp_link(dev, mode)) {
9375 		NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9376 		return -EBUSY;
9377 	}
9378 
9379 	/* don't allow if an upper device already has a program */
9380 	netdev_for_each_upper_dev_rcu(dev, upper, iter) {
9381 		if (dev_xdp_prog_count(upper) > 0) {
9382 			NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
9383 			return -EEXIST;
9384 		}
9385 	}
9386 
9387 	cur_prog = dev_xdp_prog(dev, mode);
9388 	/* can't replace attached prog with link */
9389 	if (link && cur_prog) {
9390 		NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9391 		return -EBUSY;
9392 	}
9393 	if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9394 		NL_SET_ERR_MSG(extack, "Active program does not match expected");
9395 		return -EEXIST;
9396 	}
9397 
9398 	/* put effective new program into new_prog */
9399 	if (link)
9400 		new_prog = link->link.prog;
9401 
9402 	if (new_prog) {
9403 		bool offload = mode == XDP_MODE_HW;
9404 		enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9405 					       ? XDP_MODE_DRV : XDP_MODE_SKB;
9406 
9407 		if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9408 			NL_SET_ERR_MSG(extack, "XDP program already attached");
9409 			return -EBUSY;
9410 		}
9411 		if (!offload && dev_xdp_prog(dev, other_mode)) {
9412 			NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9413 			return -EEXIST;
9414 		}
9415 		if (!offload && bpf_prog_is_offloaded(new_prog->aux)) {
9416 			NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
9417 			return -EINVAL;
9418 		}
9419 		if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) {
9420 			NL_SET_ERR_MSG(extack, "Program bound to different device");
9421 			return -EINVAL;
9422 		}
9423 		if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9424 			NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9425 			return -EINVAL;
9426 		}
9427 		if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9428 			NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9429 			return -EINVAL;
9430 		}
9431 	}
9432 
9433 	/* don't call drivers if the effective program didn't change */
9434 	if (new_prog != cur_prog) {
9435 		bpf_op = dev_xdp_bpf_op(dev, mode);
9436 		if (!bpf_op) {
9437 			NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9438 			return -EOPNOTSUPP;
9439 		}
9440 
9441 		err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9442 		if (err)
9443 			return err;
9444 	}
9445 
9446 	if (link)
9447 		dev_xdp_set_link(dev, mode, link);
9448 	else
9449 		dev_xdp_set_prog(dev, mode, new_prog);
9450 	if (cur_prog)
9451 		bpf_prog_put(cur_prog);
9452 
9453 	return 0;
9454 }
9455 
9456 static int dev_xdp_attach_link(struct net_device *dev,
9457 			       struct netlink_ext_ack *extack,
9458 			       struct bpf_xdp_link *link)
9459 {
9460 	return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9461 }
9462 
9463 static int dev_xdp_detach_link(struct net_device *dev,
9464 			       struct netlink_ext_ack *extack,
9465 			       struct bpf_xdp_link *link)
9466 {
9467 	enum bpf_xdp_mode mode;
9468 	bpf_op_t bpf_op;
9469 
9470 	ASSERT_RTNL();
9471 
9472 	mode = dev_xdp_mode(dev, link->flags);
9473 	if (dev_xdp_link(dev, mode) != link)
9474 		return -EINVAL;
9475 
9476 	bpf_op = dev_xdp_bpf_op(dev, mode);
9477 	WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9478 	dev_xdp_set_link(dev, mode, NULL);
9479 	return 0;
9480 }
9481 
9482 static void bpf_xdp_link_release(struct bpf_link *link)
9483 {
9484 	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9485 
9486 	rtnl_lock();
9487 
9488 	/* if racing with net_device's tear down, xdp_link->dev might be
9489 	 * already NULL, in which case link was already auto-detached
9490 	 */
9491 	if (xdp_link->dev) {
9492 		WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9493 		xdp_link->dev = NULL;
9494 	}
9495 
9496 	rtnl_unlock();
9497 }
9498 
9499 static int bpf_xdp_link_detach(struct bpf_link *link)
9500 {
9501 	bpf_xdp_link_release(link);
9502 	return 0;
9503 }
9504 
9505 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9506 {
9507 	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9508 
9509 	kfree(xdp_link);
9510 }
9511 
9512 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9513 				     struct seq_file *seq)
9514 {
9515 	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9516 	u32 ifindex = 0;
9517 
9518 	rtnl_lock();
9519 	if (xdp_link->dev)
9520 		ifindex = xdp_link->dev->ifindex;
9521 	rtnl_unlock();
9522 
9523 	seq_printf(seq, "ifindex:\t%u\n", ifindex);
9524 }
9525 
9526 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9527 				       struct bpf_link_info *info)
9528 {
9529 	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9530 	u32 ifindex = 0;
9531 
9532 	rtnl_lock();
9533 	if (xdp_link->dev)
9534 		ifindex = xdp_link->dev->ifindex;
9535 	rtnl_unlock();
9536 
9537 	info->xdp.ifindex = ifindex;
9538 	return 0;
9539 }
9540 
9541 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9542 			       struct bpf_prog *old_prog)
9543 {
9544 	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9545 	enum bpf_xdp_mode mode;
9546 	bpf_op_t bpf_op;
9547 	int err = 0;
9548 
9549 	rtnl_lock();
9550 
9551 	/* link might have been auto-released already, so fail */
9552 	if (!xdp_link->dev) {
9553 		err = -ENOLINK;
9554 		goto out_unlock;
9555 	}
9556 
9557 	if (old_prog && link->prog != old_prog) {
9558 		err = -EPERM;
9559 		goto out_unlock;
9560 	}
9561 	old_prog = link->prog;
9562 	if (old_prog->type != new_prog->type ||
9563 	    old_prog->expected_attach_type != new_prog->expected_attach_type) {
9564 		err = -EINVAL;
9565 		goto out_unlock;
9566 	}
9567 
9568 	if (old_prog == new_prog) {
9569 		/* no-op, don't disturb drivers */
9570 		bpf_prog_put(new_prog);
9571 		goto out_unlock;
9572 	}
9573 
9574 	mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9575 	bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9576 	err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9577 			      xdp_link->flags, new_prog);
9578 	if (err)
9579 		goto out_unlock;
9580 
9581 	old_prog = xchg(&link->prog, new_prog);
9582 	bpf_prog_put(old_prog);
9583 
9584 out_unlock:
9585 	rtnl_unlock();
9586 	return err;
9587 }
9588 
9589 static const struct bpf_link_ops bpf_xdp_link_lops = {
9590 	.release = bpf_xdp_link_release,
9591 	.dealloc = bpf_xdp_link_dealloc,
9592 	.detach = bpf_xdp_link_detach,
9593 	.show_fdinfo = bpf_xdp_link_show_fdinfo,
9594 	.fill_link_info = bpf_xdp_link_fill_link_info,
9595 	.update_prog = bpf_xdp_link_update,
9596 };
9597 
9598 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9599 {
9600 	struct net *net = current->nsproxy->net_ns;
9601 	struct bpf_link_primer link_primer;
9602 	struct netlink_ext_ack extack = {};
9603 	struct bpf_xdp_link *link;
9604 	struct net_device *dev;
9605 	int err, fd;
9606 
9607 	rtnl_lock();
9608 	dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9609 	if (!dev) {
9610 		rtnl_unlock();
9611 		return -EINVAL;
9612 	}
9613 
9614 	link = kzalloc(sizeof(*link), GFP_USER);
9615 	if (!link) {
9616 		err = -ENOMEM;
9617 		goto unlock;
9618 	}
9619 
9620 	bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9621 	link->dev = dev;
9622 	link->flags = attr->link_create.flags;
9623 
9624 	err = bpf_link_prime(&link->link, &link_primer);
9625 	if (err) {
9626 		kfree(link);
9627 		goto unlock;
9628 	}
9629 
9630 	err = dev_xdp_attach_link(dev, &extack, link);
9631 	rtnl_unlock();
9632 
9633 	if (err) {
9634 		link->dev = NULL;
9635 		bpf_link_cleanup(&link_primer);
9636 		trace_bpf_xdp_link_attach_failed(extack._msg);
9637 		goto out_put_dev;
9638 	}
9639 
9640 	fd = bpf_link_settle(&link_primer);
9641 	/* link itself doesn't hold dev's refcnt to not complicate shutdown */
9642 	dev_put(dev);
9643 	return fd;
9644 
9645 unlock:
9646 	rtnl_unlock();
9647 
9648 out_put_dev:
9649 	dev_put(dev);
9650 	return err;
9651 }
9652 
9653 /**
9654  *	dev_change_xdp_fd - set or clear a bpf program for a device rx path
9655  *	@dev: device
9656  *	@extack: netlink extended ack
9657  *	@fd: new program fd or negative value to clear
9658  *	@expected_fd: old program fd that userspace expects to replace or clear
9659  *	@flags: xdp-related flags
9660  *
9661  *	Set or clear a bpf program for a device
9662  */
9663 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9664 		      int fd, int expected_fd, u32 flags)
9665 {
9666 	enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9667 	struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9668 	int err;
9669 
9670 	ASSERT_RTNL();
9671 
9672 	if (fd >= 0) {
9673 		new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9674 						 mode != XDP_MODE_SKB);
9675 		if (IS_ERR(new_prog))
9676 			return PTR_ERR(new_prog);
9677 	}
9678 
9679 	if (expected_fd >= 0) {
9680 		old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9681 						 mode != XDP_MODE_SKB);
9682 		if (IS_ERR(old_prog)) {
9683 			err = PTR_ERR(old_prog);
9684 			old_prog = NULL;
9685 			goto err_out;
9686 		}
9687 	}
9688 
9689 	err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9690 
9691 err_out:
9692 	if (err && new_prog)
9693 		bpf_prog_put(new_prog);
9694 	if (old_prog)
9695 		bpf_prog_put(old_prog);
9696 	return err;
9697 }
9698 
9699 /**
9700  * dev_index_reserve() - allocate an ifindex in a namespace
9701  * @net: the applicable net namespace
9702  * @ifindex: requested ifindex, pass %0 to get one allocated
9703  *
9704  * Allocate a ifindex for a new device. Caller must either use the ifindex
9705  * to store the device (via list_netdevice()) or call dev_index_release()
9706  * to give the index up.
9707  *
9708  * Return: a suitable unique value for a new device interface number or -errno.
9709  */
9710 static int dev_index_reserve(struct net *net, u32 ifindex)
9711 {
9712 	int err;
9713 
9714 	if (ifindex > INT_MAX) {
9715 		DEBUG_NET_WARN_ON_ONCE(1);
9716 		return -EINVAL;
9717 	}
9718 
9719 	if (!ifindex)
9720 		err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL,
9721 				      xa_limit_31b, &net->ifindex, GFP_KERNEL);
9722 	else
9723 		err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL);
9724 	if (err < 0)
9725 		return err;
9726 
9727 	return ifindex;
9728 }
9729 
9730 static void dev_index_release(struct net *net, int ifindex)
9731 {
9732 	/* Expect only unused indexes, unlist_netdevice() removes the used */
9733 	WARN_ON(xa_erase(&net->dev_by_index, ifindex));
9734 }
9735 
9736 /* Delayed registration/unregisteration */
9737 LIST_HEAD(net_todo_list);
9738 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9739 atomic_t dev_unreg_count = ATOMIC_INIT(0);
9740 
9741 static void net_set_todo(struct net_device *dev)
9742 {
9743 	list_add_tail(&dev->todo_list, &net_todo_list);
9744 }
9745 
9746 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9747 	struct net_device *upper, netdev_features_t features)
9748 {
9749 	netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9750 	netdev_features_t feature;
9751 	int feature_bit;
9752 
9753 	for_each_netdev_feature(upper_disables, feature_bit) {
9754 		feature = __NETIF_F_BIT(feature_bit);
9755 		if (!(upper->wanted_features & feature)
9756 		    && (features & feature)) {
9757 			netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9758 				   &feature, upper->name);
9759 			features &= ~feature;
9760 		}
9761 	}
9762 
9763 	return features;
9764 }
9765 
9766 static void netdev_sync_lower_features(struct net_device *upper,
9767 	struct net_device *lower, netdev_features_t features)
9768 {
9769 	netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9770 	netdev_features_t feature;
9771 	int feature_bit;
9772 
9773 	for_each_netdev_feature(upper_disables, feature_bit) {
9774 		feature = __NETIF_F_BIT(feature_bit);
9775 		if (!(features & feature) && (lower->features & feature)) {
9776 			netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9777 				   &feature, lower->name);
9778 			lower->wanted_features &= ~feature;
9779 			__netdev_update_features(lower);
9780 
9781 			if (unlikely(lower->features & feature))
9782 				netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9783 					    &feature, lower->name);
9784 			else
9785 				netdev_features_change(lower);
9786 		}
9787 	}
9788 }
9789 
9790 static netdev_features_t netdev_fix_features(struct net_device *dev,
9791 	netdev_features_t features)
9792 {
9793 	/* Fix illegal checksum combinations */
9794 	if ((features & NETIF_F_HW_CSUM) &&
9795 	    (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9796 		netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9797 		features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9798 	}
9799 
9800 	/* TSO requires that SG is present as well. */
9801 	if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9802 		netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9803 		features &= ~NETIF_F_ALL_TSO;
9804 	}
9805 
9806 	if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9807 					!(features & NETIF_F_IP_CSUM)) {
9808 		netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9809 		features &= ~NETIF_F_TSO;
9810 		features &= ~NETIF_F_TSO_ECN;
9811 	}
9812 
9813 	if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9814 					 !(features & NETIF_F_IPV6_CSUM)) {
9815 		netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9816 		features &= ~NETIF_F_TSO6;
9817 	}
9818 
9819 	/* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9820 	if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9821 		features &= ~NETIF_F_TSO_MANGLEID;
9822 
9823 	/* TSO ECN requires that TSO is present as well. */
9824 	if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9825 		features &= ~NETIF_F_TSO_ECN;
9826 
9827 	/* Software GSO depends on SG. */
9828 	if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9829 		netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9830 		features &= ~NETIF_F_GSO;
9831 	}
9832 
9833 	/* GSO partial features require GSO partial be set */
9834 	if ((features & dev->gso_partial_features) &&
9835 	    !(features & NETIF_F_GSO_PARTIAL)) {
9836 		netdev_dbg(dev,
9837 			   "Dropping partially supported GSO features since no GSO partial.\n");
9838 		features &= ~dev->gso_partial_features;
9839 	}
9840 
9841 	if (!(features & NETIF_F_RXCSUM)) {
9842 		/* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9843 		 * successfully merged by hardware must also have the
9844 		 * checksum verified by hardware.  If the user does not
9845 		 * want to enable RXCSUM, logically, we should disable GRO_HW.
9846 		 */
9847 		if (features & NETIF_F_GRO_HW) {
9848 			netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9849 			features &= ~NETIF_F_GRO_HW;
9850 		}
9851 	}
9852 
9853 	/* LRO/HW-GRO features cannot be combined with RX-FCS */
9854 	if (features & NETIF_F_RXFCS) {
9855 		if (features & NETIF_F_LRO) {
9856 			netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9857 			features &= ~NETIF_F_LRO;
9858 		}
9859 
9860 		if (features & NETIF_F_GRO_HW) {
9861 			netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9862 			features &= ~NETIF_F_GRO_HW;
9863 		}
9864 	}
9865 
9866 	if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
9867 		netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
9868 		features &= ~NETIF_F_LRO;
9869 	}
9870 
9871 	if (features & NETIF_F_HW_TLS_TX) {
9872 		bool ip_csum = (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) ==
9873 			(NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
9874 		bool hw_csum = features & NETIF_F_HW_CSUM;
9875 
9876 		if (!ip_csum && !hw_csum) {
9877 			netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
9878 			features &= ~NETIF_F_HW_TLS_TX;
9879 		}
9880 	}
9881 
9882 	if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
9883 		netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
9884 		features &= ~NETIF_F_HW_TLS_RX;
9885 	}
9886 
9887 	return features;
9888 }
9889 
9890 int __netdev_update_features(struct net_device *dev)
9891 {
9892 	struct net_device *upper, *lower;
9893 	netdev_features_t features;
9894 	struct list_head *iter;
9895 	int err = -1;
9896 
9897 	ASSERT_RTNL();
9898 
9899 	features = netdev_get_wanted_features(dev);
9900 
9901 	if (dev->netdev_ops->ndo_fix_features)
9902 		features = dev->netdev_ops->ndo_fix_features(dev, features);
9903 
9904 	/* driver might be less strict about feature dependencies */
9905 	features = netdev_fix_features(dev, features);
9906 
9907 	/* some features can't be enabled if they're off on an upper device */
9908 	netdev_for_each_upper_dev_rcu(dev, upper, iter)
9909 		features = netdev_sync_upper_features(dev, upper, features);
9910 
9911 	if (dev->features == features)
9912 		goto sync_lower;
9913 
9914 	netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9915 		&dev->features, &features);
9916 
9917 	if (dev->netdev_ops->ndo_set_features)
9918 		err = dev->netdev_ops->ndo_set_features(dev, features);
9919 	else
9920 		err = 0;
9921 
9922 	if (unlikely(err < 0)) {
9923 		netdev_err(dev,
9924 			"set_features() failed (%d); wanted %pNF, left %pNF\n",
9925 			err, &features, &dev->features);
9926 		/* return non-0 since some features might have changed and
9927 		 * it's better to fire a spurious notification than miss it
9928 		 */
9929 		return -1;
9930 	}
9931 
9932 sync_lower:
9933 	/* some features must be disabled on lower devices when disabled
9934 	 * on an upper device (think: bonding master or bridge)
9935 	 */
9936 	netdev_for_each_lower_dev(dev, lower, iter)
9937 		netdev_sync_lower_features(dev, lower, features);
9938 
9939 	if (!err) {
9940 		netdev_features_t diff = features ^ dev->features;
9941 
9942 		if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9943 			/* udp_tunnel_{get,drop}_rx_info both need
9944 			 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9945 			 * device, or they won't do anything.
9946 			 * Thus we need to update dev->features
9947 			 * *before* calling udp_tunnel_get_rx_info,
9948 			 * but *after* calling udp_tunnel_drop_rx_info.
9949 			 */
9950 			if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9951 				dev->features = features;
9952 				udp_tunnel_get_rx_info(dev);
9953 			} else {
9954 				udp_tunnel_drop_rx_info(dev);
9955 			}
9956 		}
9957 
9958 		if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9959 			if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9960 				dev->features = features;
9961 				err |= vlan_get_rx_ctag_filter_info(dev);
9962 			} else {
9963 				vlan_drop_rx_ctag_filter_info(dev);
9964 			}
9965 		}
9966 
9967 		if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9968 			if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9969 				dev->features = features;
9970 				err |= vlan_get_rx_stag_filter_info(dev);
9971 			} else {
9972 				vlan_drop_rx_stag_filter_info(dev);
9973 			}
9974 		}
9975 
9976 		dev->features = features;
9977 	}
9978 
9979 	return err < 0 ? 0 : 1;
9980 }
9981 
9982 /**
9983  *	netdev_update_features - recalculate device features
9984  *	@dev: the device to check
9985  *
9986  *	Recalculate dev->features set and send notifications if it
9987  *	has changed. Should be called after driver or hardware dependent
9988  *	conditions might have changed that influence the features.
9989  */
9990 void netdev_update_features(struct net_device *dev)
9991 {
9992 	if (__netdev_update_features(dev))
9993 		netdev_features_change(dev);
9994 }
9995 EXPORT_SYMBOL(netdev_update_features);
9996 
9997 /**
9998  *	netdev_change_features - recalculate device features
9999  *	@dev: the device to check
10000  *
10001  *	Recalculate dev->features set and send notifications even
10002  *	if they have not changed. Should be called instead of
10003  *	netdev_update_features() if also dev->vlan_features might
10004  *	have changed to allow the changes to be propagated to stacked
10005  *	VLAN devices.
10006  */
10007 void netdev_change_features(struct net_device *dev)
10008 {
10009 	__netdev_update_features(dev);
10010 	netdev_features_change(dev);
10011 }
10012 EXPORT_SYMBOL(netdev_change_features);
10013 
10014 /**
10015  *	netif_stacked_transfer_operstate -	transfer operstate
10016  *	@rootdev: the root or lower level device to transfer state from
10017  *	@dev: the device to transfer operstate to
10018  *
10019  *	Transfer operational state from root to device. This is normally
10020  *	called when a stacking relationship exists between the root
10021  *	device and the device(a leaf device).
10022  */
10023 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
10024 					struct net_device *dev)
10025 {
10026 	if (rootdev->operstate == IF_OPER_DORMANT)
10027 		netif_dormant_on(dev);
10028 	else
10029 		netif_dormant_off(dev);
10030 
10031 	if (rootdev->operstate == IF_OPER_TESTING)
10032 		netif_testing_on(dev);
10033 	else
10034 		netif_testing_off(dev);
10035 
10036 	if (netif_carrier_ok(rootdev))
10037 		netif_carrier_on(dev);
10038 	else
10039 		netif_carrier_off(dev);
10040 }
10041 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
10042 
10043 static int netif_alloc_rx_queues(struct net_device *dev)
10044 {
10045 	unsigned int i, count = dev->num_rx_queues;
10046 	struct netdev_rx_queue *rx;
10047 	size_t sz = count * sizeof(*rx);
10048 	int err = 0;
10049 
10050 	BUG_ON(count < 1);
10051 
10052 	rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10053 	if (!rx)
10054 		return -ENOMEM;
10055 
10056 	dev->_rx = rx;
10057 
10058 	for (i = 0; i < count; i++) {
10059 		rx[i].dev = dev;
10060 
10061 		/* XDP RX-queue setup */
10062 		err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
10063 		if (err < 0)
10064 			goto err_rxq_info;
10065 	}
10066 	return 0;
10067 
10068 err_rxq_info:
10069 	/* Rollback successful reg's and free other resources */
10070 	while (i--)
10071 		xdp_rxq_info_unreg(&rx[i].xdp_rxq);
10072 	kvfree(dev->_rx);
10073 	dev->_rx = NULL;
10074 	return err;
10075 }
10076 
10077 static void netif_free_rx_queues(struct net_device *dev)
10078 {
10079 	unsigned int i, count = dev->num_rx_queues;
10080 
10081 	/* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
10082 	if (!dev->_rx)
10083 		return;
10084 
10085 	for (i = 0; i < count; i++)
10086 		xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
10087 
10088 	kvfree(dev->_rx);
10089 }
10090 
10091 static void netdev_init_one_queue(struct net_device *dev,
10092 				  struct netdev_queue *queue, void *_unused)
10093 {
10094 	/* Initialize queue lock */
10095 	spin_lock_init(&queue->_xmit_lock);
10096 	netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
10097 	queue->xmit_lock_owner = -1;
10098 	netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
10099 	queue->dev = dev;
10100 #ifdef CONFIG_BQL
10101 	dql_init(&queue->dql, HZ);
10102 #endif
10103 }
10104 
10105 static void netif_free_tx_queues(struct net_device *dev)
10106 {
10107 	kvfree(dev->_tx);
10108 }
10109 
10110 static int netif_alloc_netdev_queues(struct net_device *dev)
10111 {
10112 	unsigned int count = dev->num_tx_queues;
10113 	struct netdev_queue *tx;
10114 	size_t sz = count * sizeof(*tx);
10115 
10116 	if (count < 1 || count > 0xffff)
10117 		return -EINVAL;
10118 
10119 	tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10120 	if (!tx)
10121 		return -ENOMEM;
10122 
10123 	dev->_tx = tx;
10124 
10125 	netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
10126 	spin_lock_init(&dev->tx_global_lock);
10127 
10128 	return 0;
10129 }
10130 
10131 void netif_tx_stop_all_queues(struct net_device *dev)
10132 {
10133 	unsigned int i;
10134 
10135 	for (i = 0; i < dev->num_tx_queues; i++) {
10136 		struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
10137 
10138 		netif_tx_stop_queue(txq);
10139 	}
10140 }
10141 EXPORT_SYMBOL(netif_tx_stop_all_queues);
10142 
10143 static int netdev_do_alloc_pcpu_stats(struct net_device *dev)
10144 {
10145 	void __percpu *v;
10146 
10147 	/* Drivers implementing ndo_get_peer_dev must support tstat
10148 	 * accounting, so that skb_do_redirect() can bump the dev's
10149 	 * RX stats upon network namespace switch.
10150 	 */
10151 	if (dev->netdev_ops->ndo_get_peer_dev &&
10152 	    dev->pcpu_stat_type != NETDEV_PCPU_STAT_TSTATS)
10153 		return -EOPNOTSUPP;
10154 
10155 	switch (dev->pcpu_stat_type) {
10156 	case NETDEV_PCPU_STAT_NONE:
10157 		return 0;
10158 	case NETDEV_PCPU_STAT_LSTATS:
10159 		v = dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats);
10160 		break;
10161 	case NETDEV_PCPU_STAT_TSTATS:
10162 		v = dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
10163 		break;
10164 	case NETDEV_PCPU_STAT_DSTATS:
10165 		v = dev->dstats = netdev_alloc_pcpu_stats(struct pcpu_dstats);
10166 		break;
10167 	default:
10168 		return -EINVAL;
10169 	}
10170 
10171 	return v ? 0 : -ENOMEM;
10172 }
10173 
10174 static void netdev_do_free_pcpu_stats(struct net_device *dev)
10175 {
10176 	switch (dev->pcpu_stat_type) {
10177 	case NETDEV_PCPU_STAT_NONE:
10178 		return;
10179 	case NETDEV_PCPU_STAT_LSTATS:
10180 		free_percpu(dev->lstats);
10181 		break;
10182 	case NETDEV_PCPU_STAT_TSTATS:
10183 		free_percpu(dev->tstats);
10184 		break;
10185 	case NETDEV_PCPU_STAT_DSTATS:
10186 		free_percpu(dev->dstats);
10187 		break;
10188 	}
10189 }
10190 
10191 /**
10192  * register_netdevice() - register a network device
10193  * @dev: device to register
10194  *
10195  * Take a prepared network device structure and make it externally accessible.
10196  * A %NETDEV_REGISTER message is sent to the netdev notifier chain.
10197  * Callers must hold the rtnl lock - you may want register_netdev()
10198  * instead of this.
10199  */
10200 int register_netdevice(struct net_device *dev)
10201 {
10202 	int ret;
10203 	struct net *net = dev_net(dev);
10204 
10205 	BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
10206 		     NETDEV_FEATURE_COUNT);
10207 	BUG_ON(dev_boot_phase);
10208 	ASSERT_RTNL();
10209 
10210 	might_sleep();
10211 
10212 	/* When net_device's are persistent, this will be fatal. */
10213 	BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
10214 	BUG_ON(!net);
10215 
10216 	ret = ethtool_check_ops(dev->ethtool_ops);
10217 	if (ret)
10218 		return ret;
10219 
10220 	spin_lock_init(&dev->addr_list_lock);
10221 	netdev_set_addr_lockdep_class(dev);
10222 
10223 	ret = dev_get_valid_name(net, dev, dev->name);
10224 	if (ret < 0)
10225 		goto out;
10226 
10227 	ret = -ENOMEM;
10228 	dev->name_node = netdev_name_node_head_alloc(dev);
10229 	if (!dev->name_node)
10230 		goto out;
10231 
10232 	/* Init, if this function is available */
10233 	if (dev->netdev_ops->ndo_init) {
10234 		ret = dev->netdev_ops->ndo_init(dev);
10235 		if (ret) {
10236 			if (ret > 0)
10237 				ret = -EIO;
10238 			goto err_free_name;
10239 		}
10240 	}
10241 
10242 	if (((dev->hw_features | dev->features) &
10243 	     NETIF_F_HW_VLAN_CTAG_FILTER) &&
10244 	    (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
10245 	     !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
10246 		netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
10247 		ret = -EINVAL;
10248 		goto err_uninit;
10249 	}
10250 
10251 	ret = netdev_do_alloc_pcpu_stats(dev);
10252 	if (ret)
10253 		goto err_uninit;
10254 
10255 	ret = dev_index_reserve(net, dev->ifindex);
10256 	if (ret < 0)
10257 		goto err_free_pcpu;
10258 	dev->ifindex = ret;
10259 
10260 	/* Transfer changeable features to wanted_features and enable
10261 	 * software offloads (GSO and GRO).
10262 	 */
10263 	dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
10264 	dev->features |= NETIF_F_SOFT_FEATURES;
10265 
10266 	if (dev->udp_tunnel_nic_info) {
10267 		dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10268 		dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10269 	}
10270 
10271 	dev->wanted_features = dev->features & dev->hw_features;
10272 
10273 	if (!(dev->flags & IFF_LOOPBACK))
10274 		dev->hw_features |= NETIF_F_NOCACHE_COPY;
10275 
10276 	/* If IPv4 TCP segmentation offload is supported we should also
10277 	 * allow the device to enable segmenting the frame with the option
10278 	 * of ignoring a static IP ID value.  This doesn't enable the
10279 	 * feature itself but allows the user to enable it later.
10280 	 */
10281 	if (dev->hw_features & NETIF_F_TSO)
10282 		dev->hw_features |= NETIF_F_TSO_MANGLEID;
10283 	if (dev->vlan_features & NETIF_F_TSO)
10284 		dev->vlan_features |= NETIF_F_TSO_MANGLEID;
10285 	if (dev->mpls_features & NETIF_F_TSO)
10286 		dev->mpls_features |= NETIF_F_TSO_MANGLEID;
10287 	if (dev->hw_enc_features & NETIF_F_TSO)
10288 		dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
10289 
10290 	/* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
10291 	 */
10292 	dev->vlan_features |= NETIF_F_HIGHDMA;
10293 
10294 	/* Make NETIF_F_SG inheritable to tunnel devices.
10295 	 */
10296 	dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
10297 
10298 	/* Make NETIF_F_SG inheritable to MPLS.
10299 	 */
10300 	dev->mpls_features |= NETIF_F_SG;
10301 
10302 	ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
10303 	ret = notifier_to_errno(ret);
10304 	if (ret)
10305 		goto err_ifindex_release;
10306 
10307 	ret = netdev_register_kobject(dev);
10308 
10309 	WRITE_ONCE(dev->reg_state, ret ? NETREG_UNREGISTERED : NETREG_REGISTERED);
10310 
10311 	if (ret)
10312 		goto err_uninit_notify;
10313 
10314 	__netdev_update_features(dev);
10315 
10316 	/*
10317 	 *	Default initial state at registry is that the
10318 	 *	device is present.
10319 	 */
10320 
10321 	set_bit(__LINK_STATE_PRESENT, &dev->state);
10322 
10323 	linkwatch_init_dev(dev);
10324 
10325 	dev_init_scheduler(dev);
10326 
10327 	netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL);
10328 	list_netdevice(dev);
10329 
10330 	add_device_randomness(dev->dev_addr, dev->addr_len);
10331 
10332 	/* If the device has permanent device address, driver should
10333 	 * set dev_addr and also addr_assign_type should be set to
10334 	 * NET_ADDR_PERM (default value).
10335 	 */
10336 	if (dev->addr_assign_type == NET_ADDR_PERM)
10337 		memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
10338 
10339 	/* Notify protocols, that a new device appeared. */
10340 	ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
10341 	ret = notifier_to_errno(ret);
10342 	if (ret) {
10343 		/* Expect explicit free_netdev() on failure */
10344 		dev->needs_free_netdev = false;
10345 		unregister_netdevice_queue(dev, NULL);
10346 		goto out;
10347 	}
10348 	/*
10349 	 *	Prevent userspace races by waiting until the network
10350 	 *	device is fully setup before sending notifications.
10351 	 */
10352 	if (!dev->rtnl_link_ops ||
10353 	    dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10354 		rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
10355 
10356 out:
10357 	return ret;
10358 
10359 err_uninit_notify:
10360 	call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
10361 err_ifindex_release:
10362 	dev_index_release(net, dev->ifindex);
10363 err_free_pcpu:
10364 	netdev_do_free_pcpu_stats(dev);
10365 err_uninit:
10366 	if (dev->netdev_ops->ndo_uninit)
10367 		dev->netdev_ops->ndo_uninit(dev);
10368 	if (dev->priv_destructor)
10369 		dev->priv_destructor(dev);
10370 err_free_name:
10371 	netdev_name_node_free(dev->name_node);
10372 	goto out;
10373 }
10374 EXPORT_SYMBOL(register_netdevice);
10375 
10376 /**
10377  *	init_dummy_netdev	- init a dummy network device for NAPI
10378  *	@dev: device to init
10379  *
10380  *	This takes a network device structure and initialize the minimum
10381  *	amount of fields so it can be used to schedule NAPI polls without
10382  *	registering a full blown interface. This is to be used by drivers
10383  *	that need to tie several hardware interfaces to a single NAPI
10384  *	poll scheduler due to HW limitations.
10385  */
10386 void init_dummy_netdev(struct net_device *dev)
10387 {
10388 	/* Clear everything. Note we don't initialize spinlocks
10389 	 * are they aren't supposed to be taken by any of the
10390 	 * NAPI code and this dummy netdev is supposed to be
10391 	 * only ever used for NAPI polls
10392 	 */
10393 	memset(dev, 0, sizeof(struct net_device));
10394 
10395 	/* make sure we BUG if trying to hit standard
10396 	 * register/unregister code path
10397 	 */
10398 	dev->reg_state = NETREG_DUMMY;
10399 
10400 	/* NAPI wants this */
10401 	INIT_LIST_HEAD(&dev->napi_list);
10402 
10403 	/* a dummy interface is started by default */
10404 	set_bit(__LINK_STATE_PRESENT, &dev->state);
10405 	set_bit(__LINK_STATE_START, &dev->state);
10406 
10407 	/* napi_busy_loop stats accounting wants this */
10408 	dev_net_set(dev, &init_net);
10409 
10410 	/* Note : We dont allocate pcpu_refcnt for dummy devices,
10411 	 * because users of this 'device' dont need to change
10412 	 * its refcount.
10413 	 */
10414 }
10415 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10416 
10417 
10418 /**
10419  *	register_netdev	- register a network device
10420  *	@dev: device to register
10421  *
10422  *	Take a completed network device structure and add it to the kernel
10423  *	interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10424  *	chain. 0 is returned on success. A negative errno code is returned
10425  *	on a failure to set up the device, or if the name is a duplicate.
10426  *
10427  *	This is a wrapper around register_netdevice that takes the rtnl semaphore
10428  *	and expands the device name if you passed a format string to
10429  *	alloc_netdev.
10430  */
10431 int register_netdev(struct net_device *dev)
10432 {
10433 	int err;
10434 
10435 	if (rtnl_lock_killable())
10436 		return -EINTR;
10437 	err = register_netdevice(dev);
10438 	rtnl_unlock();
10439 	return err;
10440 }
10441 EXPORT_SYMBOL(register_netdev);
10442 
10443 int netdev_refcnt_read(const struct net_device *dev)
10444 {
10445 #ifdef CONFIG_PCPU_DEV_REFCNT
10446 	int i, refcnt = 0;
10447 
10448 	for_each_possible_cpu(i)
10449 		refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10450 	return refcnt;
10451 #else
10452 	return refcount_read(&dev->dev_refcnt);
10453 #endif
10454 }
10455 EXPORT_SYMBOL(netdev_refcnt_read);
10456 
10457 int netdev_unregister_timeout_secs __read_mostly = 10;
10458 
10459 #define WAIT_REFS_MIN_MSECS 1
10460 #define WAIT_REFS_MAX_MSECS 250
10461 /**
10462  * netdev_wait_allrefs_any - wait until all references are gone.
10463  * @list: list of net_devices to wait on
10464  *
10465  * This is called when unregistering network devices.
10466  *
10467  * Any protocol or device that holds a reference should register
10468  * for netdevice notification, and cleanup and put back the
10469  * reference if they receive an UNREGISTER event.
10470  * We can get stuck here if buggy protocols don't correctly
10471  * call dev_put.
10472  */
10473 static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
10474 {
10475 	unsigned long rebroadcast_time, warning_time;
10476 	struct net_device *dev;
10477 	int wait = 0;
10478 
10479 	rebroadcast_time = warning_time = jiffies;
10480 
10481 	list_for_each_entry(dev, list, todo_list)
10482 		if (netdev_refcnt_read(dev) == 1)
10483 			return dev;
10484 
10485 	while (true) {
10486 		if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10487 			rtnl_lock();
10488 
10489 			/* Rebroadcast unregister notification */
10490 			list_for_each_entry(dev, list, todo_list)
10491 				call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10492 
10493 			__rtnl_unlock();
10494 			rcu_barrier();
10495 			rtnl_lock();
10496 
10497 			list_for_each_entry(dev, list, todo_list)
10498 				if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10499 					     &dev->state)) {
10500 					/* We must not have linkwatch events
10501 					 * pending on unregister. If this
10502 					 * happens, we simply run the queue
10503 					 * unscheduled, resulting in a noop
10504 					 * for this device.
10505 					 */
10506 					linkwatch_run_queue();
10507 					break;
10508 				}
10509 
10510 			__rtnl_unlock();
10511 
10512 			rebroadcast_time = jiffies;
10513 		}
10514 
10515 		if (!wait) {
10516 			rcu_barrier();
10517 			wait = WAIT_REFS_MIN_MSECS;
10518 		} else {
10519 			msleep(wait);
10520 			wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10521 		}
10522 
10523 		list_for_each_entry(dev, list, todo_list)
10524 			if (netdev_refcnt_read(dev) == 1)
10525 				return dev;
10526 
10527 		if (time_after(jiffies, warning_time +
10528 			       READ_ONCE(netdev_unregister_timeout_secs) * HZ)) {
10529 			list_for_each_entry(dev, list, todo_list) {
10530 				pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10531 					 dev->name, netdev_refcnt_read(dev));
10532 				ref_tracker_dir_print(&dev->refcnt_tracker, 10);
10533 			}
10534 
10535 			warning_time = jiffies;
10536 		}
10537 	}
10538 }
10539 
10540 /* The sequence is:
10541  *
10542  *	rtnl_lock();
10543  *	...
10544  *	register_netdevice(x1);
10545  *	register_netdevice(x2);
10546  *	...
10547  *	unregister_netdevice(y1);
10548  *	unregister_netdevice(y2);
10549  *      ...
10550  *	rtnl_unlock();
10551  *	free_netdev(y1);
10552  *	free_netdev(y2);
10553  *
10554  * We are invoked by rtnl_unlock().
10555  * This allows us to deal with problems:
10556  * 1) We can delete sysfs objects which invoke hotplug
10557  *    without deadlocking with linkwatch via keventd.
10558  * 2) Since we run with the RTNL semaphore not held, we can sleep
10559  *    safely in order to wait for the netdev refcnt to drop to zero.
10560  *
10561  * We must not return until all unregister events added during
10562  * the interval the lock was held have been completed.
10563  */
10564 void netdev_run_todo(void)
10565 {
10566 	struct net_device *dev, *tmp;
10567 	struct list_head list;
10568 	int cnt;
10569 #ifdef CONFIG_LOCKDEP
10570 	struct list_head unlink_list;
10571 
10572 	list_replace_init(&net_unlink_list, &unlink_list);
10573 
10574 	while (!list_empty(&unlink_list)) {
10575 		struct net_device *dev = list_first_entry(&unlink_list,
10576 							  struct net_device,
10577 							  unlink_list);
10578 		list_del_init(&dev->unlink_list);
10579 		dev->nested_level = dev->lower_level - 1;
10580 	}
10581 #endif
10582 
10583 	/* Snapshot list, allow later requests */
10584 	list_replace_init(&net_todo_list, &list);
10585 
10586 	__rtnl_unlock();
10587 
10588 	/* Wait for rcu callbacks to finish before next phase */
10589 	if (!list_empty(&list))
10590 		rcu_barrier();
10591 
10592 	list_for_each_entry_safe(dev, tmp, &list, todo_list) {
10593 		if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10594 			netdev_WARN(dev, "run_todo but not unregistering\n");
10595 			list_del(&dev->todo_list);
10596 			continue;
10597 		}
10598 
10599 		WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERED);
10600 		linkwatch_sync_dev(dev);
10601 	}
10602 
10603 	cnt = 0;
10604 	while (!list_empty(&list)) {
10605 		dev = netdev_wait_allrefs_any(&list);
10606 		list_del(&dev->todo_list);
10607 
10608 		/* paranoia */
10609 		BUG_ON(netdev_refcnt_read(dev) != 1);
10610 		BUG_ON(!list_empty(&dev->ptype_all));
10611 		BUG_ON(!list_empty(&dev->ptype_specific));
10612 		WARN_ON(rcu_access_pointer(dev->ip_ptr));
10613 		WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10614 
10615 		netdev_do_free_pcpu_stats(dev);
10616 		if (dev->priv_destructor)
10617 			dev->priv_destructor(dev);
10618 		if (dev->needs_free_netdev)
10619 			free_netdev(dev);
10620 
10621 		cnt++;
10622 
10623 		/* Free network device */
10624 		kobject_put(&dev->dev.kobj);
10625 	}
10626 	if (cnt && atomic_sub_and_test(cnt, &dev_unreg_count))
10627 		wake_up(&netdev_unregistering_wq);
10628 }
10629 
10630 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10631  * all the same fields in the same order as net_device_stats, with only
10632  * the type differing, but rtnl_link_stats64 may have additional fields
10633  * at the end for newer counters.
10634  */
10635 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10636 			     const struct net_device_stats *netdev_stats)
10637 {
10638 	size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t);
10639 	const atomic_long_t *src = (atomic_long_t *)netdev_stats;
10640 	u64 *dst = (u64 *)stats64;
10641 
10642 	BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10643 	for (i = 0; i < n; i++)
10644 		dst[i] = (unsigned long)atomic_long_read(&src[i]);
10645 	/* zero out counters that only exist in rtnl_link_stats64 */
10646 	memset((char *)stats64 + n * sizeof(u64), 0,
10647 	       sizeof(*stats64) - n * sizeof(u64));
10648 }
10649 EXPORT_SYMBOL(netdev_stats_to_stats64);
10650 
10651 static __cold struct net_device_core_stats __percpu *netdev_core_stats_alloc(
10652 		struct net_device *dev)
10653 {
10654 	struct net_device_core_stats __percpu *p;
10655 
10656 	p = alloc_percpu_gfp(struct net_device_core_stats,
10657 			     GFP_ATOMIC | __GFP_NOWARN);
10658 
10659 	if (p && cmpxchg(&dev->core_stats, NULL, p))
10660 		free_percpu(p);
10661 
10662 	/* This READ_ONCE() pairs with the cmpxchg() above */
10663 	return READ_ONCE(dev->core_stats);
10664 }
10665 
10666 noinline void netdev_core_stats_inc(struct net_device *dev, u32 offset)
10667 {
10668 	/* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10669 	struct net_device_core_stats __percpu *p = READ_ONCE(dev->core_stats);
10670 	unsigned long __percpu *field;
10671 
10672 	if (unlikely(!p)) {
10673 		p = netdev_core_stats_alloc(dev);
10674 		if (!p)
10675 			return;
10676 	}
10677 
10678 	field = (__force unsigned long __percpu *)((__force void *)p + offset);
10679 	this_cpu_inc(*field);
10680 }
10681 EXPORT_SYMBOL_GPL(netdev_core_stats_inc);
10682 
10683 /**
10684  *	dev_get_stats	- get network device statistics
10685  *	@dev: device to get statistics from
10686  *	@storage: place to store stats
10687  *
10688  *	Get network statistics from device. Return @storage.
10689  *	The device driver may provide its own method by setting
10690  *	dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10691  *	otherwise the internal statistics structure is used.
10692  */
10693 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10694 					struct rtnl_link_stats64 *storage)
10695 {
10696 	const struct net_device_ops *ops = dev->netdev_ops;
10697 	const struct net_device_core_stats __percpu *p;
10698 
10699 	if (ops->ndo_get_stats64) {
10700 		memset(storage, 0, sizeof(*storage));
10701 		ops->ndo_get_stats64(dev, storage);
10702 	} else if (ops->ndo_get_stats) {
10703 		netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10704 	} else {
10705 		netdev_stats_to_stats64(storage, &dev->stats);
10706 	}
10707 
10708 	/* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10709 	p = READ_ONCE(dev->core_stats);
10710 	if (p) {
10711 		const struct net_device_core_stats *core_stats;
10712 		int i;
10713 
10714 		for_each_possible_cpu(i) {
10715 			core_stats = per_cpu_ptr(p, i);
10716 			storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
10717 			storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
10718 			storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
10719 			storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped);
10720 		}
10721 	}
10722 	return storage;
10723 }
10724 EXPORT_SYMBOL(dev_get_stats);
10725 
10726 /**
10727  *	dev_fetch_sw_netstats - get per-cpu network device statistics
10728  *	@s: place to store stats
10729  *	@netstats: per-cpu network stats to read from
10730  *
10731  *	Read per-cpu network statistics and populate the related fields in @s.
10732  */
10733 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10734 			   const struct pcpu_sw_netstats __percpu *netstats)
10735 {
10736 	int cpu;
10737 
10738 	for_each_possible_cpu(cpu) {
10739 		u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
10740 		const struct pcpu_sw_netstats *stats;
10741 		unsigned int start;
10742 
10743 		stats = per_cpu_ptr(netstats, cpu);
10744 		do {
10745 			start = u64_stats_fetch_begin(&stats->syncp);
10746 			rx_packets = u64_stats_read(&stats->rx_packets);
10747 			rx_bytes   = u64_stats_read(&stats->rx_bytes);
10748 			tx_packets = u64_stats_read(&stats->tx_packets);
10749 			tx_bytes   = u64_stats_read(&stats->tx_bytes);
10750 		} while (u64_stats_fetch_retry(&stats->syncp, start));
10751 
10752 		s->rx_packets += rx_packets;
10753 		s->rx_bytes   += rx_bytes;
10754 		s->tx_packets += tx_packets;
10755 		s->tx_bytes   += tx_bytes;
10756 	}
10757 }
10758 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10759 
10760 /**
10761  *	dev_get_tstats64 - ndo_get_stats64 implementation
10762  *	@dev: device to get statistics from
10763  *	@s: place to store stats
10764  *
10765  *	Populate @s from dev->stats and dev->tstats. Can be used as
10766  *	ndo_get_stats64() callback.
10767  */
10768 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
10769 {
10770 	netdev_stats_to_stats64(s, &dev->stats);
10771 	dev_fetch_sw_netstats(s, dev->tstats);
10772 }
10773 EXPORT_SYMBOL_GPL(dev_get_tstats64);
10774 
10775 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10776 {
10777 	struct netdev_queue *queue = dev_ingress_queue(dev);
10778 
10779 #ifdef CONFIG_NET_CLS_ACT
10780 	if (queue)
10781 		return queue;
10782 	queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10783 	if (!queue)
10784 		return NULL;
10785 	netdev_init_one_queue(dev, queue, NULL);
10786 	RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10787 	RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc);
10788 	rcu_assign_pointer(dev->ingress_queue, queue);
10789 #endif
10790 	return queue;
10791 }
10792 
10793 static const struct ethtool_ops default_ethtool_ops;
10794 
10795 void netdev_set_default_ethtool_ops(struct net_device *dev,
10796 				    const struct ethtool_ops *ops)
10797 {
10798 	if (dev->ethtool_ops == &default_ethtool_ops)
10799 		dev->ethtool_ops = ops;
10800 }
10801 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10802 
10803 /**
10804  * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default
10805  * @dev: netdev to enable the IRQ coalescing on
10806  *
10807  * Sets a conservative default for SW IRQ coalescing. Users can use
10808  * sysfs attributes to override the default values.
10809  */
10810 void netdev_sw_irq_coalesce_default_on(struct net_device *dev)
10811 {
10812 	WARN_ON(dev->reg_state == NETREG_REGISTERED);
10813 
10814 	if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
10815 		dev->gro_flush_timeout = 20000;
10816 		dev->napi_defer_hard_irqs = 1;
10817 	}
10818 }
10819 EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on);
10820 
10821 void netdev_freemem(struct net_device *dev)
10822 {
10823 	char *addr = (char *)dev - dev->padded;
10824 
10825 	kvfree(addr);
10826 }
10827 
10828 /**
10829  * alloc_netdev_mqs - allocate network device
10830  * @sizeof_priv: size of private data to allocate space for
10831  * @name: device name format string
10832  * @name_assign_type: origin of device name
10833  * @setup: callback to initialize device
10834  * @txqs: the number of TX subqueues to allocate
10835  * @rxqs: the number of RX subqueues to allocate
10836  *
10837  * Allocates a struct net_device with private data area for driver use
10838  * and performs basic initialization.  Also allocates subqueue structs
10839  * for each queue on the device.
10840  */
10841 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10842 		unsigned char name_assign_type,
10843 		void (*setup)(struct net_device *),
10844 		unsigned int txqs, unsigned int rxqs)
10845 {
10846 	struct net_device *dev;
10847 	unsigned int alloc_size;
10848 	struct net_device *p;
10849 
10850 	BUG_ON(strlen(name) >= sizeof(dev->name));
10851 
10852 	if (txqs < 1) {
10853 		pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10854 		return NULL;
10855 	}
10856 
10857 	if (rxqs < 1) {
10858 		pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10859 		return NULL;
10860 	}
10861 
10862 	alloc_size = sizeof(struct net_device);
10863 	if (sizeof_priv) {
10864 		/* ensure 32-byte alignment of private area */
10865 		alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10866 		alloc_size += sizeof_priv;
10867 	}
10868 	/* ensure 32-byte alignment of whole construct */
10869 	alloc_size += NETDEV_ALIGN - 1;
10870 
10871 	p = kvzalloc(alloc_size, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10872 	if (!p)
10873 		return NULL;
10874 
10875 	dev = PTR_ALIGN(p, NETDEV_ALIGN);
10876 	dev->padded = (char *)dev - (char *)p;
10877 
10878 	ref_tracker_dir_init(&dev->refcnt_tracker, 128, name);
10879 #ifdef CONFIG_PCPU_DEV_REFCNT
10880 	dev->pcpu_refcnt = alloc_percpu(int);
10881 	if (!dev->pcpu_refcnt)
10882 		goto free_dev;
10883 	__dev_hold(dev);
10884 #else
10885 	refcount_set(&dev->dev_refcnt, 1);
10886 #endif
10887 
10888 	if (dev_addr_init(dev))
10889 		goto free_pcpu;
10890 
10891 	dev_mc_init(dev);
10892 	dev_uc_init(dev);
10893 
10894 	dev_net_set(dev, &init_net);
10895 
10896 	dev->gso_max_size = GSO_LEGACY_MAX_SIZE;
10897 	dev->xdp_zc_max_segs = 1;
10898 	dev->gso_max_segs = GSO_MAX_SEGS;
10899 	dev->gro_max_size = GRO_LEGACY_MAX_SIZE;
10900 	dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE;
10901 	dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE;
10902 	dev->tso_max_size = TSO_LEGACY_MAX_SIZE;
10903 	dev->tso_max_segs = TSO_MAX_SEGS;
10904 	dev->upper_level = 1;
10905 	dev->lower_level = 1;
10906 #ifdef CONFIG_LOCKDEP
10907 	dev->nested_level = 0;
10908 	INIT_LIST_HEAD(&dev->unlink_list);
10909 #endif
10910 
10911 	INIT_LIST_HEAD(&dev->napi_list);
10912 	INIT_LIST_HEAD(&dev->unreg_list);
10913 	INIT_LIST_HEAD(&dev->close_list);
10914 	INIT_LIST_HEAD(&dev->link_watch_list);
10915 	INIT_LIST_HEAD(&dev->adj_list.upper);
10916 	INIT_LIST_HEAD(&dev->adj_list.lower);
10917 	INIT_LIST_HEAD(&dev->ptype_all);
10918 	INIT_LIST_HEAD(&dev->ptype_specific);
10919 	INIT_LIST_HEAD(&dev->net_notifier_list);
10920 #ifdef CONFIG_NET_SCHED
10921 	hash_init(dev->qdisc_hash);
10922 #endif
10923 	dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10924 	setup(dev);
10925 
10926 	if (!dev->tx_queue_len) {
10927 		dev->priv_flags |= IFF_NO_QUEUE;
10928 		dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10929 	}
10930 
10931 	dev->num_tx_queues = txqs;
10932 	dev->real_num_tx_queues = txqs;
10933 	if (netif_alloc_netdev_queues(dev))
10934 		goto free_all;
10935 
10936 	dev->num_rx_queues = rxqs;
10937 	dev->real_num_rx_queues = rxqs;
10938 	if (netif_alloc_rx_queues(dev))
10939 		goto free_all;
10940 
10941 	strcpy(dev->name, name);
10942 	dev->name_assign_type = name_assign_type;
10943 	dev->group = INIT_NETDEV_GROUP;
10944 	if (!dev->ethtool_ops)
10945 		dev->ethtool_ops = &default_ethtool_ops;
10946 
10947 	nf_hook_netdev_init(dev);
10948 
10949 	return dev;
10950 
10951 free_all:
10952 	free_netdev(dev);
10953 	return NULL;
10954 
10955 free_pcpu:
10956 #ifdef CONFIG_PCPU_DEV_REFCNT
10957 	free_percpu(dev->pcpu_refcnt);
10958 free_dev:
10959 #endif
10960 	netdev_freemem(dev);
10961 	return NULL;
10962 }
10963 EXPORT_SYMBOL(alloc_netdev_mqs);
10964 
10965 /**
10966  * free_netdev - free network device
10967  * @dev: device
10968  *
10969  * This function does the last stage of destroying an allocated device
10970  * interface. The reference to the device object is released. If this
10971  * is the last reference then it will be freed.Must be called in process
10972  * context.
10973  */
10974 void free_netdev(struct net_device *dev)
10975 {
10976 	struct napi_struct *p, *n;
10977 
10978 	might_sleep();
10979 
10980 	/* When called immediately after register_netdevice() failed the unwind
10981 	 * handling may still be dismantling the device. Handle that case by
10982 	 * deferring the free.
10983 	 */
10984 	if (dev->reg_state == NETREG_UNREGISTERING) {
10985 		ASSERT_RTNL();
10986 		dev->needs_free_netdev = true;
10987 		return;
10988 	}
10989 
10990 	netif_free_tx_queues(dev);
10991 	netif_free_rx_queues(dev);
10992 
10993 	kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10994 
10995 	/* Flush device addresses */
10996 	dev_addr_flush(dev);
10997 
10998 	list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10999 		netif_napi_del(p);
11000 
11001 	ref_tracker_dir_exit(&dev->refcnt_tracker);
11002 #ifdef CONFIG_PCPU_DEV_REFCNT
11003 	free_percpu(dev->pcpu_refcnt);
11004 	dev->pcpu_refcnt = NULL;
11005 #endif
11006 	free_percpu(dev->core_stats);
11007 	dev->core_stats = NULL;
11008 	free_percpu(dev->xdp_bulkq);
11009 	dev->xdp_bulkq = NULL;
11010 
11011 	/*  Compatibility with error handling in drivers */
11012 	if (dev->reg_state == NETREG_UNINITIALIZED) {
11013 		netdev_freemem(dev);
11014 		return;
11015 	}
11016 
11017 	BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
11018 	WRITE_ONCE(dev->reg_state, NETREG_RELEASED);
11019 
11020 	/* will free via device release */
11021 	put_device(&dev->dev);
11022 }
11023 EXPORT_SYMBOL(free_netdev);
11024 
11025 /**
11026  *	synchronize_net -  Synchronize with packet receive processing
11027  *
11028  *	Wait for packets currently being received to be done.
11029  *	Does not block later packets from starting.
11030  */
11031 void synchronize_net(void)
11032 {
11033 	might_sleep();
11034 	if (rtnl_is_locked())
11035 		synchronize_rcu_expedited();
11036 	else
11037 		synchronize_rcu();
11038 }
11039 EXPORT_SYMBOL(synchronize_net);
11040 
11041 /**
11042  *	unregister_netdevice_queue - remove device from the kernel
11043  *	@dev: device
11044  *	@head: list
11045  *
11046  *	This function shuts down a device interface and removes it
11047  *	from the kernel tables.
11048  *	If head not NULL, device is queued to be unregistered later.
11049  *
11050  *	Callers must hold the rtnl semaphore.  You may want
11051  *	unregister_netdev() instead of this.
11052  */
11053 
11054 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
11055 {
11056 	ASSERT_RTNL();
11057 
11058 	if (head) {
11059 		list_move_tail(&dev->unreg_list, head);
11060 	} else {
11061 		LIST_HEAD(single);
11062 
11063 		list_add(&dev->unreg_list, &single);
11064 		unregister_netdevice_many(&single);
11065 	}
11066 }
11067 EXPORT_SYMBOL(unregister_netdevice_queue);
11068 
11069 void unregister_netdevice_many_notify(struct list_head *head,
11070 				      u32 portid, const struct nlmsghdr *nlh)
11071 {
11072 	struct net_device *dev, *tmp;
11073 	LIST_HEAD(close_head);
11074 	int cnt = 0;
11075 
11076 	BUG_ON(dev_boot_phase);
11077 	ASSERT_RTNL();
11078 
11079 	if (list_empty(head))
11080 		return;
11081 
11082 	list_for_each_entry_safe(dev, tmp, head, unreg_list) {
11083 		/* Some devices call without registering
11084 		 * for initialization unwind. Remove those
11085 		 * devices and proceed with the remaining.
11086 		 */
11087 		if (dev->reg_state == NETREG_UNINITIALIZED) {
11088 			pr_debug("unregister_netdevice: device %s/%p never was registered\n",
11089 				 dev->name, dev);
11090 
11091 			WARN_ON(1);
11092 			list_del(&dev->unreg_list);
11093 			continue;
11094 		}
11095 		dev->dismantle = true;
11096 		BUG_ON(dev->reg_state != NETREG_REGISTERED);
11097 	}
11098 
11099 	/* If device is running, close it first. */
11100 	list_for_each_entry(dev, head, unreg_list)
11101 		list_add_tail(&dev->close_list, &close_head);
11102 	dev_close_many(&close_head, true);
11103 
11104 	list_for_each_entry(dev, head, unreg_list) {
11105 		/* And unlink it from device chain. */
11106 		unlist_netdevice(dev);
11107 		WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERING);
11108 	}
11109 	flush_all_backlogs();
11110 
11111 	synchronize_net();
11112 
11113 	list_for_each_entry(dev, head, unreg_list) {
11114 		struct sk_buff *skb = NULL;
11115 
11116 		/* Shutdown queueing discipline. */
11117 		dev_shutdown(dev);
11118 		dev_tcx_uninstall(dev);
11119 		dev_xdp_uninstall(dev);
11120 		bpf_dev_bound_netdev_unregister(dev);
11121 
11122 		netdev_offload_xstats_disable_all(dev);
11123 
11124 		/* Notify protocols, that we are about to destroy
11125 		 * this device. They should clean all the things.
11126 		 */
11127 		call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11128 
11129 		if (!dev->rtnl_link_ops ||
11130 		    dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
11131 			skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
11132 						     GFP_KERNEL, NULL, 0,
11133 						     portid, nlh);
11134 
11135 		/*
11136 		 *	Flush the unicast and multicast chains
11137 		 */
11138 		dev_uc_flush(dev);
11139 		dev_mc_flush(dev);
11140 
11141 		netdev_name_node_alt_flush(dev);
11142 		netdev_name_node_free(dev->name_node);
11143 
11144 		call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
11145 
11146 		if (dev->netdev_ops->ndo_uninit)
11147 			dev->netdev_ops->ndo_uninit(dev);
11148 
11149 		if (skb)
11150 			rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh);
11151 
11152 		/* Notifier chain MUST detach us all upper devices. */
11153 		WARN_ON(netdev_has_any_upper_dev(dev));
11154 		WARN_ON(netdev_has_any_lower_dev(dev));
11155 
11156 		/* Remove entries from kobject tree */
11157 		netdev_unregister_kobject(dev);
11158 #ifdef CONFIG_XPS
11159 		/* Remove XPS queueing entries */
11160 		netif_reset_xps_queues_gt(dev, 0);
11161 #endif
11162 	}
11163 
11164 	synchronize_net();
11165 
11166 	list_for_each_entry(dev, head, unreg_list) {
11167 		netdev_put(dev, &dev->dev_registered_tracker);
11168 		net_set_todo(dev);
11169 		cnt++;
11170 	}
11171 	atomic_add(cnt, &dev_unreg_count);
11172 
11173 	list_del(head);
11174 }
11175 
11176 /**
11177  *	unregister_netdevice_many - unregister many devices
11178  *	@head: list of devices
11179  *
11180  *  Note: As most callers use a stack allocated list_head,
11181  *  we force a list_del() to make sure stack wont be corrupted later.
11182  */
11183 void unregister_netdevice_many(struct list_head *head)
11184 {
11185 	unregister_netdevice_many_notify(head, 0, NULL);
11186 }
11187 EXPORT_SYMBOL(unregister_netdevice_many);
11188 
11189 /**
11190  *	unregister_netdev - remove device from the kernel
11191  *	@dev: device
11192  *
11193  *	This function shuts down a device interface and removes it
11194  *	from the kernel tables.
11195  *
11196  *	This is just a wrapper for unregister_netdevice that takes
11197  *	the rtnl semaphore.  In general you want to use this and not
11198  *	unregister_netdevice.
11199  */
11200 void unregister_netdev(struct net_device *dev)
11201 {
11202 	rtnl_lock();
11203 	unregister_netdevice(dev);
11204 	rtnl_unlock();
11205 }
11206 EXPORT_SYMBOL(unregister_netdev);
11207 
11208 /**
11209  *	__dev_change_net_namespace - move device to different nethost namespace
11210  *	@dev: device
11211  *	@net: network namespace
11212  *	@pat: If not NULL name pattern to try if the current device name
11213  *	      is already taken in the destination network namespace.
11214  *	@new_ifindex: If not zero, specifies device index in the target
11215  *	              namespace.
11216  *
11217  *	This function shuts down a device interface and moves it
11218  *	to a new network namespace. On success 0 is returned, on
11219  *	a failure a netagive errno code is returned.
11220  *
11221  *	Callers must hold the rtnl semaphore.
11222  */
11223 
11224 int __dev_change_net_namespace(struct net_device *dev, struct net *net,
11225 			       const char *pat, int new_ifindex)
11226 {
11227 	struct netdev_name_node *name_node;
11228 	struct net *net_old = dev_net(dev);
11229 	char new_name[IFNAMSIZ] = {};
11230 	int err, new_nsid;
11231 
11232 	ASSERT_RTNL();
11233 
11234 	/* Don't allow namespace local devices to be moved. */
11235 	err = -EINVAL;
11236 	if (dev->features & NETIF_F_NETNS_LOCAL)
11237 		goto out;
11238 
11239 	/* Ensure the device has been registrered */
11240 	if (dev->reg_state != NETREG_REGISTERED)
11241 		goto out;
11242 
11243 	/* Get out if there is nothing todo */
11244 	err = 0;
11245 	if (net_eq(net_old, net))
11246 		goto out;
11247 
11248 	/* Pick the destination device name, and ensure
11249 	 * we can use it in the destination network namespace.
11250 	 */
11251 	err = -EEXIST;
11252 	if (netdev_name_in_use(net, dev->name)) {
11253 		/* We get here if we can't use the current device name */
11254 		if (!pat)
11255 			goto out;
11256 		err = dev_prep_valid_name(net, dev, pat, new_name, EEXIST);
11257 		if (err < 0)
11258 			goto out;
11259 	}
11260 	/* Check that none of the altnames conflicts. */
11261 	err = -EEXIST;
11262 	netdev_for_each_altname(dev, name_node)
11263 		if (netdev_name_in_use(net, name_node->name))
11264 			goto out;
11265 
11266 	/* Check that new_ifindex isn't used yet. */
11267 	if (new_ifindex) {
11268 		err = dev_index_reserve(net, new_ifindex);
11269 		if (err < 0)
11270 			goto out;
11271 	} else {
11272 		/* If there is an ifindex conflict assign a new one */
11273 		err = dev_index_reserve(net, dev->ifindex);
11274 		if (err == -EBUSY)
11275 			err = dev_index_reserve(net, 0);
11276 		if (err < 0)
11277 			goto out;
11278 		new_ifindex = err;
11279 	}
11280 
11281 	/*
11282 	 * And now a mini version of register_netdevice unregister_netdevice.
11283 	 */
11284 
11285 	/* If device is running close it first. */
11286 	dev_close(dev);
11287 
11288 	/* And unlink it from device chain */
11289 	unlist_netdevice(dev);
11290 
11291 	synchronize_net();
11292 
11293 	/* Shutdown queueing discipline. */
11294 	dev_shutdown(dev);
11295 
11296 	/* Notify protocols, that we are about to destroy
11297 	 * this device. They should clean all the things.
11298 	 *
11299 	 * Note that dev->reg_state stays at NETREG_REGISTERED.
11300 	 * This is wanted because this way 8021q and macvlan know
11301 	 * the device is just moving and can keep their slaves up.
11302 	 */
11303 	call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11304 	rcu_barrier();
11305 
11306 	new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
11307 
11308 	rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
11309 			    new_ifindex);
11310 
11311 	/*
11312 	 *	Flush the unicast and multicast chains
11313 	 */
11314 	dev_uc_flush(dev);
11315 	dev_mc_flush(dev);
11316 
11317 	/* Send a netdev-removed uevent to the old namespace */
11318 	kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
11319 	netdev_adjacent_del_links(dev);
11320 
11321 	/* Move per-net netdevice notifiers that are following the netdevice */
11322 	move_netdevice_notifiers_dev_net(dev, net);
11323 
11324 	/* Actually switch the network namespace */
11325 	dev_net_set(dev, net);
11326 	dev->ifindex = new_ifindex;
11327 
11328 	if (new_name[0]) /* Rename the netdev to prepared name */
11329 		strscpy(dev->name, new_name, IFNAMSIZ);
11330 
11331 	/* Fixup kobjects */
11332 	dev_set_uevent_suppress(&dev->dev, 1);
11333 	err = device_rename(&dev->dev, dev->name);
11334 	dev_set_uevent_suppress(&dev->dev, 0);
11335 	WARN_ON(err);
11336 
11337 	/* Send a netdev-add uevent to the new namespace */
11338 	kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
11339 	netdev_adjacent_add_links(dev);
11340 
11341 	/* Adapt owner in case owning user namespace of target network
11342 	 * namespace is different from the original one.
11343 	 */
11344 	err = netdev_change_owner(dev, net_old, net);
11345 	WARN_ON(err);
11346 
11347 	/* Add the device back in the hashes */
11348 	list_netdevice(dev);
11349 
11350 	/* Notify protocols, that a new device appeared. */
11351 	call_netdevice_notifiers(NETDEV_REGISTER, dev);
11352 
11353 	/*
11354 	 *	Prevent userspace races by waiting until the network
11355 	 *	device is fully setup before sending notifications.
11356 	 */
11357 	rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
11358 
11359 	synchronize_net();
11360 	err = 0;
11361 out:
11362 	return err;
11363 }
11364 EXPORT_SYMBOL_GPL(__dev_change_net_namespace);
11365 
11366 static int dev_cpu_dead(unsigned int oldcpu)
11367 {
11368 	struct sk_buff **list_skb;
11369 	struct sk_buff *skb;
11370 	unsigned int cpu;
11371 	struct softnet_data *sd, *oldsd, *remsd = NULL;
11372 
11373 	local_irq_disable();
11374 	cpu = smp_processor_id();
11375 	sd = &per_cpu(softnet_data, cpu);
11376 	oldsd = &per_cpu(softnet_data, oldcpu);
11377 
11378 	/* Find end of our completion_queue. */
11379 	list_skb = &sd->completion_queue;
11380 	while (*list_skb)
11381 		list_skb = &(*list_skb)->next;
11382 	/* Append completion queue from offline CPU. */
11383 	*list_skb = oldsd->completion_queue;
11384 	oldsd->completion_queue = NULL;
11385 
11386 	/* Append output queue from offline CPU. */
11387 	if (oldsd->output_queue) {
11388 		*sd->output_queue_tailp = oldsd->output_queue;
11389 		sd->output_queue_tailp = oldsd->output_queue_tailp;
11390 		oldsd->output_queue = NULL;
11391 		oldsd->output_queue_tailp = &oldsd->output_queue;
11392 	}
11393 	/* Append NAPI poll list from offline CPU, with one exception :
11394 	 * process_backlog() must be called by cpu owning percpu backlog.
11395 	 * We properly handle process_queue & input_pkt_queue later.
11396 	 */
11397 	while (!list_empty(&oldsd->poll_list)) {
11398 		struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
11399 							    struct napi_struct,
11400 							    poll_list);
11401 
11402 		list_del_init(&napi->poll_list);
11403 		if (napi->poll == process_backlog)
11404 			napi->state = 0;
11405 		else
11406 			____napi_schedule(sd, napi);
11407 	}
11408 
11409 	raise_softirq_irqoff(NET_TX_SOFTIRQ);
11410 	local_irq_enable();
11411 
11412 #ifdef CONFIG_RPS
11413 	remsd = oldsd->rps_ipi_list;
11414 	oldsd->rps_ipi_list = NULL;
11415 #endif
11416 	/* send out pending IPI's on offline CPU */
11417 	net_rps_send_ipi(remsd);
11418 
11419 	/* Process offline CPU's input_pkt_queue */
11420 	while ((skb = __skb_dequeue(&oldsd->process_queue))) {
11421 		netif_rx(skb);
11422 		input_queue_head_incr(oldsd);
11423 	}
11424 	while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
11425 		netif_rx(skb);
11426 		input_queue_head_incr(oldsd);
11427 	}
11428 
11429 	return 0;
11430 }
11431 
11432 /**
11433  *	netdev_increment_features - increment feature set by one
11434  *	@all: current feature set
11435  *	@one: new feature set
11436  *	@mask: mask feature set
11437  *
11438  *	Computes a new feature set after adding a device with feature set
11439  *	@one to the master device with current feature set @all.  Will not
11440  *	enable anything that is off in @mask. Returns the new feature set.
11441  */
11442 netdev_features_t netdev_increment_features(netdev_features_t all,
11443 	netdev_features_t one, netdev_features_t mask)
11444 {
11445 	if (mask & NETIF_F_HW_CSUM)
11446 		mask |= NETIF_F_CSUM_MASK;
11447 	mask |= NETIF_F_VLAN_CHALLENGED;
11448 
11449 	all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11450 	all &= one | ~NETIF_F_ALL_FOR_ALL;
11451 
11452 	/* If one device supports hw checksumming, set for all. */
11453 	if (all & NETIF_F_HW_CSUM)
11454 		all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11455 
11456 	return all;
11457 }
11458 EXPORT_SYMBOL(netdev_increment_features);
11459 
11460 static struct hlist_head * __net_init netdev_create_hash(void)
11461 {
11462 	int i;
11463 	struct hlist_head *hash;
11464 
11465 	hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11466 	if (hash != NULL)
11467 		for (i = 0; i < NETDEV_HASHENTRIES; i++)
11468 			INIT_HLIST_HEAD(&hash[i]);
11469 
11470 	return hash;
11471 }
11472 
11473 /* Initialize per network namespace state */
11474 static int __net_init netdev_init(struct net *net)
11475 {
11476 	BUILD_BUG_ON(GRO_HASH_BUCKETS >
11477 		     8 * sizeof_field(struct napi_struct, gro_bitmask));
11478 
11479 	INIT_LIST_HEAD(&net->dev_base_head);
11480 
11481 	net->dev_name_head = netdev_create_hash();
11482 	if (net->dev_name_head == NULL)
11483 		goto err_name;
11484 
11485 	net->dev_index_head = netdev_create_hash();
11486 	if (net->dev_index_head == NULL)
11487 		goto err_idx;
11488 
11489 	xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1);
11490 
11491 	RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11492 
11493 	return 0;
11494 
11495 err_idx:
11496 	kfree(net->dev_name_head);
11497 err_name:
11498 	return -ENOMEM;
11499 }
11500 
11501 /**
11502  *	netdev_drivername - network driver for the device
11503  *	@dev: network device
11504  *
11505  *	Determine network driver for device.
11506  */
11507 const char *netdev_drivername(const struct net_device *dev)
11508 {
11509 	const struct device_driver *driver;
11510 	const struct device *parent;
11511 	const char *empty = "";
11512 
11513 	parent = dev->dev.parent;
11514 	if (!parent)
11515 		return empty;
11516 
11517 	driver = parent->driver;
11518 	if (driver && driver->name)
11519 		return driver->name;
11520 	return empty;
11521 }
11522 
11523 static void __netdev_printk(const char *level, const struct net_device *dev,
11524 			    struct va_format *vaf)
11525 {
11526 	if (dev && dev->dev.parent) {
11527 		dev_printk_emit(level[1] - '0',
11528 				dev->dev.parent,
11529 				"%s %s %s%s: %pV",
11530 				dev_driver_string(dev->dev.parent),
11531 				dev_name(dev->dev.parent),
11532 				netdev_name(dev), netdev_reg_state(dev),
11533 				vaf);
11534 	} else if (dev) {
11535 		printk("%s%s%s: %pV",
11536 		       level, netdev_name(dev), netdev_reg_state(dev), vaf);
11537 	} else {
11538 		printk("%s(NULL net_device): %pV", level, vaf);
11539 	}
11540 }
11541 
11542 void netdev_printk(const char *level, const struct net_device *dev,
11543 		   const char *format, ...)
11544 {
11545 	struct va_format vaf;
11546 	va_list args;
11547 
11548 	va_start(args, format);
11549 
11550 	vaf.fmt = format;
11551 	vaf.va = &args;
11552 
11553 	__netdev_printk(level, dev, &vaf);
11554 
11555 	va_end(args);
11556 }
11557 EXPORT_SYMBOL(netdev_printk);
11558 
11559 #define define_netdev_printk_level(func, level)			\
11560 void func(const struct net_device *dev, const char *fmt, ...)	\
11561 {								\
11562 	struct va_format vaf;					\
11563 	va_list args;						\
11564 								\
11565 	va_start(args, fmt);					\
11566 								\
11567 	vaf.fmt = fmt;						\
11568 	vaf.va = &args;						\
11569 								\
11570 	__netdev_printk(level, dev, &vaf);			\
11571 								\
11572 	va_end(args);						\
11573 }								\
11574 EXPORT_SYMBOL(func);
11575 
11576 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11577 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11578 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11579 define_netdev_printk_level(netdev_err, KERN_ERR);
11580 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11581 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11582 define_netdev_printk_level(netdev_info, KERN_INFO);
11583 
11584 static void __net_exit netdev_exit(struct net *net)
11585 {
11586 	kfree(net->dev_name_head);
11587 	kfree(net->dev_index_head);
11588 	xa_destroy(&net->dev_by_index);
11589 	if (net != &init_net)
11590 		WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11591 }
11592 
11593 static struct pernet_operations __net_initdata netdev_net_ops = {
11594 	.init = netdev_init,
11595 	.exit = netdev_exit,
11596 };
11597 
11598 static void __net_exit default_device_exit_net(struct net *net)
11599 {
11600 	struct netdev_name_node *name_node, *tmp;
11601 	struct net_device *dev, *aux;
11602 	/*
11603 	 * Push all migratable network devices back to the
11604 	 * initial network namespace
11605 	 */
11606 	ASSERT_RTNL();
11607 	for_each_netdev_safe(net, dev, aux) {
11608 		int err;
11609 		char fb_name[IFNAMSIZ];
11610 
11611 		/* Ignore unmoveable devices (i.e. loopback) */
11612 		if (dev->features & NETIF_F_NETNS_LOCAL)
11613 			continue;
11614 
11615 		/* Leave virtual devices for the generic cleanup */
11616 		if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11617 			continue;
11618 
11619 		/* Push remaining network devices to init_net */
11620 		snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11621 		if (netdev_name_in_use(&init_net, fb_name))
11622 			snprintf(fb_name, IFNAMSIZ, "dev%%d");
11623 
11624 		netdev_for_each_altname_safe(dev, name_node, tmp)
11625 			if (netdev_name_in_use(&init_net, name_node->name))
11626 				__netdev_name_node_alt_destroy(name_node);
11627 
11628 		err = dev_change_net_namespace(dev, &init_net, fb_name);
11629 		if (err) {
11630 			pr_emerg("%s: failed to move %s to init_net: %d\n",
11631 				 __func__, dev->name, err);
11632 			BUG();
11633 		}
11634 	}
11635 }
11636 
11637 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11638 {
11639 	/* At exit all network devices most be removed from a network
11640 	 * namespace.  Do this in the reverse order of registration.
11641 	 * Do this across as many network namespaces as possible to
11642 	 * improve batching efficiency.
11643 	 */
11644 	struct net_device *dev;
11645 	struct net *net;
11646 	LIST_HEAD(dev_kill_list);
11647 
11648 	rtnl_lock();
11649 	list_for_each_entry(net, net_list, exit_list) {
11650 		default_device_exit_net(net);
11651 		cond_resched();
11652 	}
11653 
11654 	list_for_each_entry(net, net_list, exit_list) {
11655 		for_each_netdev_reverse(net, dev) {
11656 			if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11657 				dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11658 			else
11659 				unregister_netdevice_queue(dev, &dev_kill_list);
11660 		}
11661 	}
11662 	unregister_netdevice_many(&dev_kill_list);
11663 	rtnl_unlock();
11664 }
11665 
11666 static struct pernet_operations __net_initdata default_device_ops = {
11667 	.exit_batch = default_device_exit_batch,
11668 };
11669 
11670 static void __init net_dev_struct_check(void)
11671 {
11672 	/* TX read-mostly hotpath */
11673 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, priv_flags);
11674 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, netdev_ops);
11675 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, header_ops);
11676 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, _tx);
11677 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, real_num_tx_queues);
11678 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_size);
11679 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_ipv4_max_size);
11680 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_segs);
11681 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_partial_features);
11682 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, num_tc);
11683 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, mtu);
11684 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, needed_headroom);
11685 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tc_to_txq);
11686 #ifdef CONFIG_XPS
11687 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, xps_maps);
11688 #endif
11689 #ifdef CONFIG_NETFILTER_EGRESS
11690 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, nf_hooks_egress);
11691 #endif
11692 #ifdef CONFIG_NET_XGRESS
11693 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tcx_egress);
11694 #endif
11695 	CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_tx, 160);
11696 
11697 	/* TXRX read-mostly hotpath */
11698 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, lstats);
11699 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, flags);
11700 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, hard_header_len);
11701 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, features);
11702 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, ip6_ptr);
11703 	CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_txrx, 38);
11704 
11705 	/* RX read-mostly hotpath */
11706 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ptype_specific);
11707 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ifindex);
11708 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, real_num_rx_queues);
11709 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, _rx);
11710 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_flush_timeout);
11711 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, napi_defer_hard_irqs);
11712 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_max_size);
11713 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_ipv4_max_size);
11714 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler);
11715 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler_data);
11716 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, nd_net);
11717 #ifdef CONFIG_NETPOLL
11718 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, npinfo);
11719 #endif
11720 #ifdef CONFIG_NET_XGRESS
11721 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, tcx_ingress);
11722 #endif
11723 	CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_rx, 104);
11724 }
11725 
11726 /*
11727  *	Initialize the DEV module. At boot time this walks the device list and
11728  *	unhooks any devices that fail to initialise (normally hardware not
11729  *	present) and leaves us with a valid list of present and active devices.
11730  *
11731  */
11732 
11733 /* We allocate 256 pages for each CPU if PAGE_SHIFT is 12 */
11734 #define SYSTEM_PERCPU_PAGE_POOL_SIZE	((1 << 20) / PAGE_SIZE)
11735 
11736 static int net_page_pool_create(int cpuid)
11737 {
11738 #if IS_ENABLED(CONFIG_PAGE_POOL)
11739 	struct page_pool_params page_pool_params = {
11740 		.pool_size = SYSTEM_PERCPU_PAGE_POOL_SIZE,
11741 		.flags = PP_FLAG_SYSTEM_POOL,
11742 		.nid = NUMA_NO_NODE,
11743 	};
11744 	struct page_pool *pp_ptr;
11745 
11746 	pp_ptr = page_pool_create_percpu(&page_pool_params, cpuid);
11747 	if (IS_ERR(pp_ptr))
11748 		return -ENOMEM;
11749 
11750 	per_cpu(system_page_pool, cpuid) = pp_ptr;
11751 #endif
11752 	return 0;
11753 }
11754 
11755 /*
11756  *       This is called single threaded during boot, so no need
11757  *       to take the rtnl semaphore.
11758  */
11759 static int __init net_dev_init(void)
11760 {
11761 	int i, rc = -ENOMEM;
11762 
11763 	BUG_ON(!dev_boot_phase);
11764 
11765 	net_dev_struct_check();
11766 
11767 	if (dev_proc_init())
11768 		goto out;
11769 
11770 	if (netdev_kobject_init())
11771 		goto out;
11772 
11773 	INIT_LIST_HEAD(&ptype_all);
11774 	for (i = 0; i < PTYPE_HASH_SIZE; i++)
11775 		INIT_LIST_HEAD(&ptype_base[i]);
11776 
11777 	if (register_pernet_subsys(&netdev_net_ops))
11778 		goto out;
11779 
11780 	/*
11781 	 *	Initialise the packet receive queues.
11782 	 */
11783 
11784 	for_each_possible_cpu(i) {
11785 		struct work_struct *flush = per_cpu_ptr(&flush_works, i);
11786 		struct softnet_data *sd = &per_cpu(softnet_data, i);
11787 
11788 		INIT_WORK(flush, flush_backlog);
11789 
11790 		skb_queue_head_init(&sd->input_pkt_queue);
11791 		skb_queue_head_init(&sd->process_queue);
11792 #ifdef CONFIG_XFRM_OFFLOAD
11793 		skb_queue_head_init(&sd->xfrm_backlog);
11794 #endif
11795 		INIT_LIST_HEAD(&sd->poll_list);
11796 		sd->output_queue_tailp = &sd->output_queue;
11797 #ifdef CONFIG_RPS
11798 		INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
11799 		sd->cpu = i;
11800 #endif
11801 		INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd);
11802 		spin_lock_init(&sd->defer_lock);
11803 
11804 		init_gro_hash(&sd->backlog);
11805 		sd->backlog.poll = process_backlog;
11806 		sd->backlog.weight = weight_p;
11807 
11808 		if (net_page_pool_create(i))
11809 			goto out;
11810 	}
11811 
11812 	dev_boot_phase = 0;
11813 
11814 	/* The loopback device is special if any other network devices
11815 	 * is present in a network namespace the loopback device must
11816 	 * be present. Since we now dynamically allocate and free the
11817 	 * loopback device ensure this invariant is maintained by
11818 	 * keeping the loopback device as the first device on the
11819 	 * list of network devices.  Ensuring the loopback devices
11820 	 * is the first device that appears and the last network device
11821 	 * that disappears.
11822 	 */
11823 	if (register_pernet_device(&loopback_net_ops))
11824 		goto out;
11825 
11826 	if (register_pernet_device(&default_device_ops))
11827 		goto out;
11828 
11829 	open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11830 	open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11831 
11832 	rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11833 				       NULL, dev_cpu_dead);
11834 	WARN_ON(rc < 0);
11835 	rc = 0;
11836 out:
11837 	if (rc < 0) {
11838 		for_each_possible_cpu(i) {
11839 			struct page_pool *pp_ptr;
11840 
11841 			pp_ptr = per_cpu(system_page_pool, i);
11842 			if (!pp_ptr)
11843 				continue;
11844 
11845 			page_pool_destroy(pp_ptr);
11846 			per_cpu(system_page_pool, i) = NULL;
11847 		}
11848 	}
11849 
11850 	return rc;
11851 }
11852 
11853 subsys_initcall(net_dev_init);
11854