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