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