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