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