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