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