xref: /linux/net/core/dev.c (revision 2c7e4a2663a1ab5a740c59c31991579b6b865a26)
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  *	__dev_get_by_flags - find any device with given flags
1271  *	@net: the applicable net namespace
1272  *	@if_flags: IFF_* values
1273  *	@mask: bitmask of bits in if_flags to check
1274  *
1275  *	Search for any interface with the given flags. Returns NULL if a device
1276  *	is not found or a pointer to the device. Must be called inside
1277  *	rtnl_lock(), and result refcount is unchanged.
1278  */
1279 
__dev_get_by_flags(struct net * net,unsigned short if_flags,unsigned short mask)1280 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1281 				      unsigned short mask)
1282 {
1283 	struct net_device *dev, *ret;
1284 
1285 	ASSERT_RTNL();
1286 
1287 	ret = NULL;
1288 	for_each_netdev(net, dev) {
1289 		if (((dev->flags ^ if_flags) & mask) == 0) {
1290 			ret = dev;
1291 			break;
1292 		}
1293 	}
1294 	return ret;
1295 }
1296 EXPORT_SYMBOL(__dev_get_by_flags);
1297 
1298 /**
1299  *	dev_valid_name - check if name is okay for network device
1300  *	@name: name string
1301  *
1302  *	Network device names need to be valid file names to
1303  *	allow sysfs to work.  We also disallow any kind of
1304  *	whitespace.
1305  */
dev_valid_name(const char * name)1306 bool dev_valid_name(const char *name)
1307 {
1308 	if (*name == '\0')
1309 		return false;
1310 	if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1311 		return false;
1312 	if (!strcmp(name, ".") || !strcmp(name, ".."))
1313 		return false;
1314 
1315 	while (*name) {
1316 		if (*name == '/' || *name == ':' || isspace(*name))
1317 			return false;
1318 		name++;
1319 	}
1320 	return true;
1321 }
1322 EXPORT_SYMBOL(dev_valid_name);
1323 
1324 /**
1325  *	__dev_alloc_name - allocate a name for a device
1326  *	@net: network namespace to allocate the device name in
1327  *	@name: name format string
1328  *	@res: result name string
1329  *
1330  *	Passed a format string - eg "lt%d" it will try and find a suitable
1331  *	id. It scans list of devices to build up a free map, then chooses
1332  *	the first empty slot. The caller must hold the dev_base or rtnl lock
1333  *	while allocating the name and adding the device in order to avoid
1334  *	duplicates.
1335  *	Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1336  *	Returns the number of the unit assigned or a negative errno code.
1337  */
1338 
__dev_alloc_name(struct net * net,const char * name,char * res)1339 static int __dev_alloc_name(struct net *net, const char *name, char *res)
1340 {
1341 	int i = 0;
1342 	const char *p;
1343 	const int max_netdevices = 8*PAGE_SIZE;
1344 	unsigned long *inuse;
1345 	struct net_device *d;
1346 	char buf[IFNAMSIZ];
1347 
1348 	/* Verify the string as this thing may have come from the user.
1349 	 * There must be one "%d" and no other "%" characters.
1350 	 */
1351 	p = strchr(name, '%');
1352 	if (!p || p[1] != 'd' || strchr(p + 2, '%'))
1353 		return -EINVAL;
1354 
1355 	/* Use one page as a bit array of possible slots */
1356 	inuse = bitmap_zalloc(max_netdevices, GFP_ATOMIC);
1357 	if (!inuse)
1358 		return -ENOMEM;
1359 
1360 	for_each_netdev(net, d) {
1361 		struct netdev_name_node *name_node;
1362 
1363 		netdev_for_each_altname(d, name_node) {
1364 			if (!sscanf(name_node->name, name, &i))
1365 				continue;
1366 			if (i < 0 || i >= max_netdevices)
1367 				continue;
1368 
1369 			/* avoid cases where sscanf is not exact inverse of printf */
1370 			snprintf(buf, IFNAMSIZ, name, i);
1371 			if (!strncmp(buf, name_node->name, IFNAMSIZ))
1372 				__set_bit(i, inuse);
1373 		}
1374 		if (!sscanf(d->name, name, &i))
1375 			continue;
1376 		if (i < 0 || i >= max_netdevices)
1377 			continue;
1378 
1379 		/* avoid cases where sscanf is not exact inverse of printf */
1380 		snprintf(buf, IFNAMSIZ, name, i);
1381 		if (!strncmp(buf, d->name, IFNAMSIZ))
1382 			__set_bit(i, inuse);
1383 	}
1384 
1385 	i = find_first_zero_bit(inuse, max_netdevices);
1386 	bitmap_free(inuse);
1387 	if (i == max_netdevices)
1388 		return -ENFILE;
1389 
1390 	/* 'res' and 'name' could overlap, use 'buf' as an intermediate buffer */
1391 	strscpy(buf, name, IFNAMSIZ);
1392 	snprintf(res, IFNAMSIZ, buf, i);
1393 	return i;
1394 }
1395 
1396 /* 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)1397 static int dev_prep_valid_name(struct net *net, struct net_device *dev,
1398 			       const char *want_name, char *out_name,
1399 			       int dup_errno)
1400 {
1401 	if (!dev_valid_name(want_name))
1402 		return -EINVAL;
1403 
1404 	if (strchr(want_name, '%'))
1405 		return __dev_alloc_name(net, want_name, out_name);
1406 
1407 	if (netdev_name_in_use(net, want_name))
1408 		return -dup_errno;
1409 	if (out_name != want_name)
1410 		strscpy(out_name, want_name, IFNAMSIZ);
1411 	return 0;
1412 }
1413 
1414 /**
1415  *	dev_alloc_name - allocate a name for a device
1416  *	@dev: device
1417  *	@name: name format string
1418  *
1419  *	Passed a format string - eg "lt%d" it will try and find a suitable
1420  *	id. It scans list of devices to build up a free map, then chooses
1421  *	the first empty slot. The caller must hold the dev_base or rtnl lock
1422  *	while allocating the name and adding the device in order to avoid
1423  *	duplicates.
1424  *	Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1425  *	Returns the number of the unit assigned or a negative errno code.
1426  */
1427 
dev_alloc_name(struct net_device * dev,const char * name)1428 int dev_alloc_name(struct net_device *dev, const char *name)
1429 {
1430 	return dev_prep_valid_name(dev_net(dev), dev, name, dev->name, ENFILE);
1431 }
1432 EXPORT_SYMBOL(dev_alloc_name);
1433 
dev_get_valid_name(struct net * net,struct net_device * dev,const char * name)1434 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1435 			      const char *name)
1436 {
1437 	int ret;
1438 
1439 	ret = dev_prep_valid_name(net, dev, name, dev->name, EEXIST);
1440 	return ret < 0 ? ret : 0;
1441 }
1442 
netif_change_name(struct net_device * dev,const char * newname)1443 int netif_change_name(struct net_device *dev, const char *newname)
1444 {
1445 	struct net *net = dev_net(dev);
1446 	unsigned char old_assign_type;
1447 	char oldname[IFNAMSIZ];
1448 	int err = 0;
1449 	int ret;
1450 
1451 	ASSERT_RTNL_NET(net);
1452 
1453 	if (!strncmp(newname, dev->name, IFNAMSIZ))
1454 		return 0;
1455 
1456 	memcpy(oldname, dev->name, IFNAMSIZ);
1457 
1458 	write_seqlock_bh(&netdev_rename_lock);
1459 	err = dev_get_valid_name(net, dev, newname);
1460 	write_sequnlock_bh(&netdev_rename_lock);
1461 
1462 	if (err < 0)
1463 		return err;
1464 
1465 	if (oldname[0] && !strchr(oldname, '%'))
1466 		netdev_info(dev, "renamed from %s%s\n", oldname,
1467 			    dev->flags & IFF_UP ? " (while UP)" : "");
1468 
1469 	old_assign_type = dev->name_assign_type;
1470 	WRITE_ONCE(dev->name_assign_type, NET_NAME_RENAMED);
1471 
1472 rollback:
1473 	ret = device_rename(&dev->dev, dev->name);
1474 	if (ret) {
1475 		write_seqlock_bh(&netdev_rename_lock);
1476 		memcpy(dev->name, oldname, IFNAMSIZ);
1477 		write_sequnlock_bh(&netdev_rename_lock);
1478 		WRITE_ONCE(dev->name_assign_type, old_assign_type);
1479 		return ret;
1480 	}
1481 
1482 	netdev_adjacent_rename_links(dev, oldname);
1483 
1484 	netdev_name_node_del(dev->name_node);
1485 
1486 	synchronize_net();
1487 
1488 	netdev_name_node_add(net, dev->name_node);
1489 
1490 	ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1491 	ret = notifier_to_errno(ret);
1492 
1493 	if (ret) {
1494 		/* err >= 0 after dev_alloc_name() or stores the first errno */
1495 		if (err >= 0) {
1496 			err = ret;
1497 			write_seqlock_bh(&netdev_rename_lock);
1498 			memcpy(dev->name, oldname, IFNAMSIZ);
1499 			write_sequnlock_bh(&netdev_rename_lock);
1500 			memcpy(oldname, newname, IFNAMSIZ);
1501 			WRITE_ONCE(dev->name_assign_type, old_assign_type);
1502 			old_assign_type = NET_NAME_RENAMED;
1503 			goto rollback;
1504 		} else {
1505 			netdev_err(dev, "name change rollback failed: %d\n",
1506 				   ret);
1507 		}
1508 	}
1509 
1510 	return err;
1511 }
1512 
netif_set_alias(struct net_device * dev,const char * alias,size_t len)1513 int netif_set_alias(struct net_device *dev, const char *alias, size_t len)
1514 {
1515 	struct dev_ifalias *new_alias = NULL;
1516 
1517 	if (len >= IFALIASZ)
1518 		return -EINVAL;
1519 
1520 	if (len) {
1521 		new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1522 		if (!new_alias)
1523 			return -ENOMEM;
1524 
1525 		memcpy(new_alias->ifalias, alias, len);
1526 		new_alias->ifalias[len] = 0;
1527 	}
1528 
1529 	mutex_lock(&ifalias_mutex);
1530 	new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1531 					mutex_is_locked(&ifalias_mutex));
1532 	mutex_unlock(&ifalias_mutex);
1533 
1534 	if (new_alias)
1535 		kfree_rcu(new_alias, rcuhead);
1536 
1537 	return len;
1538 }
1539 
1540 /**
1541  *	dev_get_alias - get ifalias of a device
1542  *	@dev: device
1543  *	@name: buffer to store name of ifalias
1544  *	@len: size of buffer
1545  *
1546  *	get ifalias for a device.  Caller must make sure dev cannot go
1547  *	away,  e.g. rcu read lock or own a reference count to device.
1548  */
dev_get_alias(const struct net_device * dev,char * name,size_t len)1549 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1550 {
1551 	const struct dev_ifalias *alias;
1552 	int ret = 0;
1553 
1554 	rcu_read_lock();
1555 	alias = rcu_dereference(dev->ifalias);
1556 	if (alias)
1557 		ret = snprintf(name, len, "%s", alias->ifalias);
1558 	rcu_read_unlock();
1559 
1560 	return ret;
1561 }
1562 
1563 /**
1564  *	netdev_features_change - device changes features
1565  *	@dev: device to cause notification
1566  *
1567  *	Called to indicate a device has changed features.
1568  */
netdev_features_change(struct net_device * dev)1569 void netdev_features_change(struct net_device *dev)
1570 {
1571 	call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1572 }
1573 EXPORT_SYMBOL(netdev_features_change);
1574 
netif_state_change(struct net_device * dev)1575 void netif_state_change(struct net_device *dev)
1576 {
1577 	netdev_ops_assert_locked_or_invisible(dev);
1578 
1579 	if (dev->flags & IFF_UP) {
1580 		struct netdev_notifier_change_info change_info = {
1581 			.info.dev = dev,
1582 		};
1583 
1584 		call_netdevice_notifiers_info(NETDEV_CHANGE,
1585 					      &change_info.info);
1586 		rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL, 0, NULL);
1587 	}
1588 }
1589 
1590 /**
1591  * __netdev_notify_peers - notify network peers about existence of @dev,
1592  * to be called when rtnl lock is already held.
1593  * @dev: network device
1594  *
1595  * Generate traffic such that interested network peers are aware of
1596  * @dev, such as by generating a gratuitous ARP. This may be used when
1597  * a device wants to inform the rest of the network about some sort of
1598  * reconfiguration such as a failover event or virtual machine
1599  * migration.
1600  */
__netdev_notify_peers(struct net_device * dev)1601 void __netdev_notify_peers(struct net_device *dev)
1602 {
1603 	ASSERT_RTNL();
1604 	call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1605 	call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1606 }
1607 EXPORT_SYMBOL(__netdev_notify_peers);
1608 
1609 /**
1610  * netdev_notify_peers - notify network peers about existence of @dev
1611  * @dev: network device
1612  *
1613  * Generate traffic such that interested network peers are aware of
1614  * @dev, such as by generating a gratuitous ARP. This may be used when
1615  * a device wants to inform the rest of the network about some sort of
1616  * reconfiguration such as a failover event or virtual machine
1617  * migration.
1618  */
netdev_notify_peers(struct net_device * dev)1619 void netdev_notify_peers(struct net_device *dev)
1620 {
1621 	rtnl_lock();
1622 	__netdev_notify_peers(dev);
1623 	rtnl_unlock();
1624 }
1625 EXPORT_SYMBOL(netdev_notify_peers);
1626 
1627 static int napi_threaded_poll(void *data);
1628 
napi_kthread_create(struct napi_struct * n)1629 static int napi_kthread_create(struct napi_struct *n)
1630 {
1631 	int err = 0;
1632 
1633 	/* Create and wake up the kthread once to put it in
1634 	 * TASK_INTERRUPTIBLE mode to avoid the blocked task
1635 	 * warning and work with loadavg.
1636 	 */
1637 	n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d",
1638 				n->dev->name, n->napi_id);
1639 	if (IS_ERR(n->thread)) {
1640 		err = PTR_ERR(n->thread);
1641 		pr_err("kthread_run failed with err %d\n", err);
1642 		n->thread = NULL;
1643 	}
1644 
1645 	return err;
1646 }
1647 
__dev_open(struct net_device * dev,struct netlink_ext_ack * extack)1648 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1649 {
1650 	const struct net_device_ops *ops = dev->netdev_ops;
1651 	int ret;
1652 
1653 	ASSERT_RTNL();
1654 	dev_addr_check(dev);
1655 
1656 	if (!netif_device_present(dev)) {
1657 		/* may be detached because parent is runtime-suspended */
1658 		if (dev->dev.parent)
1659 			pm_runtime_resume(dev->dev.parent);
1660 		if (!netif_device_present(dev))
1661 			return -ENODEV;
1662 	}
1663 
1664 	/* Block netpoll from trying to do any rx path servicing.
1665 	 * If we don't do this there is a chance ndo_poll_controller
1666 	 * or ndo_poll may be running while we open the device
1667 	 */
1668 	netpoll_poll_disable(dev);
1669 
1670 	ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1671 	ret = notifier_to_errno(ret);
1672 	if (ret)
1673 		return ret;
1674 
1675 	set_bit(__LINK_STATE_START, &dev->state);
1676 
1677 	netdev_ops_assert_locked(dev);
1678 
1679 	if (ops->ndo_validate_addr)
1680 		ret = ops->ndo_validate_addr(dev);
1681 
1682 	if (!ret && ops->ndo_open)
1683 		ret = ops->ndo_open(dev);
1684 
1685 	netpoll_poll_enable(dev);
1686 
1687 	if (ret)
1688 		clear_bit(__LINK_STATE_START, &dev->state);
1689 	else {
1690 		netif_set_up(dev, true);
1691 		dev_set_rx_mode(dev);
1692 		dev_activate(dev);
1693 		add_device_randomness(dev->dev_addr, dev->addr_len);
1694 	}
1695 
1696 	return ret;
1697 }
1698 
netif_open(struct net_device * dev,struct netlink_ext_ack * extack)1699 int netif_open(struct net_device *dev, struct netlink_ext_ack *extack)
1700 {
1701 	int ret;
1702 
1703 	if (dev->flags & IFF_UP)
1704 		return 0;
1705 
1706 	ret = __dev_open(dev, extack);
1707 	if (ret < 0)
1708 		return ret;
1709 
1710 	rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1711 	call_netdevice_notifiers(NETDEV_UP, dev);
1712 
1713 	return ret;
1714 }
1715 
__dev_close_many(struct list_head * head)1716 static void __dev_close_many(struct list_head *head)
1717 {
1718 	struct net_device *dev;
1719 
1720 	ASSERT_RTNL();
1721 	might_sleep();
1722 
1723 	list_for_each_entry(dev, head, close_list) {
1724 		/* Temporarily disable netpoll until the interface is down */
1725 		netpoll_poll_disable(dev);
1726 
1727 		call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1728 
1729 		clear_bit(__LINK_STATE_START, &dev->state);
1730 
1731 		/* Synchronize to scheduled poll. We cannot touch poll list, it
1732 		 * can be even on different cpu. So just clear netif_running().
1733 		 *
1734 		 * dev->stop() will invoke napi_disable() on all of it's
1735 		 * napi_struct instances on this device.
1736 		 */
1737 		smp_mb__after_atomic(); /* Commit netif_running(). */
1738 	}
1739 
1740 	dev_deactivate_many(head);
1741 
1742 	list_for_each_entry(dev, head, close_list) {
1743 		const struct net_device_ops *ops = dev->netdev_ops;
1744 
1745 		/*
1746 		 *	Call the device specific close. This cannot fail.
1747 		 *	Only if device is UP
1748 		 *
1749 		 *	We allow it to be called even after a DETACH hot-plug
1750 		 *	event.
1751 		 */
1752 
1753 		netdev_ops_assert_locked(dev);
1754 
1755 		if (ops->ndo_stop)
1756 			ops->ndo_stop(dev);
1757 
1758 		netif_set_up(dev, false);
1759 		netpoll_poll_enable(dev);
1760 	}
1761 }
1762 
__dev_close(struct net_device * dev)1763 static void __dev_close(struct net_device *dev)
1764 {
1765 	LIST_HEAD(single);
1766 
1767 	list_add(&dev->close_list, &single);
1768 	__dev_close_many(&single);
1769 	list_del(&single);
1770 }
1771 
dev_close_many(struct list_head * head,bool unlink)1772 void dev_close_many(struct list_head *head, bool unlink)
1773 {
1774 	struct net_device *dev, *tmp;
1775 
1776 	/* Remove the devices that don't need to be closed */
1777 	list_for_each_entry_safe(dev, tmp, head, close_list)
1778 		if (!(dev->flags & IFF_UP))
1779 			list_del_init(&dev->close_list);
1780 
1781 	__dev_close_many(head);
1782 
1783 	list_for_each_entry_safe(dev, tmp, head, close_list) {
1784 		rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1785 		call_netdevice_notifiers(NETDEV_DOWN, dev);
1786 		if (unlink)
1787 			list_del_init(&dev->close_list);
1788 	}
1789 }
1790 EXPORT_SYMBOL(dev_close_many);
1791 
netif_close(struct net_device * dev)1792 void netif_close(struct net_device *dev)
1793 {
1794 	if (dev->flags & IFF_UP) {
1795 		LIST_HEAD(single);
1796 
1797 		list_add(&dev->close_list, &single);
1798 		dev_close_many(&single, true);
1799 		list_del(&single);
1800 	}
1801 }
1802 EXPORT_SYMBOL(netif_close);
1803 
netif_disable_lro(struct net_device * dev)1804 void netif_disable_lro(struct net_device *dev)
1805 {
1806 	struct net_device *lower_dev;
1807 	struct list_head *iter;
1808 
1809 	dev->wanted_features &= ~NETIF_F_LRO;
1810 	netdev_update_features(dev);
1811 
1812 	if (unlikely(dev->features & NETIF_F_LRO))
1813 		netdev_WARN(dev, "failed to disable LRO!\n");
1814 
1815 	netdev_for_each_lower_dev(dev, lower_dev, iter) {
1816 		netdev_lock_ops(lower_dev);
1817 		netif_disable_lro(lower_dev);
1818 		netdev_unlock_ops(lower_dev);
1819 	}
1820 }
1821 EXPORT_IPV6_MOD(netif_disable_lro);
1822 
1823 /**
1824  *	dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1825  *	@dev: device
1826  *
1827  *	Disable HW Generic Receive Offload (GRO_HW) on a net device.  Must be
1828  *	called under RTNL.  This is needed if Generic XDP is installed on
1829  *	the device.
1830  */
dev_disable_gro_hw(struct net_device * dev)1831 static void dev_disable_gro_hw(struct net_device *dev)
1832 {
1833 	dev->wanted_features &= ~NETIF_F_GRO_HW;
1834 	netdev_update_features(dev);
1835 
1836 	if (unlikely(dev->features & NETIF_F_GRO_HW))
1837 		netdev_WARN(dev, "failed to disable GRO_HW!\n");
1838 }
1839 
netdev_cmd_to_name(enum netdev_cmd cmd)1840 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1841 {
1842 #define N(val) 						\
1843 	case NETDEV_##val:				\
1844 		return "NETDEV_" __stringify(val);
1845 	switch (cmd) {
1846 	N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1847 	N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1848 	N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1849 	N(POST_INIT) N(PRE_UNINIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN)
1850 	N(CHANGEUPPER) N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA)
1851 	N(BONDING_INFO) N(PRECHANGEUPPER) N(CHANGELOWERSTATE)
1852 	N(UDP_TUNNEL_PUSH_INFO) N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1853 	N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1854 	N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1855 	N(PRE_CHANGEADDR) N(OFFLOAD_XSTATS_ENABLE) N(OFFLOAD_XSTATS_DISABLE)
1856 	N(OFFLOAD_XSTATS_REPORT_USED) N(OFFLOAD_XSTATS_REPORT_DELTA)
1857 	N(XDP_FEAT_CHANGE)
1858 	}
1859 #undef N
1860 	return "UNKNOWN_NETDEV_EVENT";
1861 }
1862 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1863 
call_netdevice_notifier(struct notifier_block * nb,unsigned long val,struct net_device * dev)1864 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1865 				   struct net_device *dev)
1866 {
1867 	struct netdev_notifier_info info = {
1868 		.dev = dev,
1869 	};
1870 
1871 	return nb->notifier_call(nb, val, &info);
1872 }
1873 
call_netdevice_register_notifiers(struct notifier_block * nb,struct net_device * dev)1874 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1875 					     struct net_device *dev)
1876 {
1877 	int err;
1878 
1879 	err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1880 	err = notifier_to_errno(err);
1881 	if (err)
1882 		return err;
1883 
1884 	if (!(dev->flags & IFF_UP))
1885 		return 0;
1886 
1887 	call_netdevice_notifier(nb, NETDEV_UP, dev);
1888 	return 0;
1889 }
1890 
call_netdevice_unregister_notifiers(struct notifier_block * nb,struct net_device * dev)1891 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1892 						struct net_device *dev)
1893 {
1894 	if (dev->flags & IFF_UP) {
1895 		call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1896 					dev);
1897 		call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1898 	}
1899 	call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1900 }
1901 
call_netdevice_register_net_notifiers(struct notifier_block * nb,struct net * net)1902 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1903 						 struct net *net)
1904 {
1905 	struct net_device *dev;
1906 	int err;
1907 
1908 	for_each_netdev(net, dev) {
1909 		netdev_lock_ops(dev);
1910 		err = call_netdevice_register_notifiers(nb, dev);
1911 		netdev_unlock_ops(dev);
1912 		if (err)
1913 			goto rollback;
1914 	}
1915 	return 0;
1916 
1917 rollback:
1918 	for_each_netdev_continue_reverse(net, dev)
1919 		call_netdevice_unregister_notifiers(nb, dev);
1920 	return err;
1921 }
1922 
call_netdevice_unregister_net_notifiers(struct notifier_block * nb,struct net * net)1923 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1924 						    struct net *net)
1925 {
1926 	struct net_device *dev;
1927 
1928 	for_each_netdev(net, dev)
1929 		call_netdevice_unregister_notifiers(nb, dev);
1930 }
1931 
1932 static int dev_boot_phase = 1;
1933 
1934 /**
1935  * register_netdevice_notifier - register a network notifier block
1936  * @nb: notifier
1937  *
1938  * Register a notifier to be called when network device events occur.
1939  * The notifier passed is linked into the kernel structures and must
1940  * not be reused until it has been unregistered. A negative errno code
1941  * is returned on a failure.
1942  *
1943  * When registered all registration and up events are replayed
1944  * to the new notifier to allow device to have a race free
1945  * view of the network device list.
1946  */
1947 
register_netdevice_notifier(struct notifier_block * nb)1948 int register_netdevice_notifier(struct notifier_block *nb)
1949 {
1950 	struct net *net;
1951 	int err;
1952 
1953 	/* Close race with setup_net() and cleanup_net() */
1954 	down_write(&pernet_ops_rwsem);
1955 
1956 	/* When RTNL is removed, we need protection for netdev_chain. */
1957 	rtnl_lock();
1958 
1959 	err = raw_notifier_chain_register(&netdev_chain, nb);
1960 	if (err)
1961 		goto unlock;
1962 	if (dev_boot_phase)
1963 		goto unlock;
1964 	for_each_net(net) {
1965 		__rtnl_net_lock(net);
1966 		err = call_netdevice_register_net_notifiers(nb, net);
1967 		__rtnl_net_unlock(net);
1968 		if (err)
1969 			goto rollback;
1970 	}
1971 
1972 unlock:
1973 	rtnl_unlock();
1974 	up_write(&pernet_ops_rwsem);
1975 	return err;
1976 
1977 rollback:
1978 	for_each_net_continue_reverse(net) {
1979 		__rtnl_net_lock(net);
1980 		call_netdevice_unregister_net_notifiers(nb, net);
1981 		__rtnl_net_unlock(net);
1982 	}
1983 
1984 	raw_notifier_chain_unregister(&netdev_chain, nb);
1985 	goto unlock;
1986 }
1987 EXPORT_SYMBOL(register_netdevice_notifier);
1988 
1989 /**
1990  * unregister_netdevice_notifier - unregister a network notifier block
1991  * @nb: notifier
1992  *
1993  * Unregister a notifier previously registered by
1994  * register_netdevice_notifier(). The notifier is unlinked into the
1995  * kernel structures and may then be reused. A negative errno code
1996  * is returned on a failure.
1997  *
1998  * After unregistering unregister and down device events are synthesized
1999  * for all devices on the device list to the removed notifier to remove
2000  * the need for special case cleanup code.
2001  */
2002 
unregister_netdevice_notifier(struct notifier_block * nb)2003 int unregister_netdevice_notifier(struct notifier_block *nb)
2004 {
2005 	struct net *net;
2006 	int err;
2007 
2008 	/* Close race with setup_net() and cleanup_net() */
2009 	down_write(&pernet_ops_rwsem);
2010 	rtnl_lock();
2011 	err = raw_notifier_chain_unregister(&netdev_chain, nb);
2012 	if (err)
2013 		goto unlock;
2014 
2015 	for_each_net(net) {
2016 		__rtnl_net_lock(net);
2017 		call_netdevice_unregister_net_notifiers(nb, net);
2018 		__rtnl_net_unlock(net);
2019 	}
2020 
2021 unlock:
2022 	rtnl_unlock();
2023 	up_write(&pernet_ops_rwsem);
2024 	return err;
2025 }
2026 EXPORT_SYMBOL(unregister_netdevice_notifier);
2027 
__register_netdevice_notifier_net(struct net * net,struct notifier_block * nb,bool ignore_call_fail)2028 static int __register_netdevice_notifier_net(struct net *net,
2029 					     struct notifier_block *nb,
2030 					     bool ignore_call_fail)
2031 {
2032 	int err;
2033 
2034 	err = raw_notifier_chain_register(&net->netdev_chain, nb);
2035 	if (err)
2036 		return err;
2037 	if (dev_boot_phase)
2038 		return 0;
2039 
2040 	err = call_netdevice_register_net_notifiers(nb, net);
2041 	if (err && !ignore_call_fail)
2042 		goto chain_unregister;
2043 
2044 	return 0;
2045 
2046 chain_unregister:
2047 	raw_notifier_chain_unregister(&net->netdev_chain, nb);
2048 	return err;
2049 }
2050 
__unregister_netdevice_notifier_net(struct net * net,struct notifier_block * nb)2051 static int __unregister_netdevice_notifier_net(struct net *net,
2052 					       struct notifier_block *nb)
2053 {
2054 	int err;
2055 
2056 	err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
2057 	if (err)
2058 		return err;
2059 
2060 	call_netdevice_unregister_net_notifiers(nb, net);
2061 	return 0;
2062 }
2063 
2064 /**
2065  * register_netdevice_notifier_net - register a per-netns network notifier block
2066  * @net: network namespace
2067  * @nb: notifier
2068  *
2069  * Register a notifier to be called when network device events occur.
2070  * The notifier passed is linked into the kernel structures and must
2071  * not be reused until it has been unregistered. A negative errno code
2072  * is returned on a failure.
2073  *
2074  * When registered all registration and up events are replayed
2075  * to the new notifier to allow device to have a race free
2076  * view of the network device list.
2077  */
2078 
register_netdevice_notifier_net(struct net * net,struct notifier_block * nb)2079 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
2080 {
2081 	int err;
2082 
2083 	rtnl_net_lock(net);
2084 	err = __register_netdevice_notifier_net(net, nb, false);
2085 	rtnl_net_unlock(net);
2086 
2087 	return err;
2088 }
2089 EXPORT_SYMBOL(register_netdevice_notifier_net);
2090 
2091 /**
2092  * unregister_netdevice_notifier_net - unregister a per-netns
2093  *                                     network notifier block
2094  * @net: network namespace
2095  * @nb: notifier
2096  *
2097  * Unregister a notifier previously registered by
2098  * register_netdevice_notifier_net(). The notifier is unlinked from the
2099  * kernel structures and may then be reused. A negative errno code
2100  * is returned on a failure.
2101  *
2102  * After unregistering unregister and down device events are synthesized
2103  * for all devices on the device list to the removed notifier to remove
2104  * the need for special case cleanup code.
2105  */
2106 
unregister_netdevice_notifier_net(struct net * net,struct notifier_block * nb)2107 int unregister_netdevice_notifier_net(struct net *net,
2108 				      struct notifier_block *nb)
2109 {
2110 	int err;
2111 
2112 	rtnl_net_lock(net);
2113 	err = __unregister_netdevice_notifier_net(net, nb);
2114 	rtnl_net_unlock(net);
2115 
2116 	return err;
2117 }
2118 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
2119 
__move_netdevice_notifier_net(struct net * src_net,struct net * dst_net,struct notifier_block * nb)2120 static void __move_netdevice_notifier_net(struct net *src_net,
2121 					  struct net *dst_net,
2122 					  struct notifier_block *nb)
2123 {
2124 	__unregister_netdevice_notifier_net(src_net, nb);
2125 	__register_netdevice_notifier_net(dst_net, nb, true);
2126 }
2127 
rtnl_net_dev_lock(struct net_device * dev)2128 static void rtnl_net_dev_lock(struct net_device *dev)
2129 {
2130 	bool again;
2131 
2132 	do {
2133 		struct net *net;
2134 
2135 		again = false;
2136 
2137 		/* netns might be being dismantled. */
2138 		rcu_read_lock();
2139 		net = dev_net_rcu(dev);
2140 		net_passive_inc(net);
2141 		rcu_read_unlock();
2142 
2143 		rtnl_net_lock(net);
2144 
2145 #ifdef CONFIG_NET_NS
2146 		/* dev might have been moved to another netns. */
2147 		if (!net_eq(net, rcu_access_pointer(dev->nd_net.net))) {
2148 			rtnl_net_unlock(net);
2149 			net_passive_dec(net);
2150 			again = true;
2151 		}
2152 #endif
2153 	} while (again);
2154 }
2155 
rtnl_net_dev_unlock(struct net_device * dev)2156 static void rtnl_net_dev_unlock(struct net_device *dev)
2157 {
2158 	struct net *net = dev_net(dev);
2159 
2160 	rtnl_net_unlock(net);
2161 	net_passive_dec(net);
2162 }
2163 
register_netdevice_notifier_dev_net(struct net_device * dev,struct notifier_block * nb,struct netdev_net_notifier * nn)2164 int register_netdevice_notifier_dev_net(struct net_device *dev,
2165 					struct notifier_block *nb,
2166 					struct netdev_net_notifier *nn)
2167 {
2168 	int err;
2169 
2170 	rtnl_net_dev_lock(dev);
2171 	err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
2172 	if (!err) {
2173 		nn->nb = nb;
2174 		list_add(&nn->list, &dev->net_notifier_list);
2175 	}
2176 	rtnl_net_dev_unlock(dev);
2177 
2178 	return err;
2179 }
2180 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
2181 
unregister_netdevice_notifier_dev_net(struct net_device * dev,struct notifier_block * nb,struct netdev_net_notifier * nn)2182 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
2183 					  struct notifier_block *nb,
2184 					  struct netdev_net_notifier *nn)
2185 {
2186 	int err;
2187 
2188 	rtnl_net_dev_lock(dev);
2189 	list_del(&nn->list);
2190 	err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
2191 	rtnl_net_dev_unlock(dev);
2192 
2193 	return err;
2194 }
2195 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
2196 
move_netdevice_notifiers_dev_net(struct net_device * dev,struct net * net)2197 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
2198 					     struct net *net)
2199 {
2200 	struct netdev_net_notifier *nn;
2201 
2202 	list_for_each_entry(nn, &dev->net_notifier_list, list)
2203 		__move_netdevice_notifier_net(dev_net(dev), net, nn->nb);
2204 }
2205 
2206 /**
2207  *	call_netdevice_notifiers_info - call all network notifier blocks
2208  *	@val: value passed unmodified to notifier function
2209  *	@info: notifier information data
2210  *
2211  *	Call all network notifier blocks.  Parameters and return value
2212  *	are as for raw_notifier_call_chain().
2213  */
2214 
call_netdevice_notifiers_info(unsigned long val,struct netdev_notifier_info * info)2215 int call_netdevice_notifiers_info(unsigned long val,
2216 				  struct netdev_notifier_info *info)
2217 {
2218 	struct net *net = dev_net(info->dev);
2219 	int ret;
2220 
2221 	ASSERT_RTNL();
2222 
2223 	/* Run per-netns notifier block chain first, then run the global one.
2224 	 * Hopefully, one day, the global one is going to be removed after
2225 	 * all notifier block registrators get converted to be per-netns.
2226 	 */
2227 	ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
2228 	if (ret & NOTIFY_STOP_MASK)
2229 		return ret;
2230 	return raw_notifier_call_chain(&netdev_chain, val, info);
2231 }
2232 
2233 /**
2234  *	call_netdevice_notifiers_info_robust - call per-netns notifier blocks
2235  *	                                       for and rollback on error
2236  *	@val_up: value passed unmodified to notifier function
2237  *	@val_down: value passed unmodified to the notifier function when
2238  *	           recovering from an error on @val_up
2239  *	@info: notifier information data
2240  *
2241  *	Call all per-netns network notifier blocks, but not notifier blocks on
2242  *	the global notifier chain. Parameters and return value are as for
2243  *	raw_notifier_call_chain_robust().
2244  */
2245 
2246 static int
call_netdevice_notifiers_info_robust(unsigned long val_up,unsigned long val_down,struct netdev_notifier_info * info)2247 call_netdevice_notifiers_info_robust(unsigned long val_up,
2248 				     unsigned long val_down,
2249 				     struct netdev_notifier_info *info)
2250 {
2251 	struct net *net = dev_net(info->dev);
2252 
2253 	ASSERT_RTNL();
2254 
2255 	return raw_notifier_call_chain_robust(&net->netdev_chain,
2256 					      val_up, val_down, info);
2257 }
2258 
call_netdevice_notifiers_extack(unsigned long val,struct net_device * dev,struct netlink_ext_ack * extack)2259 static int call_netdevice_notifiers_extack(unsigned long val,
2260 					   struct net_device *dev,
2261 					   struct netlink_ext_ack *extack)
2262 {
2263 	struct netdev_notifier_info info = {
2264 		.dev = dev,
2265 		.extack = extack,
2266 	};
2267 
2268 	return call_netdevice_notifiers_info(val, &info);
2269 }
2270 
2271 /**
2272  *	call_netdevice_notifiers - call all network notifier blocks
2273  *      @val: value passed unmodified to notifier function
2274  *      @dev: net_device pointer passed unmodified to notifier function
2275  *
2276  *	Call all network notifier blocks.  Parameters and return value
2277  *	are as for raw_notifier_call_chain().
2278  */
2279 
call_netdevice_notifiers(unsigned long val,struct net_device * dev)2280 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
2281 {
2282 	return call_netdevice_notifiers_extack(val, dev, NULL);
2283 }
2284 EXPORT_SYMBOL(call_netdevice_notifiers);
2285 
2286 /**
2287  *	call_netdevice_notifiers_mtu - call all network notifier blocks
2288  *	@val: value passed unmodified to notifier function
2289  *	@dev: net_device pointer passed unmodified to notifier function
2290  *	@arg: additional u32 argument passed to the notifier function
2291  *
2292  *	Call all network notifier blocks.  Parameters and return value
2293  *	are as for raw_notifier_call_chain().
2294  */
call_netdevice_notifiers_mtu(unsigned long val,struct net_device * dev,u32 arg)2295 static int call_netdevice_notifiers_mtu(unsigned long val,
2296 					struct net_device *dev, u32 arg)
2297 {
2298 	struct netdev_notifier_info_ext info = {
2299 		.info.dev = dev,
2300 		.ext.mtu = arg,
2301 	};
2302 
2303 	BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2304 
2305 	return call_netdevice_notifiers_info(val, &info.info);
2306 }
2307 
2308 #ifdef CONFIG_NET_INGRESS
2309 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2310 
net_inc_ingress_queue(void)2311 void net_inc_ingress_queue(void)
2312 {
2313 	static_branch_inc(&ingress_needed_key);
2314 }
2315 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2316 
net_dec_ingress_queue(void)2317 void net_dec_ingress_queue(void)
2318 {
2319 	static_branch_dec(&ingress_needed_key);
2320 }
2321 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2322 #endif
2323 
2324 #ifdef CONFIG_NET_EGRESS
2325 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2326 
net_inc_egress_queue(void)2327 void net_inc_egress_queue(void)
2328 {
2329 	static_branch_inc(&egress_needed_key);
2330 }
2331 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2332 
net_dec_egress_queue(void)2333 void net_dec_egress_queue(void)
2334 {
2335 	static_branch_dec(&egress_needed_key);
2336 }
2337 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2338 #endif
2339 
2340 #ifdef CONFIG_NET_CLS_ACT
2341 DEFINE_STATIC_KEY_FALSE(tcf_sw_enabled_key);
2342 EXPORT_SYMBOL(tcf_sw_enabled_key);
2343 #endif
2344 
2345 DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2346 EXPORT_SYMBOL(netstamp_needed_key);
2347 #ifdef CONFIG_JUMP_LABEL
2348 static atomic_t netstamp_needed_deferred;
2349 static atomic_t netstamp_wanted;
netstamp_clear(struct work_struct * work)2350 static void netstamp_clear(struct work_struct *work)
2351 {
2352 	int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2353 	int wanted;
2354 
2355 	wanted = atomic_add_return(deferred, &netstamp_wanted);
2356 	if (wanted > 0)
2357 		static_branch_enable(&netstamp_needed_key);
2358 	else
2359 		static_branch_disable(&netstamp_needed_key);
2360 }
2361 static DECLARE_WORK(netstamp_work, netstamp_clear);
2362 #endif
2363 
net_enable_timestamp(void)2364 void net_enable_timestamp(void)
2365 {
2366 #ifdef CONFIG_JUMP_LABEL
2367 	int wanted = atomic_read(&netstamp_wanted);
2368 
2369 	while (wanted > 0) {
2370 		if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted + 1))
2371 			return;
2372 	}
2373 	atomic_inc(&netstamp_needed_deferred);
2374 	schedule_work(&netstamp_work);
2375 #else
2376 	static_branch_inc(&netstamp_needed_key);
2377 #endif
2378 }
2379 EXPORT_SYMBOL(net_enable_timestamp);
2380 
net_disable_timestamp(void)2381 void net_disable_timestamp(void)
2382 {
2383 #ifdef CONFIG_JUMP_LABEL
2384 	int wanted = atomic_read(&netstamp_wanted);
2385 
2386 	while (wanted > 1) {
2387 		if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted - 1))
2388 			return;
2389 	}
2390 	atomic_dec(&netstamp_needed_deferred);
2391 	schedule_work(&netstamp_work);
2392 #else
2393 	static_branch_dec(&netstamp_needed_key);
2394 #endif
2395 }
2396 EXPORT_SYMBOL(net_disable_timestamp);
2397 
net_timestamp_set(struct sk_buff * skb)2398 static inline void net_timestamp_set(struct sk_buff *skb)
2399 {
2400 	skb->tstamp = 0;
2401 	skb->tstamp_type = SKB_CLOCK_REALTIME;
2402 	if (static_branch_unlikely(&netstamp_needed_key))
2403 		skb->tstamp = ktime_get_real();
2404 }
2405 
2406 #define net_timestamp_check(COND, SKB)				\
2407 	if (static_branch_unlikely(&netstamp_needed_key)) {	\
2408 		if ((COND) && !(SKB)->tstamp)			\
2409 			(SKB)->tstamp = ktime_get_real();	\
2410 	}							\
2411 
is_skb_forwardable(const struct net_device * dev,const struct sk_buff * skb)2412 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2413 {
2414 	return __is_skb_forwardable(dev, skb, true);
2415 }
2416 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2417 
__dev_forward_skb2(struct net_device * dev,struct sk_buff * skb,bool check_mtu)2418 static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb,
2419 			      bool check_mtu)
2420 {
2421 	int ret = ____dev_forward_skb(dev, skb, check_mtu);
2422 
2423 	if (likely(!ret)) {
2424 		skb->protocol = eth_type_trans(skb, dev);
2425 		skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2426 	}
2427 
2428 	return ret;
2429 }
2430 
__dev_forward_skb(struct net_device * dev,struct sk_buff * skb)2431 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2432 {
2433 	return __dev_forward_skb2(dev, skb, true);
2434 }
2435 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2436 
2437 /**
2438  * dev_forward_skb - loopback an skb to another netif
2439  *
2440  * @dev: destination network device
2441  * @skb: buffer to forward
2442  *
2443  * return values:
2444  *	NET_RX_SUCCESS	(no congestion)
2445  *	NET_RX_DROP     (packet was dropped, but freed)
2446  *
2447  * dev_forward_skb can be used for injecting an skb from the
2448  * start_xmit function of one device into the receive queue
2449  * of another device.
2450  *
2451  * The receiving device may be in another namespace, so
2452  * we have to clear all information in the skb that could
2453  * impact namespace isolation.
2454  */
dev_forward_skb(struct net_device * dev,struct sk_buff * skb)2455 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2456 {
2457 	return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2458 }
2459 EXPORT_SYMBOL_GPL(dev_forward_skb);
2460 
dev_forward_skb_nomtu(struct net_device * dev,struct sk_buff * skb)2461 int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb)
2462 {
2463 	return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb);
2464 }
2465 
deliver_skb(struct sk_buff * skb,struct packet_type * pt_prev,struct net_device * orig_dev)2466 static inline int deliver_skb(struct sk_buff *skb,
2467 			      struct packet_type *pt_prev,
2468 			      struct net_device *orig_dev)
2469 {
2470 	if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2471 		return -ENOMEM;
2472 	refcount_inc(&skb->users);
2473 	return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2474 }
2475 
deliver_ptype_list_skb(struct sk_buff * skb,struct packet_type ** pt,struct net_device * orig_dev,__be16 type,struct list_head * ptype_list)2476 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2477 					  struct packet_type **pt,
2478 					  struct net_device *orig_dev,
2479 					  __be16 type,
2480 					  struct list_head *ptype_list)
2481 {
2482 	struct packet_type *ptype, *pt_prev = *pt;
2483 
2484 	list_for_each_entry_rcu(ptype, ptype_list, list) {
2485 		if (ptype->type != type)
2486 			continue;
2487 		if (pt_prev)
2488 			deliver_skb(skb, pt_prev, orig_dev);
2489 		pt_prev = ptype;
2490 	}
2491 	*pt = pt_prev;
2492 }
2493 
skb_loop_sk(struct packet_type * ptype,struct sk_buff * skb)2494 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2495 {
2496 	if (!ptype->af_packet_priv || !skb->sk)
2497 		return false;
2498 
2499 	if (ptype->id_match)
2500 		return ptype->id_match(ptype, skb->sk);
2501 	else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2502 		return true;
2503 
2504 	return false;
2505 }
2506 
2507 /**
2508  * dev_nit_active_rcu - return true if any network interface taps are in use
2509  *
2510  * The caller must hold the RCU lock
2511  *
2512  * @dev: network device to check for the presence of taps
2513  */
dev_nit_active_rcu(const struct net_device * dev)2514 bool dev_nit_active_rcu(const struct net_device *dev)
2515 {
2516 	/* Callers may hold either RCU or RCU BH lock */
2517 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
2518 
2519 	return !list_empty(&dev_net(dev)->ptype_all) ||
2520 	       !list_empty(&dev->ptype_all);
2521 }
2522 EXPORT_SYMBOL_GPL(dev_nit_active_rcu);
2523 
2524 /*
2525  *	Support routine. Sends outgoing frames to any network
2526  *	taps currently in use.
2527  */
2528 
dev_queue_xmit_nit(struct sk_buff * skb,struct net_device * dev)2529 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2530 {
2531 	struct packet_type *ptype, *pt_prev = NULL;
2532 	struct list_head *ptype_list;
2533 	struct sk_buff *skb2 = NULL;
2534 
2535 	rcu_read_lock();
2536 	ptype_list = &dev_net_rcu(dev)->ptype_all;
2537 again:
2538 	list_for_each_entry_rcu(ptype, ptype_list, list) {
2539 		if (READ_ONCE(ptype->ignore_outgoing))
2540 			continue;
2541 
2542 		/* Never send packets back to the socket
2543 		 * they originated from - MvS (miquels@drinkel.ow.org)
2544 		 */
2545 		if (skb_loop_sk(ptype, skb))
2546 			continue;
2547 
2548 		if (pt_prev) {
2549 			deliver_skb(skb2, pt_prev, skb->dev);
2550 			pt_prev = ptype;
2551 			continue;
2552 		}
2553 
2554 		/* need to clone skb, done only once */
2555 		skb2 = skb_clone(skb, GFP_ATOMIC);
2556 		if (!skb2)
2557 			goto out_unlock;
2558 
2559 		net_timestamp_set(skb2);
2560 
2561 		/* skb->nh should be correctly
2562 		 * set by sender, so that the second statement is
2563 		 * just protection against buggy protocols.
2564 		 */
2565 		skb_reset_mac_header(skb2);
2566 
2567 		if (skb_network_header(skb2) < skb2->data ||
2568 		    skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2569 			net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2570 					     ntohs(skb2->protocol),
2571 					     dev->name);
2572 			skb_reset_network_header(skb2);
2573 		}
2574 
2575 		skb2->transport_header = skb2->network_header;
2576 		skb2->pkt_type = PACKET_OUTGOING;
2577 		pt_prev = ptype;
2578 	}
2579 
2580 	if (ptype_list != &dev->ptype_all) {
2581 		ptype_list = &dev->ptype_all;
2582 		goto again;
2583 	}
2584 out_unlock:
2585 	if (pt_prev) {
2586 		if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2587 			pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2588 		else
2589 			kfree_skb(skb2);
2590 	}
2591 	rcu_read_unlock();
2592 }
2593 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2594 
2595 /**
2596  * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2597  * @dev: Network device
2598  * @txq: number of queues available
2599  *
2600  * If real_num_tx_queues is changed the tc mappings may no longer be
2601  * valid. To resolve this verify the tc mapping remains valid and if
2602  * not NULL the mapping. With no priorities mapping to this
2603  * offset/count pair it will no longer be used. In the worst case TC0
2604  * is invalid nothing can be done so disable priority mappings. If is
2605  * expected that drivers will fix this mapping if they can before
2606  * calling netif_set_real_num_tx_queues.
2607  */
netif_setup_tc(struct net_device * dev,unsigned int txq)2608 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2609 {
2610 	int i;
2611 	struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2612 
2613 	/* If TC0 is invalidated disable TC mapping */
2614 	if (tc->offset + tc->count > txq) {
2615 		netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2616 		dev->num_tc = 0;
2617 		return;
2618 	}
2619 
2620 	/* Invalidated prio to tc mappings set to TC0 */
2621 	for (i = 1; i < TC_BITMASK + 1; i++) {
2622 		int q = netdev_get_prio_tc_map(dev, i);
2623 
2624 		tc = &dev->tc_to_txq[q];
2625 		if (tc->offset + tc->count > txq) {
2626 			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",
2627 				    i, q);
2628 			netdev_set_prio_tc_map(dev, i, 0);
2629 		}
2630 	}
2631 }
2632 
netdev_txq_to_tc(struct net_device * dev,unsigned int txq)2633 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2634 {
2635 	if (dev->num_tc) {
2636 		struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2637 		int i;
2638 
2639 		/* walk through the TCs and see if it falls into any of them */
2640 		for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2641 			if ((txq - tc->offset) < tc->count)
2642 				return i;
2643 		}
2644 
2645 		/* didn't find it, just return -1 to indicate no match */
2646 		return -1;
2647 	}
2648 
2649 	return 0;
2650 }
2651 EXPORT_SYMBOL(netdev_txq_to_tc);
2652 
2653 #ifdef CONFIG_XPS
2654 static struct static_key xps_needed __read_mostly;
2655 static struct static_key xps_rxqs_needed __read_mostly;
2656 static DEFINE_MUTEX(xps_map_mutex);
2657 #define xmap_dereference(P)		\
2658 	rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2659 
remove_xps_queue(struct xps_dev_maps * dev_maps,struct xps_dev_maps * old_maps,int tci,u16 index)2660 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2661 			     struct xps_dev_maps *old_maps, int tci, u16 index)
2662 {
2663 	struct xps_map *map = NULL;
2664 	int pos;
2665 
2666 	map = xmap_dereference(dev_maps->attr_map[tci]);
2667 	if (!map)
2668 		return false;
2669 
2670 	for (pos = map->len; pos--;) {
2671 		if (map->queues[pos] != index)
2672 			continue;
2673 
2674 		if (map->len > 1) {
2675 			map->queues[pos] = map->queues[--map->len];
2676 			break;
2677 		}
2678 
2679 		if (old_maps)
2680 			RCU_INIT_POINTER(old_maps->attr_map[tci], NULL);
2681 		RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2682 		kfree_rcu(map, rcu);
2683 		return false;
2684 	}
2685 
2686 	return true;
2687 }
2688 
remove_xps_queue_cpu(struct net_device * dev,struct xps_dev_maps * dev_maps,int cpu,u16 offset,u16 count)2689 static bool remove_xps_queue_cpu(struct net_device *dev,
2690 				 struct xps_dev_maps *dev_maps,
2691 				 int cpu, u16 offset, u16 count)
2692 {
2693 	int num_tc = dev_maps->num_tc;
2694 	bool active = false;
2695 	int tci;
2696 
2697 	for (tci = cpu * num_tc; num_tc--; tci++) {
2698 		int i, j;
2699 
2700 		for (i = count, j = offset; i--; j++) {
2701 			if (!remove_xps_queue(dev_maps, NULL, tci, j))
2702 				break;
2703 		}
2704 
2705 		active |= i < 0;
2706 	}
2707 
2708 	return active;
2709 }
2710 
reset_xps_maps(struct net_device * dev,struct xps_dev_maps * dev_maps,enum xps_map_type type)2711 static void reset_xps_maps(struct net_device *dev,
2712 			   struct xps_dev_maps *dev_maps,
2713 			   enum xps_map_type type)
2714 {
2715 	static_key_slow_dec_cpuslocked(&xps_needed);
2716 	if (type == XPS_RXQS)
2717 		static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2718 
2719 	RCU_INIT_POINTER(dev->xps_maps[type], NULL);
2720 
2721 	kfree_rcu(dev_maps, rcu);
2722 }
2723 
clean_xps_maps(struct net_device * dev,enum xps_map_type type,u16 offset,u16 count)2724 static void clean_xps_maps(struct net_device *dev, enum xps_map_type type,
2725 			   u16 offset, u16 count)
2726 {
2727 	struct xps_dev_maps *dev_maps;
2728 	bool active = false;
2729 	int i, j;
2730 
2731 	dev_maps = xmap_dereference(dev->xps_maps[type]);
2732 	if (!dev_maps)
2733 		return;
2734 
2735 	for (j = 0; j < dev_maps->nr_ids; j++)
2736 		active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count);
2737 	if (!active)
2738 		reset_xps_maps(dev, dev_maps, type);
2739 
2740 	if (type == XPS_CPUS) {
2741 		for (i = offset + (count - 1); count--; i--)
2742 			netdev_queue_numa_node_write(
2743 				netdev_get_tx_queue(dev, i), NUMA_NO_NODE);
2744 	}
2745 }
2746 
netif_reset_xps_queues(struct net_device * dev,u16 offset,u16 count)2747 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2748 				   u16 count)
2749 {
2750 	if (!static_key_false(&xps_needed))
2751 		return;
2752 
2753 	cpus_read_lock();
2754 	mutex_lock(&xps_map_mutex);
2755 
2756 	if (static_key_false(&xps_rxqs_needed))
2757 		clean_xps_maps(dev, XPS_RXQS, offset, count);
2758 
2759 	clean_xps_maps(dev, XPS_CPUS, offset, count);
2760 
2761 	mutex_unlock(&xps_map_mutex);
2762 	cpus_read_unlock();
2763 }
2764 
netif_reset_xps_queues_gt(struct net_device * dev,u16 index)2765 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2766 {
2767 	netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2768 }
2769 
expand_xps_map(struct xps_map * map,int attr_index,u16 index,bool is_rxqs_map)2770 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2771 				      u16 index, bool is_rxqs_map)
2772 {
2773 	struct xps_map *new_map;
2774 	int alloc_len = XPS_MIN_MAP_ALLOC;
2775 	int i, pos;
2776 
2777 	for (pos = 0; map && pos < map->len; pos++) {
2778 		if (map->queues[pos] != index)
2779 			continue;
2780 		return map;
2781 	}
2782 
2783 	/* Need to add tx-queue to this CPU's/rx-queue's existing map */
2784 	if (map) {
2785 		if (pos < map->alloc_len)
2786 			return map;
2787 
2788 		alloc_len = map->alloc_len * 2;
2789 	}
2790 
2791 	/* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2792 	 *  map
2793 	 */
2794 	if (is_rxqs_map)
2795 		new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2796 	else
2797 		new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2798 				       cpu_to_node(attr_index));
2799 	if (!new_map)
2800 		return NULL;
2801 
2802 	for (i = 0; i < pos; i++)
2803 		new_map->queues[i] = map->queues[i];
2804 	new_map->alloc_len = alloc_len;
2805 	new_map->len = pos;
2806 
2807 	return new_map;
2808 }
2809 
2810 /* 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)2811 static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps,
2812 			      struct xps_dev_maps *new_dev_maps, int index,
2813 			      int tc, bool skip_tc)
2814 {
2815 	int i, tci = index * dev_maps->num_tc;
2816 	struct xps_map *map;
2817 
2818 	/* copy maps belonging to foreign traffic classes */
2819 	for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2820 		if (i == tc && skip_tc)
2821 			continue;
2822 
2823 		/* fill in the new device map from the old device map */
2824 		map = xmap_dereference(dev_maps->attr_map[tci]);
2825 		RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2826 	}
2827 }
2828 
2829 /* 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)2830 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2831 			  u16 index, enum xps_map_type type)
2832 {
2833 	struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL;
2834 	const unsigned long *online_mask = NULL;
2835 	bool active = false, copy = false;
2836 	int i, j, tci, numa_node_id = -2;
2837 	int maps_sz, num_tc = 1, tc = 0;
2838 	struct xps_map *map, *new_map;
2839 	unsigned int nr_ids;
2840 
2841 	WARN_ON_ONCE(index >= dev->num_tx_queues);
2842 
2843 	if (dev->num_tc) {
2844 		/* Do not allow XPS on subordinate device directly */
2845 		num_tc = dev->num_tc;
2846 		if (num_tc < 0)
2847 			return -EINVAL;
2848 
2849 		/* If queue belongs to subordinate dev use its map */
2850 		dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2851 
2852 		tc = netdev_txq_to_tc(dev, index);
2853 		if (tc < 0)
2854 			return -EINVAL;
2855 	}
2856 
2857 	mutex_lock(&xps_map_mutex);
2858 
2859 	dev_maps = xmap_dereference(dev->xps_maps[type]);
2860 	if (type == XPS_RXQS) {
2861 		maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2862 		nr_ids = dev->num_rx_queues;
2863 	} else {
2864 		maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2865 		if (num_possible_cpus() > 1)
2866 			online_mask = cpumask_bits(cpu_online_mask);
2867 		nr_ids = nr_cpu_ids;
2868 	}
2869 
2870 	if (maps_sz < L1_CACHE_BYTES)
2871 		maps_sz = L1_CACHE_BYTES;
2872 
2873 	/* The old dev_maps could be larger or smaller than the one we're
2874 	 * setting up now, as dev->num_tc or nr_ids could have been updated in
2875 	 * between. We could try to be smart, but let's be safe instead and only
2876 	 * copy foreign traffic classes if the two map sizes match.
2877 	 */
2878 	if (dev_maps &&
2879 	    dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids)
2880 		copy = true;
2881 
2882 	/* allocate memory for queue storage */
2883 	for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2884 	     j < nr_ids;) {
2885 		if (!new_dev_maps) {
2886 			new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2887 			if (!new_dev_maps) {
2888 				mutex_unlock(&xps_map_mutex);
2889 				return -ENOMEM;
2890 			}
2891 
2892 			new_dev_maps->nr_ids = nr_ids;
2893 			new_dev_maps->num_tc = num_tc;
2894 		}
2895 
2896 		tci = j * num_tc + tc;
2897 		map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL;
2898 
2899 		map = expand_xps_map(map, j, index, type == XPS_RXQS);
2900 		if (!map)
2901 			goto error;
2902 
2903 		RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2904 	}
2905 
2906 	if (!new_dev_maps)
2907 		goto out_no_new_maps;
2908 
2909 	if (!dev_maps) {
2910 		/* Increment static keys at most once per type */
2911 		static_key_slow_inc_cpuslocked(&xps_needed);
2912 		if (type == XPS_RXQS)
2913 			static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2914 	}
2915 
2916 	for (j = 0; j < nr_ids; j++) {
2917 		bool skip_tc = false;
2918 
2919 		tci = j * num_tc + tc;
2920 		if (netif_attr_test_mask(j, mask, nr_ids) &&
2921 		    netif_attr_test_online(j, online_mask, nr_ids)) {
2922 			/* add tx-queue to CPU/rx-queue maps */
2923 			int pos = 0;
2924 
2925 			skip_tc = true;
2926 
2927 			map = xmap_dereference(new_dev_maps->attr_map[tci]);
2928 			while ((pos < map->len) && (map->queues[pos] != index))
2929 				pos++;
2930 
2931 			if (pos == map->len)
2932 				map->queues[map->len++] = index;
2933 #ifdef CONFIG_NUMA
2934 			if (type == XPS_CPUS) {
2935 				if (numa_node_id == -2)
2936 					numa_node_id = cpu_to_node(j);
2937 				else if (numa_node_id != cpu_to_node(j))
2938 					numa_node_id = -1;
2939 			}
2940 #endif
2941 		}
2942 
2943 		if (copy)
2944 			xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc,
2945 					  skip_tc);
2946 	}
2947 
2948 	rcu_assign_pointer(dev->xps_maps[type], new_dev_maps);
2949 
2950 	/* Cleanup old maps */
2951 	if (!dev_maps)
2952 		goto out_no_old_maps;
2953 
2954 	for (j = 0; j < dev_maps->nr_ids; j++) {
2955 		for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
2956 			map = xmap_dereference(dev_maps->attr_map[tci]);
2957 			if (!map)
2958 				continue;
2959 
2960 			if (copy) {
2961 				new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2962 				if (map == new_map)
2963 					continue;
2964 			}
2965 
2966 			RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2967 			kfree_rcu(map, rcu);
2968 		}
2969 	}
2970 
2971 	old_dev_maps = dev_maps;
2972 
2973 out_no_old_maps:
2974 	dev_maps = new_dev_maps;
2975 	active = true;
2976 
2977 out_no_new_maps:
2978 	if (type == XPS_CPUS)
2979 		/* update Tx queue numa node */
2980 		netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2981 					     (numa_node_id >= 0) ?
2982 					     numa_node_id : NUMA_NO_NODE);
2983 
2984 	if (!dev_maps)
2985 		goto out_no_maps;
2986 
2987 	/* removes tx-queue from unused CPUs/rx-queues */
2988 	for (j = 0; j < dev_maps->nr_ids; j++) {
2989 		tci = j * dev_maps->num_tc;
2990 
2991 		for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2992 			if (i == tc &&
2993 			    netif_attr_test_mask(j, mask, dev_maps->nr_ids) &&
2994 			    netif_attr_test_online(j, online_mask, dev_maps->nr_ids))
2995 				continue;
2996 
2997 			active |= remove_xps_queue(dev_maps,
2998 						   copy ? old_dev_maps : NULL,
2999 						   tci, index);
3000 		}
3001 	}
3002 
3003 	if (old_dev_maps)
3004 		kfree_rcu(old_dev_maps, rcu);
3005 
3006 	/* free map if not active */
3007 	if (!active)
3008 		reset_xps_maps(dev, dev_maps, type);
3009 
3010 out_no_maps:
3011 	mutex_unlock(&xps_map_mutex);
3012 
3013 	return 0;
3014 error:
3015 	/* remove any maps that we added */
3016 	for (j = 0; j < nr_ids; j++) {
3017 		for (i = num_tc, tci = j * num_tc; i--; tci++) {
3018 			new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
3019 			map = copy ?
3020 			      xmap_dereference(dev_maps->attr_map[tci]) :
3021 			      NULL;
3022 			if (new_map && new_map != map)
3023 				kfree(new_map);
3024 		}
3025 	}
3026 
3027 	mutex_unlock(&xps_map_mutex);
3028 
3029 	kfree(new_dev_maps);
3030 	return -ENOMEM;
3031 }
3032 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
3033 
netif_set_xps_queue(struct net_device * dev,const struct cpumask * mask,u16 index)3034 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
3035 			u16 index)
3036 {
3037 	int ret;
3038 
3039 	cpus_read_lock();
3040 	ret =  __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS);
3041 	cpus_read_unlock();
3042 
3043 	return ret;
3044 }
3045 EXPORT_SYMBOL(netif_set_xps_queue);
3046 
3047 #endif
netdev_unbind_all_sb_channels(struct net_device * dev)3048 static void netdev_unbind_all_sb_channels(struct net_device *dev)
3049 {
3050 	struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
3051 
3052 	/* Unbind any subordinate channels */
3053 	while (txq-- != &dev->_tx[0]) {
3054 		if (txq->sb_dev)
3055 			netdev_unbind_sb_channel(dev, txq->sb_dev);
3056 	}
3057 }
3058 
netdev_reset_tc(struct net_device * dev)3059 void netdev_reset_tc(struct net_device *dev)
3060 {
3061 #ifdef CONFIG_XPS
3062 	netif_reset_xps_queues_gt(dev, 0);
3063 #endif
3064 	netdev_unbind_all_sb_channels(dev);
3065 
3066 	/* Reset TC configuration of device */
3067 	dev->num_tc = 0;
3068 	memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
3069 	memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
3070 }
3071 EXPORT_SYMBOL(netdev_reset_tc);
3072 
netdev_set_tc_queue(struct net_device * dev,u8 tc,u16 count,u16 offset)3073 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
3074 {
3075 	if (tc >= dev->num_tc)
3076 		return -EINVAL;
3077 
3078 #ifdef CONFIG_XPS
3079 	netif_reset_xps_queues(dev, offset, count);
3080 #endif
3081 	dev->tc_to_txq[tc].count = count;
3082 	dev->tc_to_txq[tc].offset = offset;
3083 	return 0;
3084 }
3085 EXPORT_SYMBOL(netdev_set_tc_queue);
3086 
netdev_set_num_tc(struct net_device * dev,u8 num_tc)3087 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
3088 {
3089 	if (num_tc > TC_MAX_QUEUE)
3090 		return -EINVAL;
3091 
3092 #ifdef CONFIG_XPS
3093 	netif_reset_xps_queues_gt(dev, 0);
3094 #endif
3095 	netdev_unbind_all_sb_channels(dev);
3096 
3097 	dev->num_tc = num_tc;
3098 	return 0;
3099 }
3100 EXPORT_SYMBOL(netdev_set_num_tc);
3101 
netdev_unbind_sb_channel(struct net_device * dev,struct net_device * sb_dev)3102 void netdev_unbind_sb_channel(struct net_device *dev,
3103 			      struct net_device *sb_dev)
3104 {
3105 	struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
3106 
3107 #ifdef CONFIG_XPS
3108 	netif_reset_xps_queues_gt(sb_dev, 0);
3109 #endif
3110 	memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
3111 	memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
3112 
3113 	while (txq-- != &dev->_tx[0]) {
3114 		if (txq->sb_dev == sb_dev)
3115 			txq->sb_dev = NULL;
3116 	}
3117 }
3118 EXPORT_SYMBOL(netdev_unbind_sb_channel);
3119 
netdev_bind_sb_channel_queue(struct net_device * dev,struct net_device * sb_dev,u8 tc,u16 count,u16 offset)3120 int netdev_bind_sb_channel_queue(struct net_device *dev,
3121 				 struct net_device *sb_dev,
3122 				 u8 tc, u16 count, u16 offset)
3123 {
3124 	/* Make certain the sb_dev and dev are already configured */
3125 	if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
3126 		return -EINVAL;
3127 
3128 	/* We cannot hand out queues we don't have */
3129 	if ((offset + count) > dev->real_num_tx_queues)
3130 		return -EINVAL;
3131 
3132 	/* Record the mapping */
3133 	sb_dev->tc_to_txq[tc].count = count;
3134 	sb_dev->tc_to_txq[tc].offset = offset;
3135 
3136 	/* Provide a way for Tx queue to find the tc_to_txq map or
3137 	 * XPS map for itself.
3138 	 */
3139 	while (count--)
3140 		netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
3141 
3142 	return 0;
3143 }
3144 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
3145 
netdev_set_sb_channel(struct net_device * dev,u16 channel)3146 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
3147 {
3148 	/* Do not use a multiqueue device to represent a subordinate channel */
3149 	if (netif_is_multiqueue(dev))
3150 		return -ENODEV;
3151 
3152 	/* We allow channels 1 - 32767 to be used for subordinate channels.
3153 	 * Channel 0 is meant to be "native" mode and used only to represent
3154 	 * the main root device. We allow writing 0 to reset the device back
3155 	 * to normal mode after being used as a subordinate channel.
3156 	 */
3157 	if (channel > S16_MAX)
3158 		return -EINVAL;
3159 
3160 	dev->num_tc = -channel;
3161 
3162 	return 0;
3163 }
3164 EXPORT_SYMBOL(netdev_set_sb_channel);
3165 
3166 /*
3167  * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
3168  * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
3169  */
netif_set_real_num_tx_queues(struct net_device * dev,unsigned int txq)3170 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
3171 {
3172 	bool disabling;
3173 	int rc;
3174 
3175 	disabling = txq < dev->real_num_tx_queues;
3176 
3177 	if (txq < 1 || txq > dev->num_tx_queues)
3178 		return -EINVAL;
3179 
3180 	if (dev->reg_state == NETREG_REGISTERED ||
3181 	    dev->reg_state == NETREG_UNREGISTERING) {
3182 		ASSERT_RTNL();
3183 		netdev_ops_assert_locked(dev);
3184 
3185 		rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
3186 						  txq);
3187 		if (rc)
3188 			return rc;
3189 
3190 		if (dev->num_tc)
3191 			netif_setup_tc(dev, txq);
3192 
3193 		net_shaper_set_real_num_tx_queues(dev, txq);
3194 
3195 		dev_qdisc_change_real_num_tx(dev, txq);
3196 
3197 		dev->real_num_tx_queues = txq;
3198 
3199 		if (disabling) {
3200 			synchronize_net();
3201 			qdisc_reset_all_tx_gt(dev, txq);
3202 #ifdef CONFIG_XPS
3203 			netif_reset_xps_queues_gt(dev, txq);
3204 #endif
3205 		}
3206 	} else {
3207 		dev->real_num_tx_queues = txq;
3208 	}
3209 
3210 	return 0;
3211 }
3212 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
3213 
3214 /**
3215  *	netif_set_real_num_rx_queues - set actual number of RX queues used
3216  *	@dev: Network device
3217  *	@rxq: Actual number of RX queues
3218  *
3219  *	This must be called either with the rtnl_lock held or before
3220  *	registration of the net device.  Returns 0 on success, or a
3221  *	negative error code.  If called before registration, it always
3222  *	succeeds.
3223  */
netif_set_real_num_rx_queues(struct net_device * dev,unsigned int rxq)3224 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
3225 {
3226 	int rc;
3227 
3228 	if (rxq < 1 || rxq > dev->num_rx_queues)
3229 		return -EINVAL;
3230 
3231 	if (dev->reg_state == NETREG_REGISTERED) {
3232 		ASSERT_RTNL();
3233 		netdev_ops_assert_locked(dev);
3234 
3235 		rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
3236 						  rxq);
3237 		if (rc)
3238 			return rc;
3239 	}
3240 
3241 	dev->real_num_rx_queues = rxq;
3242 	return 0;
3243 }
3244 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
3245 
3246 /**
3247  *	netif_set_real_num_queues - set actual number of RX and TX queues used
3248  *	@dev: Network device
3249  *	@txq: Actual number of TX queues
3250  *	@rxq: Actual number of RX queues
3251  *
3252  *	Set the real number of both TX and RX queues.
3253  *	Does nothing if the number of queues is already correct.
3254  */
netif_set_real_num_queues(struct net_device * dev,unsigned int txq,unsigned int rxq)3255 int netif_set_real_num_queues(struct net_device *dev,
3256 			      unsigned int txq, unsigned int rxq)
3257 {
3258 	unsigned int old_rxq = dev->real_num_rx_queues;
3259 	int err;
3260 
3261 	if (txq < 1 || txq > dev->num_tx_queues ||
3262 	    rxq < 1 || rxq > dev->num_rx_queues)
3263 		return -EINVAL;
3264 
3265 	/* Start from increases, so the error path only does decreases -
3266 	 * decreases can't fail.
3267 	 */
3268 	if (rxq > dev->real_num_rx_queues) {
3269 		err = netif_set_real_num_rx_queues(dev, rxq);
3270 		if (err)
3271 			return err;
3272 	}
3273 	if (txq > dev->real_num_tx_queues) {
3274 		err = netif_set_real_num_tx_queues(dev, txq);
3275 		if (err)
3276 			goto undo_rx;
3277 	}
3278 	if (rxq < dev->real_num_rx_queues)
3279 		WARN_ON(netif_set_real_num_rx_queues(dev, rxq));
3280 	if (txq < dev->real_num_tx_queues)
3281 		WARN_ON(netif_set_real_num_tx_queues(dev, txq));
3282 
3283 	return 0;
3284 undo_rx:
3285 	WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq));
3286 	return err;
3287 }
3288 EXPORT_SYMBOL(netif_set_real_num_queues);
3289 
3290 /**
3291  * netif_set_tso_max_size() - set the max size of TSO frames supported
3292  * @dev:	netdev to update
3293  * @size:	max skb->len of a TSO frame
3294  *
3295  * Set the limit on the size of TSO super-frames the device can handle.
3296  * Unless explicitly set the stack will assume the value of
3297  * %GSO_LEGACY_MAX_SIZE.
3298  */
netif_set_tso_max_size(struct net_device * dev,unsigned int size)3299 void netif_set_tso_max_size(struct net_device *dev, unsigned int size)
3300 {
3301 	dev->tso_max_size = min(GSO_MAX_SIZE, size);
3302 	if (size < READ_ONCE(dev->gso_max_size))
3303 		netif_set_gso_max_size(dev, size);
3304 	if (size < READ_ONCE(dev->gso_ipv4_max_size))
3305 		netif_set_gso_ipv4_max_size(dev, size);
3306 }
3307 EXPORT_SYMBOL(netif_set_tso_max_size);
3308 
3309 /**
3310  * netif_set_tso_max_segs() - set the max number of segs supported for TSO
3311  * @dev:	netdev to update
3312  * @segs:	max number of TCP segments
3313  *
3314  * Set the limit on the number of TCP segments the device can generate from
3315  * a single TSO super-frame.
3316  * Unless explicitly set the stack will assume the value of %GSO_MAX_SEGS.
3317  */
netif_set_tso_max_segs(struct net_device * dev,unsigned int segs)3318 void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs)
3319 {
3320 	dev->tso_max_segs = segs;
3321 	if (segs < READ_ONCE(dev->gso_max_segs))
3322 		netif_set_gso_max_segs(dev, segs);
3323 }
3324 EXPORT_SYMBOL(netif_set_tso_max_segs);
3325 
3326 /**
3327  * netif_inherit_tso_max() - copy all TSO limits from a lower device to an upper
3328  * @to:		netdev to update
3329  * @from:	netdev from which to copy the limits
3330  */
netif_inherit_tso_max(struct net_device * to,const struct net_device * from)3331 void netif_inherit_tso_max(struct net_device *to, const struct net_device *from)
3332 {
3333 	netif_set_tso_max_size(to, from->tso_max_size);
3334 	netif_set_tso_max_segs(to, from->tso_max_segs);
3335 }
3336 EXPORT_SYMBOL(netif_inherit_tso_max);
3337 
3338 /**
3339  * netif_get_num_default_rss_queues - default number of RSS queues
3340  *
3341  * Default value is the number of physical cores if there are only 1 or 2, or
3342  * divided by 2 if there are more.
3343  */
netif_get_num_default_rss_queues(void)3344 int netif_get_num_default_rss_queues(void)
3345 {
3346 	cpumask_var_t cpus;
3347 	int cpu, count = 0;
3348 
3349 	if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL)))
3350 		return 1;
3351 
3352 	cpumask_copy(cpus, cpu_online_mask);
3353 	for_each_cpu(cpu, cpus) {
3354 		++count;
3355 		cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu));
3356 	}
3357 	free_cpumask_var(cpus);
3358 
3359 	return count > 2 ? DIV_ROUND_UP(count, 2) : count;
3360 }
3361 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3362 
__netif_reschedule(struct Qdisc * q)3363 static void __netif_reschedule(struct Qdisc *q)
3364 {
3365 	struct softnet_data *sd;
3366 	unsigned long flags;
3367 
3368 	local_irq_save(flags);
3369 	sd = this_cpu_ptr(&softnet_data);
3370 	q->next_sched = NULL;
3371 	*sd->output_queue_tailp = q;
3372 	sd->output_queue_tailp = &q->next_sched;
3373 	raise_softirq_irqoff(NET_TX_SOFTIRQ);
3374 	local_irq_restore(flags);
3375 }
3376 
__netif_schedule(struct Qdisc * q)3377 void __netif_schedule(struct Qdisc *q)
3378 {
3379 	if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3380 		__netif_reschedule(q);
3381 }
3382 EXPORT_SYMBOL(__netif_schedule);
3383 
3384 struct dev_kfree_skb_cb {
3385 	enum skb_drop_reason reason;
3386 };
3387 
get_kfree_skb_cb(const struct sk_buff * skb)3388 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3389 {
3390 	return (struct dev_kfree_skb_cb *)skb->cb;
3391 }
3392 
netif_schedule_queue(struct netdev_queue * txq)3393 void netif_schedule_queue(struct netdev_queue *txq)
3394 {
3395 	rcu_read_lock();
3396 	if (!netif_xmit_stopped(txq)) {
3397 		struct Qdisc *q = rcu_dereference(txq->qdisc);
3398 
3399 		__netif_schedule(q);
3400 	}
3401 	rcu_read_unlock();
3402 }
3403 EXPORT_SYMBOL(netif_schedule_queue);
3404 
netif_tx_wake_queue(struct netdev_queue * dev_queue)3405 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3406 {
3407 	if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3408 		struct Qdisc *q;
3409 
3410 		rcu_read_lock();
3411 		q = rcu_dereference(dev_queue->qdisc);
3412 		__netif_schedule(q);
3413 		rcu_read_unlock();
3414 	}
3415 }
3416 EXPORT_SYMBOL(netif_tx_wake_queue);
3417 
dev_kfree_skb_irq_reason(struct sk_buff * skb,enum skb_drop_reason reason)3418 void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3419 {
3420 	unsigned long flags;
3421 
3422 	if (unlikely(!skb))
3423 		return;
3424 
3425 	if (likely(refcount_read(&skb->users) == 1)) {
3426 		smp_rmb();
3427 		refcount_set(&skb->users, 0);
3428 	} else if (likely(!refcount_dec_and_test(&skb->users))) {
3429 		return;
3430 	}
3431 	get_kfree_skb_cb(skb)->reason = reason;
3432 	local_irq_save(flags);
3433 	skb->next = __this_cpu_read(softnet_data.completion_queue);
3434 	__this_cpu_write(softnet_data.completion_queue, skb);
3435 	raise_softirq_irqoff(NET_TX_SOFTIRQ);
3436 	local_irq_restore(flags);
3437 }
3438 EXPORT_SYMBOL(dev_kfree_skb_irq_reason);
3439 
dev_kfree_skb_any_reason(struct sk_buff * skb,enum skb_drop_reason reason)3440 void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3441 {
3442 	if (in_hardirq() || irqs_disabled())
3443 		dev_kfree_skb_irq_reason(skb, reason);
3444 	else
3445 		kfree_skb_reason(skb, reason);
3446 }
3447 EXPORT_SYMBOL(dev_kfree_skb_any_reason);
3448 
3449 
3450 /**
3451  * netif_device_detach - mark device as removed
3452  * @dev: network device
3453  *
3454  * Mark device as removed from system and therefore no longer available.
3455  */
netif_device_detach(struct net_device * dev)3456 void netif_device_detach(struct net_device *dev)
3457 {
3458 	if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3459 	    netif_running(dev)) {
3460 		netif_tx_stop_all_queues(dev);
3461 	}
3462 }
3463 EXPORT_SYMBOL(netif_device_detach);
3464 
3465 /**
3466  * netif_device_attach - mark device as attached
3467  * @dev: network device
3468  *
3469  * Mark device as attached from system and restart if needed.
3470  */
netif_device_attach(struct net_device * dev)3471 void netif_device_attach(struct net_device *dev)
3472 {
3473 	if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3474 	    netif_running(dev)) {
3475 		netif_tx_wake_all_queues(dev);
3476 		netdev_watchdog_up(dev);
3477 	}
3478 }
3479 EXPORT_SYMBOL(netif_device_attach);
3480 
3481 /*
3482  * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3483  * to be used as a distribution range.
3484  */
skb_tx_hash(const struct net_device * dev,const struct net_device * sb_dev,struct sk_buff * skb)3485 static u16 skb_tx_hash(const struct net_device *dev,
3486 		       const struct net_device *sb_dev,
3487 		       struct sk_buff *skb)
3488 {
3489 	u32 hash;
3490 	u16 qoffset = 0;
3491 	u16 qcount = dev->real_num_tx_queues;
3492 
3493 	if (dev->num_tc) {
3494 		u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3495 
3496 		qoffset = sb_dev->tc_to_txq[tc].offset;
3497 		qcount = sb_dev->tc_to_txq[tc].count;
3498 		if (unlikely(!qcount)) {
3499 			net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3500 					     sb_dev->name, qoffset, tc);
3501 			qoffset = 0;
3502 			qcount = dev->real_num_tx_queues;
3503 		}
3504 	}
3505 
3506 	if (skb_rx_queue_recorded(skb)) {
3507 		DEBUG_NET_WARN_ON_ONCE(qcount == 0);
3508 		hash = skb_get_rx_queue(skb);
3509 		if (hash >= qoffset)
3510 			hash -= qoffset;
3511 		while (unlikely(hash >= qcount))
3512 			hash -= qcount;
3513 		return hash + qoffset;
3514 	}
3515 
3516 	return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3517 }
3518 
skb_warn_bad_offload(const struct sk_buff * skb)3519 void skb_warn_bad_offload(const struct sk_buff *skb)
3520 {
3521 	static const netdev_features_t null_features;
3522 	struct net_device *dev = skb->dev;
3523 	const char *name = "";
3524 
3525 	if (!net_ratelimit())
3526 		return;
3527 
3528 	if (dev) {
3529 		if (dev->dev.parent)
3530 			name = dev_driver_string(dev->dev.parent);
3531 		else
3532 			name = netdev_name(dev);
3533 	}
3534 	skb_dump(KERN_WARNING, skb, false);
3535 	WARN(1, "%s: caps=(%pNF, %pNF)\n",
3536 	     name, dev ? &dev->features : &null_features,
3537 	     skb->sk ? &skb->sk->sk_route_caps : &null_features);
3538 }
3539 
3540 /*
3541  * Invalidate hardware checksum when packet is to be mangled, and
3542  * complete checksum manually on outgoing path.
3543  */
skb_checksum_help(struct sk_buff * skb)3544 int skb_checksum_help(struct sk_buff *skb)
3545 {
3546 	__wsum csum;
3547 	int ret = 0, offset;
3548 
3549 	if (skb->ip_summed == CHECKSUM_COMPLETE)
3550 		goto out_set_summed;
3551 
3552 	if (unlikely(skb_is_gso(skb))) {
3553 		skb_warn_bad_offload(skb);
3554 		return -EINVAL;
3555 	}
3556 
3557 	if (!skb_frags_readable(skb)) {
3558 		return -EFAULT;
3559 	}
3560 
3561 	/* Before computing a checksum, we should make sure no frag could
3562 	 * be modified by an external entity : checksum could be wrong.
3563 	 */
3564 	if (skb_has_shared_frag(skb)) {
3565 		ret = __skb_linearize(skb);
3566 		if (ret)
3567 			goto out;
3568 	}
3569 
3570 	offset = skb_checksum_start_offset(skb);
3571 	ret = -EINVAL;
3572 	if (unlikely(offset >= skb_headlen(skb))) {
3573 		DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3574 		WARN_ONCE(true, "offset (%d) >= skb_headlen() (%u)\n",
3575 			  offset, skb_headlen(skb));
3576 		goto out;
3577 	}
3578 	csum = skb_checksum(skb, offset, skb->len - offset, 0);
3579 
3580 	offset += skb->csum_offset;
3581 	if (unlikely(offset + sizeof(__sum16) > skb_headlen(skb))) {
3582 		DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3583 		WARN_ONCE(true, "offset+2 (%zu) > skb_headlen() (%u)\n",
3584 			  offset + sizeof(__sum16), skb_headlen(skb));
3585 		goto out;
3586 	}
3587 	ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3588 	if (ret)
3589 		goto out;
3590 
3591 	*(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3592 out_set_summed:
3593 	skb->ip_summed = CHECKSUM_NONE;
3594 out:
3595 	return ret;
3596 }
3597 EXPORT_SYMBOL(skb_checksum_help);
3598 
3599 #ifdef CONFIG_NET_CRC32C
skb_crc32c_csum_help(struct sk_buff * skb)3600 int skb_crc32c_csum_help(struct sk_buff *skb)
3601 {
3602 	u32 crc;
3603 	int ret = 0, offset, start;
3604 
3605 	if (skb->ip_summed != CHECKSUM_PARTIAL)
3606 		goto out;
3607 
3608 	if (unlikely(skb_is_gso(skb)))
3609 		goto out;
3610 
3611 	/* Before computing a checksum, we should make sure no frag could
3612 	 * be modified by an external entity : checksum could be wrong.
3613 	 */
3614 	if (unlikely(skb_has_shared_frag(skb))) {
3615 		ret = __skb_linearize(skb);
3616 		if (ret)
3617 			goto out;
3618 	}
3619 	start = skb_checksum_start_offset(skb);
3620 	offset = start + offsetof(struct sctphdr, checksum);
3621 	if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3622 		ret = -EINVAL;
3623 		goto out;
3624 	}
3625 
3626 	ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3627 	if (ret)
3628 		goto out;
3629 
3630 	crc = ~skb_crc32c(skb, start, skb->len - start, ~0);
3631 	*(__le32 *)(skb->data + offset) = cpu_to_le32(crc);
3632 	skb_reset_csum_not_inet(skb);
3633 out:
3634 	return ret;
3635 }
3636 EXPORT_SYMBOL(skb_crc32c_csum_help);
3637 #endif /* CONFIG_NET_CRC32C */
3638 
skb_network_protocol(struct sk_buff * skb,int * depth)3639 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3640 {
3641 	__be16 type = skb->protocol;
3642 
3643 	/* Tunnel gso handlers can set protocol to ethernet. */
3644 	if (type == htons(ETH_P_TEB)) {
3645 		struct ethhdr *eth;
3646 
3647 		if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3648 			return 0;
3649 
3650 		eth = (struct ethhdr *)skb->data;
3651 		type = eth->h_proto;
3652 	}
3653 
3654 	return vlan_get_protocol_and_depth(skb, type, depth);
3655 }
3656 
3657 
3658 /* Take action when hardware reception checksum errors are detected. */
3659 #ifdef CONFIG_BUG
do_netdev_rx_csum_fault(struct net_device * dev,struct sk_buff * skb)3660 static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3661 {
3662 	netdev_err(dev, "hw csum failure\n");
3663 	skb_dump(KERN_ERR, skb, true);
3664 	dump_stack();
3665 }
3666 
netdev_rx_csum_fault(struct net_device * dev,struct sk_buff * skb)3667 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3668 {
3669 	DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb);
3670 }
3671 EXPORT_SYMBOL(netdev_rx_csum_fault);
3672 #endif
3673 
3674 /* XXX: check that highmem exists at all on the given machine. */
illegal_highdma(struct net_device * dev,struct sk_buff * skb)3675 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3676 {
3677 #ifdef CONFIG_HIGHMEM
3678 	int i;
3679 
3680 	if (!(dev->features & NETIF_F_HIGHDMA)) {
3681 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3682 			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3683 			struct page *page = skb_frag_page(frag);
3684 
3685 			if (page && PageHighMem(page))
3686 				return 1;
3687 		}
3688 	}
3689 #endif
3690 	return 0;
3691 }
3692 
3693 /* If MPLS offload request, verify we are testing hardware MPLS features
3694  * instead of standard features for the netdev.
3695  */
3696 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
net_mpls_features(struct sk_buff * skb,netdev_features_t features,__be16 type)3697 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3698 					   netdev_features_t features,
3699 					   __be16 type)
3700 {
3701 	if (eth_p_mpls(type))
3702 		features &= skb->dev->mpls_features;
3703 
3704 	return features;
3705 }
3706 #else
net_mpls_features(struct sk_buff * skb,netdev_features_t features,__be16 type)3707 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3708 					   netdev_features_t features,
3709 					   __be16 type)
3710 {
3711 	return features;
3712 }
3713 #endif
3714 
harmonize_features(struct sk_buff * skb,netdev_features_t features)3715 static netdev_features_t harmonize_features(struct sk_buff *skb,
3716 	netdev_features_t features)
3717 {
3718 	__be16 type;
3719 
3720 	type = skb_network_protocol(skb, NULL);
3721 	features = net_mpls_features(skb, features, type);
3722 
3723 	if (skb->ip_summed != CHECKSUM_NONE &&
3724 	    !can_checksum_protocol(features, type)) {
3725 		features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3726 	}
3727 	if (illegal_highdma(skb->dev, skb))
3728 		features &= ~NETIF_F_SG;
3729 
3730 	return features;
3731 }
3732 
passthru_features_check(struct sk_buff * skb,struct net_device * dev,netdev_features_t features)3733 netdev_features_t passthru_features_check(struct sk_buff *skb,
3734 					  struct net_device *dev,
3735 					  netdev_features_t features)
3736 {
3737 	return features;
3738 }
3739 EXPORT_SYMBOL(passthru_features_check);
3740 
dflt_features_check(struct sk_buff * skb,struct net_device * dev,netdev_features_t features)3741 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3742 					     struct net_device *dev,
3743 					     netdev_features_t features)
3744 {
3745 	return vlan_features_check(skb, features);
3746 }
3747 
gso_features_check(const struct sk_buff * skb,struct net_device * dev,netdev_features_t features)3748 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3749 					    struct net_device *dev,
3750 					    netdev_features_t features)
3751 {
3752 	u16 gso_segs = skb_shinfo(skb)->gso_segs;
3753 
3754 	if (gso_segs > READ_ONCE(dev->gso_max_segs))
3755 		return features & ~NETIF_F_GSO_MASK;
3756 
3757 	if (unlikely(skb->len >= netif_get_gso_max_size(dev, skb)))
3758 		return features & ~NETIF_F_GSO_MASK;
3759 
3760 	if (!skb_shinfo(skb)->gso_type) {
3761 		skb_warn_bad_offload(skb);
3762 		return features & ~NETIF_F_GSO_MASK;
3763 	}
3764 
3765 	/* Support for GSO partial features requires software
3766 	 * intervention before we can actually process the packets
3767 	 * so we need to strip support for any partial features now
3768 	 * and we can pull them back in after we have partially
3769 	 * segmented the frame.
3770 	 */
3771 	if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3772 		features &= ~dev->gso_partial_features;
3773 
3774 	/* Make sure to clear the IPv4 ID mangling feature if the
3775 	 * IPv4 header has the potential to be fragmented.
3776 	 */
3777 	if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3778 		struct iphdr *iph = skb->encapsulation ?
3779 				    inner_ip_hdr(skb) : ip_hdr(skb);
3780 
3781 		if (!(iph->frag_off & htons(IP_DF)))
3782 			features &= ~NETIF_F_TSO_MANGLEID;
3783 	}
3784 
3785 	return features;
3786 }
3787 
netif_skb_features(struct sk_buff * skb)3788 netdev_features_t netif_skb_features(struct sk_buff *skb)
3789 {
3790 	struct net_device *dev = skb->dev;
3791 	netdev_features_t features = dev->features;
3792 
3793 	if (skb_is_gso(skb))
3794 		features = gso_features_check(skb, dev, features);
3795 
3796 	/* If encapsulation offload request, verify we are testing
3797 	 * hardware encapsulation features instead of standard
3798 	 * features for the netdev
3799 	 */
3800 	if (skb->encapsulation)
3801 		features &= dev->hw_enc_features;
3802 
3803 	if (skb_vlan_tagged(skb))
3804 		features = netdev_intersect_features(features,
3805 						     dev->vlan_features |
3806 						     NETIF_F_HW_VLAN_CTAG_TX |
3807 						     NETIF_F_HW_VLAN_STAG_TX);
3808 
3809 	if (dev->netdev_ops->ndo_features_check)
3810 		features &= dev->netdev_ops->ndo_features_check(skb, dev,
3811 								features);
3812 	else
3813 		features &= dflt_features_check(skb, dev, features);
3814 
3815 	return harmonize_features(skb, features);
3816 }
3817 EXPORT_SYMBOL(netif_skb_features);
3818 
xmit_one(struct sk_buff * skb,struct net_device * dev,struct netdev_queue * txq,bool more)3819 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3820 		    struct netdev_queue *txq, bool more)
3821 {
3822 	unsigned int len;
3823 	int rc;
3824 
3825 	if (dev_nit_active_rcu(dev))
3826 		dev_queue_xmit_nit(skb, dev);
3827 
3828 	len = skb->len;
3829 	trace_net_dev_start_xmit(skb, dev);
3830 	rc = netdev_start_xmit(skb, dev, txq, more);
3831 	trace_net_dev_xmit(skb, rc, dev, len);
3832 
3833 	return rc;
3834 }
3835 
dev_hard_start_xmit(struct sk_buff * first,struct net_device * dev,struct netdev_queue * txq,int * ret)3836 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3837 				    struct netdev_queue *txq, int *ret)
3838 {
3839 	struct sk_buff *skb = first;
3840 	int rc = NETDEV_TX_OK;
3841 
3842 	while (skb) {
3843 		struct sk_buff *next = skb->next;
3844 
3845 		skb_mark_not_on_list(skb);
3846 		rc = xmit_one(skb, dev, txq, next != NULL);
3847 		if (unlikely(!dev_xmit_complete(rc))) {
3848 			skb->next = next;
3849 			goto out;
3850 		}
3851 
3852 		skb = next;
3853 		if (netif_tx_queue_stopped(txq) && skb) {
3854 			rc = NETDEV_TX_BUSY;
3855 			break;
3856 		}
3857 	}
3858 
3859 out:
3860 	*ret = rc;
3861 	return skb;
3862 }
3863 
validate_xmit_vlan(struct sk_buff * skb,netdev_features_t features)3864 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3865 					  netdev_features_t features)
3866 {
3867 	if (skb_vlan_tag_present(skb) &&
3868 	    !vlan_hw_offload_capable(features, skb->vlan_proto))
3869 		skb = __vlan_hwaccel_push_inside(skb);
3870 	return skb;
3871 }
3872 
skb_csum_hwoffload_help(struct sk_buff * skb,const netdev_features_t features)3873 int skb_csum_hwoffload_help(struct sk_buff *skb,
3874 			    const netdev_features_t features)
3875 {
3876 	if (unlikely(skb_csum_is_sctp(skb)))
3877 		return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3878 			skb_crc32c_csum_help(skb);
3879 
3880 	if (features & NETIF_F_HW_CSUM)
3881 		return 0;
3882 
3883 	if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
3884 		if (vlan_get_protocol(skb) == htons(ETH_P_IPV6) &&
3885 		    skb_network_header_len(skb) != sizeof(struct ipv6hdr) &&
3886 		    !ipv6_has_hopopt_jumbo(skb))
3887 			goto sw_checksum;
3888 
3889 		switch (skb->csum_offset) {
3890 		case offsetof(struct tcphdr, check):
3891 		case offsetof(struct udphdr, check):
3892 			return 0;
3893 		}
3894 	}
3895 
3896 sw_checksum:
3897 	return skb_checksum_help(skb);
3898 }
3899 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3900 
validate_xmit_unreadable_skb(struct sk_buff * skb,struct net_device * dev)3901 static struct sk_buff *validate_xmit_unreadable_skb(struct sk_buff *skb,
3902 						    struct net_device *dev)
3903 {
3904 	struct skb_shared_info *shinfo;
3905 	struct net_iov *niov;
3906 
3907 	if (likely(skb_frags_readable(skb)))
3908 		goto out;
3909 
3910 	if (!dev->netmem_tx)
3911 		goto out_free;
3912 
3913 	shinfo = skb_shinfo(skb);
3914 
3915 	if (shinfo->nr_frags > 0) {
3916 		niov = netmem_to_net_iov(skb_frag_netmem(&shinfo->frags[0]));
3917 		if (net_is_devmem_iov(niov) &&
3918 		    net_devmem_iov_binding(niov)->dev != dev)
3919 			goto out_free;
3920 	}
3921 
3922 out:
3923 	return skb;
3924 
3925 out_free:
3926 	kfree_skb(skb);
3927 	return NULL;
3928 }
3929 
validate_xmit_skb(struct sk_buff * skb,struct net_device * dev,bool * again)3930 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3931 {
3932 	netdev_features_t features;
3933 
3934 	skb = validate_xmit_unreadable_skb(skb, dev);
3935 	if (unlikely(!skb))
3936 		goto out_null;
3937 
3938 	features = netif_skb_features(skb);
3939 	skb = validate_xmit_vlan(skb, features);
3940 	if (unlikely(!skb))
3941 		goto out_null;
3942 
3943 	skb = sk_validate_xmit_skb(skb, dev);
3944 	if (unlikely(!skb))
3945 		goto out_null;
3946 
3947 	if (netif_needs_gso(skb, features)) {
3948 		struct sk_buff *segs;
3949 
3950 		segs = skb_gso_segment(skb, features);
3951 		if (IS_ERR(segs)) {
3952 			goto out_kfree_skb;
3953 		} else if (segs) {
3954 			consume_skb(skb);
3955 			skb = segs;
3956 		}
3957 	} else {
3958 		if (skb_needs_linearize(skb, features) &&
3959 		    __skb_linearize(skb))
3960 			goto out_kfree_skb;
3961 
3962 		/* If packet is not checksummed and device does not
3963 		 * support checksumming for this protocol, complete
3964 		 * checksumming here.
3965 		 */
3966 		if (skb->ip_summed == CHECKSUM_PARTIAL) {
3967 			if (skb->encapsulation)
3968 				skb_set_inner_transport_header(skb,
3969 							       skb_checksum_start_offset(skb));
3970 			else
3971 				skb_set_transport_header(skb,
3972 							 skb_checksum_start_offset(skb));
3973 			if (skb_csum_hwoffload_help(skb, features))
3974 				goto out_kfree_skb;
3975 		}
3976 	}
3977 
3978 	skb = validate_xmit_xfrm(skb, features, again);
3979 
3980 	return skb;
3981 
3982 out_kfree_skb:
3983 	kfree_skb(skb);
3984 out_null:
3985 	dev_core_stats_tx_dropped_inc(dev);
3986 	return NULL;
3987 }
3988 
validate_xmit_skb_list(struct sk_buff * skb,struct net_device * dev,bool * again)3989 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3990 {
3991 	struct sk_buff *next, *head = NULL, *tail;
3992 
3993 	for (; skb != NULL; skb = next) {
3994 		next = skb->next;
3995 		skb_mark_not_on_list(skb);
3996 
3997 		/* in case skb won't be segmented, point to itself */
3998 		skb->prev = skb;
3999 
4000 		skb = validate_xmit_skb(skb, dev, again);
4001 		if (!skb)
4002 			continue;
4003 
4004 		if (!head)
4005 			head = skb;
4006 		else
4007 			tail->next = skb;
4008 		/* If skb was segmented, skb->prev points to
4009 		 * the last segment. If not, it still contains skb.
4010 		 */
4011 		tail = skb->prev;
4012 	}
4013 	return head;
4014 }
4015 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
4016 
qdisc_pkt_len_init(struct sk_buff * skb)4017 static void qdisc_pkt_len_init(struct sk_buff *skb)
4018 {
4019 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
4020 
4021 	qdisc_skb_cb(skb)->pkt_len = skb->len;
4022 
4023 	/* To get more precise estimation of bytes sent on wire,
4024 	 * we add to pkt_len the headers size of all segments
4025 	 */
4026 	if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
4027 		u16 gso_segs = shinfo->gso_segs;
4028 		unsigned int hdr_len;
4029 
4030 		/* mac layer + network layer */
4031 		hdr_len = skb_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()/dev_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 	struct packet_type *ptype, *pt_prev;
5753 	rx_handler_func_t *rx_handler;
5754 	struct sk_buff *skb = *pskb;
5755 	struct net_device *orig_dev;
5756 	bool deliver_exact = false;
5757 	int ret = NET_RX_DROP;
5758 	__be16 type;
5759 
5760 	net_timestamp_check(!READ_ONCE(net_hotdata.tstamp_prequeue), skb);
5761 
5762 	trace_netif_receive_skb(skb);
5763 
5764 	orig_dev = skb->dev;
5765 
5766 	skb_reset_network_header(skb);
5767 #if !defined(CONFIG_DEBUG_NET)
5768 	/* We plan to no longer reset the transport header here.
5769 	 * Give some time to fuzzers and dev build to catch bugs
5770 	 * in network stacks.
5771 	 */
5772 	if (!skb_transport_header_was_set(skb))
5773 		skb_reset_transport_header(skb);
5774 #endif
5775 	skb_reset_mac_len(skb);
5776 
5777 	pt_prev = NULL;
5778 
5779 another_round:
5780 	skb->skb_iif = skb->dev->ifindex;
5781 
5782 	__this_cpu_inc(softnet_data.processed);
5783 
5784 	if (static_branch_unlikely(&generic_xdp_needed_key)) {
5785 		int ret2;
5786 
5787 		migrate_disable();
5788 		ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog),
5789 				      &skb);
5790 		migrate_enable();
5791 
5792 		if (ret2 != XDP_PASS) {
5793 			ret = NET_RX_DROP;
5794 			goto out;
5795 		}
5796 	}
5797 
5798 	if (eth_type_vlan(skb->protocol)) {
5799 		skb = skb_vlan_untag(skb);
5800 		if (unlikely(!skb))
5801 			goto out;
5802 	}
5803 
5804 	if (skb_skip_tc_classify(skb))
5805 		goto skip_classify;
5806 
5807 	if (pfmemalloc)
5808 		goto skip_taps;
5809 
5810 	list_for_each_entry_rcu(ptype, &dev_net_rcu(skb->dev)->ptype_all,
5811 				list) {
5812 		if (pt_prev)
5813 			ret = deliver_skb(skb, pt_prev, orig_dev);
5814 		pt_prev = ptype;
5815 	}
5816 
5817 	list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5818 		if (pt_prev)
5819 			ret = deliver_skb(skb, pt_prev, orig_dev);
5820 		pt_prev = ptype;
5821 	}
5822 
5823 skip_taps:
5824 #ifdef CONFIG_NET_INGRESS
5825 	if (static_branch_unlikely(&ingress_needed_key)) {
5826 		bool another = false;
5827 
5828 		nf_skip_egress(skb, true);
5829 		skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5830 					 &another);
5831 		if (another)
5832 			goto another_round;
5833 		if (!skb)
5834 			goto out;
5835 
5836 		nf_skip_egress(skb, false);
5837 		if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5838 			goto out;
5839 	}
5840 #endif
5841 	skb_reset_redirect(skb);
5842 skip_classify:
5843 	if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5844 		goto drop;
5845 
5846 	if (skb_vlan_tag_present(skb)) {
5847 		if (pt_prev) {
5848 			ret = deliver_skb(skb, pt_prev, orig_dev);
5849 			pt_prev = NULL;
5850 		}
5851 		if (vlan_do_receive(&skb))
5852 			goto another_round;
5853 		else if (unlikely(!skb))
5854 			goto out;
5855 	}
5856 
5857 	rx_handler = rcu_dereference(skb->dev->rx_handler);
5858 	if (rx_handler) {
5859 		if (pt_prev) {
5860 			ret = deliver_skb(skb, pt_prev, orig_dev);
5861 			pt_prev = NULL;
5862 		}
5863 		switch (rx_handler(&skb)) {
5864 		case RX_HANDLER_CONSUMED:
5865 			ret = NET_RX_SUCCESS;
5866 			goto out;
5867 		case RX_HANDLER_ANOTHER:
5868 			goto another_round;
5869 		case RX_HANDLER_EXACT:
5870 			deliver_exact = true;
5871 			break;
5872 		case RX_HANDLER_PASS:
5873 			break;
5874 		default:
5875 			BUG();
5876 		}
5877 	}
5878 
5879 	if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5880 check_vlan_id:
5881 		if (skb_vlan_tag_get_id(skb)) {
5882 			/* Vlan id is non 0 and vlan_do_receive() above couldn't
5883 			 * find vlan device.
5884 			 */
5885 			skb->pkt_type = PACKET_OTHERHOST;
5886 		} else if (eth_type_vlan(skb->protocol)) {
5887 			/* Outer header is 802.1P with vlan 0, inner header is
5888 			 * 802.1Q or 802.1AD and vlan_do_receive() above could
5889 			 * not find vlan dev for vlan id 0.
5890 			 */
5891 			__vlan_hwaccel_clear_tag(skb);
5892 			skb = skb_vlan_untag(skb);
5893 			if (unlikely(!skb))
5894 				goto out;
5895 			if (vlan_do_receive(&skb))
5896 				/* After stripping off 802.1P header with vlan 0
5897 				 * vlan dev is found for inner header.
5898 				 */
5899 				goto another_round;
5900 			else if (unlikely(!skb))
5901 				goto out;
5902 			else
5903 				/* We have stripped outer 802.1P vlan 0 header.
5904 				 * But could not find vlan dev.
5905 				 * check again for vlan id to set OTHERHOST.
5906 				 */
5907 				goto check_vlan_id;
5908 		}
5909 		/* Note: we might in the future use prio bits
5910 		 * and set skb->priority like in vlan_do_receive()
5911 		 * For the time being, just ignore Priority Code Point
5912 		 */
5913 		__vlan_hwaccel_clear_tag(skb);
5914 	}
5915 
5916 	type = skb->protocol;
5917 
5918 	/* deliver only exact match when indicated */
5919 	if (likely(!deliver_exact)) {
5920 		deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5921 				       &ptype_base[ntohs(type) &
5922 						   PTYPE_HASH_MASK]);
5923 
5924 		/* orig_dev and skb->dev could belong to different netns;
5925 		 * Even in such case we need to traverse only the list
5926 		 * coming from skb->dev, as the ptype owner (packet socket)
5927 		 * will use dev_net(skb->dev) to do namespace filtering.
5928 		 */
5929 		deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5930 				       &dev_net_rcu(skb->dev)->ptype_specific);
5931 	}
5932 
5933 	deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5934 			       &orig_dev->ptype_specific);
5935 
5936 	if (unlikely(skb->dev != orig_dev)) {
5937 		deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5938 				       &skb->dev->ptype_specific);
5939 	}
5940 
5941 	if (pt_prev) {
5942 		if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5943 			goto drop;
5944 		*ppt_prev = pt_prev;
5945 	} else {
5946 drop:
5947 		if (!deliver_exact)
5948 			dev_core_stats_rx_dropped_inc(skb->dev);
5949 		else
5950 			dev_core_stats_rx_nohandler_inc(skb->dev);
5951 		kfree_skb_reason(skb, SKB_DROP_REASON_UNHANDLED_PROTO);
5952 		/* Jamal, now you will not able to escape explaining
5953 		 * me how you were going to use this. :-)
5954 		 */
5955 		ret = NET_RX_DROP;
5956 	}
5957 
5958 out:
5959 	/* The invariant here is that if *ppt_prev is not NULL
5960 	 * then skb should also be non-NULL.
5961 	 *
5962 	 * Apparently *ppt_prev assignment above holds this invariant due to
5963 	 * skb dereferencing near it.
5964 	 */
5965 	*pskb = skb;
5966 	return ret;
5967 }
5968 
__netif_receive_skb_one_core(struct sk_buff * skb,bool pfmemalloc)5969 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5970 {
5971 	struct net_device *orig_dev = skb->dev;
5972 	struct packet_type *pt_prev = NULL;
5973 	int ret;
5974 
5975 	ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5976 	if (pt_prev)
5977 		ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5978 					 skb->dev, pt_prev, orig_dev);
5979 	return ret;
5980 }
5981 
5982 /**
5983  *	netif_receive_skb_core - special purpose version of netif_receive_skb
5984  *	@skb: buffer to process
5985  *
5986  *	More direct receive version of netif_receive_skb().  It should
5987  *	only be used by callers that have a need to skip RPS and Generic XDP.
5988  *	Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5989  *
5990  *	This function may only be called from softirq context and interrupts
5991  *	should be enabled.
5992  *
5993  *	Return values (usually ignored):
5994  *	NET_RX_SUCCESS: no congestion
5995  *	NET_RX_DROP: packet was dropped
5996  */
netif_receive_skb_core(struct sk_buff * skb)5997 int netif_receive_skb_core(struct sk_buff *skb)
5998 {
5999 	int ret;
6000 
6001 	rcu_read_lock();
6002 	ret = __netif_receive_skb_one_core(skb, false);
6003 	rcu_read_unlock();
6004 
6005 	return ret;
6006 }
6007 EXPORT_SYMBOL(netif_receive_skb_core);
6008 
__netif_receive_skb_list_ptype(struct list_head * head,struct packet_type * pt_prev,struct net_device * orig_dev)6009 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
6010 						  struct packet_type *pt_prev,
6011 						  struct net_device *orig_dev)
6012 {
6013 	struct sk_buff *skb, *next;
6014 
6015 	if (!pt_prev)
6016 		return;
6017 	if (list_empty(head))
6018 		return;
6019 	if (pt_prev->list_func != NULL)
6020 		INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
6021 				   ip_list_rcv, head, pt_prev, orig_dev);
6022 	else
6023 		list_for_each_entry_safe(skb, next, head, list) {
6024 			skb_list_del_init(skb);
6025 			pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
6026 		}
6027 }
6028 
__netif_receive_skb_list_core(struct list_head * head,bool pfmemalloc)6029 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
6030 {
6031 	/* Fast-path assumptions:
6032 	 * - There is no RX handler.
6033 	 * - Only one packet_type matches.
6034 	 * If either of these fails, we will end up doing some per-packet
6035 	 * processing in-line, then handling the 'last ptype' for the whole
6036 	 * sublist.  This can't cause out-of-order delivery to any single ptype,
6037 	 * because the 'last ptype' must be constant across the sublist, and all
6038 	 * other ptypes are handled per-packet.
6039 	 */
6040 	/* Current (common) ptype of sublist */
6041 	struct packet_type *pt_curr = NULL;
6042 	/* Current (common) orig_dev of sublist */
6043 	struct net_device *od_curr = NULL;
6044 	struct sk_buff *skb, *next;
6045 	LIST_HEAD(sublist);
6046 
6047 	list_for_each_entry_safe(skb, next, head, list) {
6048 		struct net_device *orig_dev = skb->dev;
6049 		struct packet_type *pt_prev = NULL;
6050 
6051 		skb_list_del_init(skb);
6052 		__netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
6053 		if (!pt_prev)
6054 			continue;
6055 		if (pt_curr != pt_prev || od_curr != orig_dev) {
6056 			/* dispatch old sublist */
6057 			__netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
6058 			/* start new sublist */
6059 			INIT_LIST_HEAD(&sublist);
6060 			pt_curr = pt_prev;
6061 			od_curr = orig_dev;
6062 		}
6063 		list_add_tail(&skb->list, &sublist);
6064 	}
6065 
6066 	/* dispatch final sublist */
6067 	__netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
6068 }
6069 
__netif_receive_skb(struct sk_buff * skb)6070 static int __netif_receive_skb(struct sk_buff *skb)
6071 {
6072 	int ret;
6073 
6074 	if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
6075 		unsigned int noreclaim_flag;
6076 
6077 		/*
6078 		 * PFMEMALLOC skbs are special, they should
6079 		 * - be delivered to SOCK_MEMALLOC sockets only
6080 		 * - stay away from userspace
6081 		 * - have bounded memory usage
6082 		 *
6083 		 * Use PF_MEMALLOC as this saves us from propagating the allocation
6084 		 * context down to all allocation sites.
6085 		 */
6086 		noreclaim_flag = memalloc_noreclaim_save();
6087 		ret = __netif_receive_skb_one_core(skb, true);
6088 		memalloc_noreclaim_restore(noreclaim_flag);
6089 	} else
6090 		ret = __netif_receive_skb_one_core(skb, false);
6091 
6092 	return ret;
6093 }
6094 
__netif_receive_skb_list(struct list_head * head)6095 static void __netif_receive_skb_list(struct list_head *head)
6096 {
6097 	unsigned long noreclaim_flag = 0;
6098 	struct sk_buff *skb, *next;
6099 	bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
6100 
6101 	list_for_each_entry_safe(skb, next, head, list) {
6102 		if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
6103 			struct list_head sublist;
6104 
6105 			/* Handle the previous sublist */
6106 			list_cut_before(&sublist, head, &skb->list);
6107 			if (!list_empty(&sublist))
6108 				__netif_receive_skb_list_core(&sublist, pfmemalloc);
6109 			pfmemalloc = !pfmemalloc;
6110 			/* See comments in __netif_receive_skb */
6111 			if (pfmemalloc)
6112 				noreclaim_flag = memalloc_noreclaim_save();
6113 			else
6114 				memalloc_noreclaim_restore(noreclaim_flag);
6115 		}
6116 	}
6117 	/* Handle the remaining sublist */
6118 	if (!list_empty(head))
6119 		__netif_receive_skb_list_core(head, pfmemalloc);
6120 	/* Restore pflags */
6121 	if (pfmemalloc)
6122 		memalloc_noreclaim_restore(noreclaim_flag);
6123 }
6124 
generic_xdp_install(struct net_device * dev,struct netdev_bpf * xdp)6125 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
6126 {
6127 	struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
6128 	struct bpf_prog *new = xdp->prog;
6129 	int ret = 0;
6130 
6131 	switch (xdp->command) {
6132 	case XDP_SETUP_PROG:
6133 		rcu_assign_pointer(dev->xdp_prog, new);
6134 		if (old)
6135 			bpf_prog_put(old);
6136 
6137 		if (old && !new) {
6138 			static_branch_dec(&generic_xdp_needed_key);
6139 		} else if (new && !old) {
6140 			static_branch_inc(&generic_xdp_needed_key);
6141 			netif_disable_lro(dev);
6142 			dev_disable_gro_hw(dev);
6143 		}
6144 		break;
6145 
6146 	default:
6147 		ret = -EINVAL;
6148 		break;
6149 	}
6150 
6151 	return ret;
6152 }
6153 
netif_receive_skb_internal(struct sk_buff * skb)6154 static int netif_receive_skb_internal(struct sk_buff *skb)
6155 {
6156 	int ret;
6157 
6158 	net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb);
6159 
6160 	if (skb_defer_rx_timestamp(skb))
6161 		return NET_RX_SUCCESS;
6162 
6163 	rcu_read_lock();
6164 #ifdef CONFIG_RPS
6165 	if (static_branch_unlikely(&rps_needed)) {
6166 		struct rps_dev_flow voidflow, *rflow = &voidflow;
6167 		int cpu = get_rps_cpu(skb->dev, skb, &rflow);
6168 
6169 		if (cpu >= 0) {
6170 			ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
6171 			rcu_read_unlock();
6172 			return ret;
6173 		}
6174 	}
6175 #endif
6176 	ret = __netif_receive_skb(skb);
6177 	rcu_read_unlock();
6178 	return ret;
6179 }
6180 
netif_receive_skb_list_internal(struct list_head * head)6181 void netif_receive_skb_list_internal(struct list_head *head)
6182 {
6183 	struct sk_buff *skb, *next;
6184 	LIST_HEAD(sublist);
6185 
6186 	list_for_each_entry_safe(skb, next, head, list) {
6187 		net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue),
6188 				    skb);
6189 		skb_list_del_init(skb);
6190 		if (!skb_defer_rx_timestamp(skb))
6191 			list_add_tail(&skb->list, &sublist);
6192 	}
6193 	list_splice_init(&sublist, head);
6194 
6195 	rcu_read_lock();
6196 #ifdef CONFIG_RPS
6197 	if (static_branch_unlikely(&rps_needed)) {
6198 		list_for_each_entry_safe(skb, next, head, list) {
6199 			struct rps_dev_flow voidflow, *rflow = &voidflow;
6200 			int cpu = get_rps_cpu(skb->dev, skb, &rflow);
6201 
6202 			if (cpu >= 0) {
6203 				/* Will be handled, remove from list */
6204 				skb_list_del_init(skb);
6205 				enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
6206 			}
6207 		}
6208 	}
6209 #endif
6210 	__netif_receive_skb_list(head);
6211 	rcu_read_unlock();
6212 }
6213 
6214 /**
6215  *	netif_receive_skb - process receive buffer from network
6216  *	@skb: buffer to process
6217  *
6218  *	netif_receive_skb() is the main receive data processing function.
6219  *	It always succeeds. The buffer may be dropped during processing
6220  *	for congestion control or by the protocol layers.
6221  *
6222  *	This function may only be called from softirq context and interrupts
6223  *	should be enabled.
6224  *
6225  *	Return values (usually ignored):
6226  *	NET_RX_SUCCESS: no congestion
6227  *	NET_RX_DROP: packet was dropped
6228  */
netif_receive_skb(struct sk_buff * skb)6229 int netif_receive_skb(struct sk_buff *skb)
6230 {
6231 	int ret;
6232 
6233 	trace_netif_receive_skb_entry(skb);
6234 
6235 	ret = netif_receive_skb_internal(skb);
6236 	trace_netif_receive_skb_exit(ret);
6237 
6238 	return ret;
6239 }
6240 EXPORT_SYMBOL(netif_receive_skb);
6241 
6242 /**
6243  *	netif_receive_skb_list - process many receive buffers from network
6244  *	@head: list of skbs to process.
6245  *
6246  *	Since return value of netif_receive_skb() is normally ignored, and
6247  *	wouldn't be meaningful for a list, this function returns void.
6248  *
6249  *	This function may only be called from softirq context and interrupts
6250  *	should be enabled.
6251  */
netif_receive_skb_list(struct list_head * head)6252 void netif_receive_skb_list(struct list_head *head)
6253 {
6254 	struct sk_buff *skb;
6255 
6256 	if (list_empty(head))
6257 		return;
6258 	if (trace_netif_receive_skb_list_entry_enabled()) {
6259 		list_for_each_entry(skb, head, list)
6260 			trace_netif_receive_skb_list_entry(skb);
6261 	}
6262 	netif_receive_skb_list_internal(head);
6263 	trace_netif_receive_skb_list_exit(0);
6264 }
6265 EXPORT_SYMBOL(netif_receive_skb_list);
6266 
6267 /* Network device is going away, flush any packets still pending */
flush_backlog(struct work_struct * work)6268 static void flush_backlog(struct work_struct *work)
6269 {
6270 	struct sk_buff *skb, *tmp;
6271 	struct sk_buff_head list;
6272 	struct softnet_data *sd;
6273 
6274 	__skb_queue_head_init(&list);
6275 	local_bh_disable();
6276 	sd = this_cpu_ptr(&softnet_data);
6277 
6278 	backlog_lock_irq_disable(sd);
6279 	skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
6280 		if (READ_ONCE(skb->dev->reg_state) == NETREG_UNREGISTERING) {
6281 			__skb_unlink(skb, &sd->input_pkt_queue);
6282 			__skb_queue_tail(&list, skb);
6283 			rps_input_queue_head_incr(sd);
6284 		}
6285 	}
6286 	backlog_unlock_irq_enable(sd);
6287 
6288 	local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
6289 	skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
6290 		if (READ_ONCE(skb->dev->reg_state) == NETREG_UNREGISTERING) {
6291 			__skb_unlink(skb, &sd->process_queue);
6292 			__skb_queue_tail(&list, skb);
6293 			rps_input_queue_head_incr(sd);
6294 		}
6295 	}
6296 	local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
6297 	local_bh_enable();
6298 
6299 	__skb_queue_purge_reason(&list, SKB_DROP_REASON_DEV_READY);
6300 }
6301 
flush_required(int cpu)6302 static bool flush_required(int cpu)
6303 {
6304 #if IS_ENABLED(CONFIG_RPS)
6305 	struct softnet_data *sd = &per_cpu(softnet_data, cpu);
6306 	bool do_flush;
6307 
6308 	backlog_lock_irq_disable(sd);
6309 
6310 	/* as insertion into process_queue happens with the rps lock held,
6311 	 * process_queue access may race only with dequeue
6312 	 */
6313 	do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
6314 		   !skb_queue_empty_lockless(&sd->process_queue);
6315 	backlog_unlock_irq_enable(sd);
6316 
6317 	return do_flush;
6318 #endif
6319 	/* without RPS we can't safely check input_pkt_queue: during a
6320 	 * concurrent remote skb_queue_splice() we can detect as empty both
6321 	 * input_pkt_queue and process_queue even if the latter could end-up
6322 	 * containing a lot of packets.
6323 	 */
6324 	return true;
6325 }
6326 
6327 struct flush_backlogs {
6328 	cpumask_t		flush_cpus;
6329 	struct work_struct	w[];
6330 };
6331 
flush_backlogs_alloc(void)6332 static struct flush_backlogs *flush_backlogs_alloc(void)
6333 {
6334 	return kmalloc(struct_size_t(struct flush_backlogs, w, nr_cpu_ids),
6335 		       GFP_KERNEL);
6336 }
6337 
6338 static struct flush_backlogs *flush_backlogs_fallback;
6339 static DEFINE_MUTEX(flush_backlogs_mutex);
6340 
flush_all_backlogs(void)6341 static void flush_all_backlogs(void)
6342 {
6343 	struct flush_backlogs *ptr = flush_backlogs_alloc();
6344 	unsigned int cpu;
6345 
6346 	if (!ptr) {
6347 		mutex_lock(&flush_backlogs_mutex);
6348 		ptr = flush_backlogs_fallback;
6349 	}
6350 	cpumask_clear(&ptr->flush_cpus);
6351 
6352 	cpus_read_lock();
6353 
6354 	for_each_online_cpu(cpu) {
6355 		if (flush_required(cpu)) {
6356 			INIT_WORK(&ptr->w[cpu], flush_backlog);
6357 			queue_work_on(cpu, system_highpri_wq, &ptr->w[cpu]);
6358 			__cpumask_set_cpu(cpu, &ptr->flush_cpus);
6359 		}
6360 	}
6361 
6362 	/* we can have in flight packet[s] on the cpus we are not flushing,
6363 	 * synchronize_net() in unregister_netdevice_many() will take care of
6364 	 * them.
6365 	 */
6366 	for_each_cpu(cpu, &ptr->flush_cpus)
6367 		flush_work(&ptr->w[cpu]);
6368 
6369 	cpus_read_unlock();
6370 
6371 	if (ptr != flush_backlogs_fallback)
6372 		kfree(ptr);
6373 	else
6374 		mutex_unlock(&flush_backlogs_mutex);
6375 }
6376 
net_rps_send_ipi(struct softnet_data * remsd)6377 static void net_rps_send_ipi(struct softnet_data *remsd)
6378 {
6379 #ifdef CONFIG_RPS
6380 	while (remsd) {
6381 		struct softnet_data *next = remsd->rps_ipi_next;
6382 
6383 		if (cpu_online(remsd->cpu))
6384 			smp_call_function_single_async(remsd->cpu, &remsd->csd);
6385 		remsd = next;
6386 	}
6387 #endif
6388 }
6389 
6390 /*
6391  * net_rps_action_and_irq_enable sends any pending IPI's for rps.
6392  * Note: called with local irq disabled, but exits with local irq enabled.
6393  */
net_rps_action_and_irq_enable(struct softnet_data * sd)6394 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
6395 {
6396 #ifdef CONFIG_RPS
6397 	struct softnet_data *remsd = sd->rps_ipi_list;
6398 
6399 	if (!use_backlog_threads() && remsd) {
6400 		sd->rps_ipi_list = NULL;
6401 
6402 		local_irq_enable();
6403 
6404 		/* Send pending IPI's to kick RPS processing on remote cpus. */
6405 		net_rps_send_ipi(remsd);
6406 	} else
6407 #endif
6408 		local_irq_enable();
6409 }
6410 
sd_has_rps_ipi_waiting(struct softnet_data * sd)6411 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
6412 {
6413 #ifdef CONFIG_RPS
6414 	return !use_backlog_threads() && sd->rps_ipi_list;
6415 #else
6416 	return false;
6417 #endif
6418 }
6419 
process_backlog(struct napi_struct * napi,int quota)6420 static int process_backlog(struct napi_struct *napi, int quota)
6421 {
6422 	struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
6423 	bool again = true;
6424 	int work = 0;
6425 
6426 	/* Check if we have pending ipi, its better to send them now,
6427 	 * not waiting net_rx_action() end.
6428 	 */
6429 	if (sd_has_rps_ipi_waiting(sd)) {
6430 		local_irq_disable();
6431 		net_rps_action_and_irq_enable(sd);
6432 	}
6433 
6434 	napi->weight = READ_ONCE(net_hotdata.dev_rx_weight);
6435 	while (again) {
6436 		struct sk_buff *skb;
6437 
6438 		local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
6439 		while ((skb = __skb_dequeue(&sd->process_queue))) {
6440 			local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
6441 			rcu_read_lock();
6442 			__netif_receive_skb(skb);
6443 			rcu_read_unlock();
6444 			if (++work >= quota) {
6445 				rps_input_queue_head_add(sd, work);
6446 				return work;
6447 			}
6448 
6449 			local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
6450 		}
6451 		local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
6452 
6453 		backlog_lock_irq_disable(sd);
6454 		if (skb_queue_empty(&sd->input_pkt_queue)) {
6455 			/*
6456 			 * Inline a custom version of __napi_complete().
6457 			 * only current cpu owns and manipulates this napi,
6458 			 * and NAPI_STATE_SCHED is the only possible flag set
6459 			 * on backlog.
6460 			 * We can use a plain write instead of clear_bit(),
6461 			 * and we dont need an smp_mb() memory barrier.
6462 			 */
6463 			napi->state &= NAPIF_STATE_THREADED;
6464 			again = false;
6465 		} else {
6466 			local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
6467 			skb_queue_splice_tail_init(&sd->input_pkt_queue,
6468 						   &sd->process_queue);
6469 			local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
6470 		}
6471 		backlog_unlock_irq_enable(sd);
6472 	}
6473 
6474 	if (work)
6475 		rps_input_queue_head_add(sd, work);
6476 	return work;
6477 }
6478 
6479 /**
6480  * __napi_schedule - schedule for receive
6481  * @n: entry to schedule
6482  *
6483  * The entry's receive function will be scheduled to run.
6484  * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6485  */
__napi_schedule(struct napi_struct * n)6486 void __napi_schedule(struct napi_struct *n)
6487 {
6488 	unsigned long flags;
6489 
6490 	local_irq_save(flags);
6491 	____napi_schedule(this_cpu_ptr(&softnet_data), n);
6492 	local_irq_restore(flags);
6493 }
6494 EXPORT_SYMBOL(__napi_schedule);
6495 
6496 /**
6497  *	napi_schedule_prep - check if napi can be scheduled
6498  *	@n: napi context
6499  *
6500  * Test if NAPI routine is already running, and if not mark
6501  * it as running.  This is used as a condition variable to
6502  * insure only one NAPI poll instance runs.  We also make
6503  * sure there is no pending NAPI disable.
6504  */
napi_schedule_prep(struct napi_struct * n)6505 bool napi_schedule_prep(struct napi_struct *n)
6506 {
6507 	unsigned long new, val = READ_ONCE(n->state);
6508 
6509 	do {
6510 		if (unlikely(val & NAPIF_STATE_DISABLE))
6511 			return false;
6512 		new = val | NAPIF_STATE_SCHED;
6513 
6514 		/* Sets STATE_MISSED bit if STATE_SCHED was already set
6515 		 * This was suggested by Alexander Duyck, as compiler
6516 		 * emits better code than :
6517 		 * if (val & NAPIF_STATE_SCHED)
6518 		 *     new |= NAPIF_STATE_MISSED;
6519 		 */
6520 		new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6521 						   NAPIF_STATE_MISSED;
6522 	} while (!try_cmpxchg(&n->state, &val, new));
6523 
6524 	return !(val & NAPIF_STATE_SCHED);
6525 }
6526 EXPORT_SYMBOL(napi_schedule_prep);
6527 
6528 /**
6529  * __napi_schedule_irqoff - schedule for receive
6530  * @n: entry to schedule
6531  *
6532  * Variant of __napi_schedule() assuming hard irqs are masked.
6533  *
6534  * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
6535  * because the interrupt disabled assumption might not be true
6536  * due to force-threaded interrupts and spinlock substitution.
6537  */
__napi_schedule_irqoff(struct napi_struct * n)6538 void __napi_schedule_irqoff(struct napi_struct *n)
6539 {
6540 	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6541 		____napi_schedule(this_cpu_ptr(&softnet_data), n);
6542 	else
6543 		__napi_schedule(n);
6544 }
6545 EXPORT_SYMBOL(__napi_schedule_irqoff);
6546 
napi_complete_done(struct napi_struct * n,int work_done)6547 bool napi_complete_done(struct napi_struct *n, int work_done)
6548 {
6549 	unsigned long flags, val, new, timeout = 0;
6550 	bool ret = true;
6551 
6552 	/*
6553 	 * 1) Don't let napi dequeue from the cpu poll list
6554 	 *    just in case its running on a different cpu.
6555 	 * 2) If we are busy polling, do nothing here, we have
6556 	 *    the guarantee we will be called later.
6557 	 */
6558 	if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6559 				 NAPIF_STATE_IN_BUSY_POLL)))
6560 		return false;
6561 
6562 	if (work_done) {
6563 		if (n->gro.bitmask)
6564 			timeout = napi_get_gro_flush_timeout(n);
6565 		n->defer_hard_irqs_count = napi_get_defer_hard_irqs(n);
6566 	}
6567 	if (n->defer_hard_irqs_count > 0) {
6568 		n->defer_hard_irqs_count--;
6569 		timeout = napi_get_gro_flush_timeout(n);
6570 		if (timeout)
6571 			ret = false;
6572 	}
6573 
6574 	/*
6575 	 * When the NAPI instance uses a timeout and keeps postponing
6576 	 * it, we need to bound somehow the time packets are kept in
6577 	 * the GRO layer.
6578 	 */
6579 	gro_flush(&n->gro, !!timeout);
6580 	gro_normal_list(&n->gro);
6581 
6582 	if (unlikely(!list_empty(&n->poll_list))) {
6583 		/* If n->poll_list is not empty, we need to mask irqs */
6584 		local_irq_save(flags);
6585 		list_del_init(&n->poll_list);
6586 		local_irq_restore(flags);
6587 	}
6588 	WRITE_ONCE(n->list_owner, -1);
6589 
6590 	val = READ_ONCE(n->state);
6591 	do {
6592 		WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6593 
6594 		new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
6595 			      NAPIF_STATE_SCHED_THREADED |
6596 			      NAPIF_STATE_PREFER_BUSY_POLL);
6597 
6598 		/* If STATE_MISSED was set, leave STATE_SCHED set,
6599 		 * because we will call napi->poll() one more time.
6600 		 * This C code was suggested by Alexander Duyck to help gcc.
6601 		 */
6602 		new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6603 						    NAPIF_STATE_SCHED;
6604 	} while (!try_cmpxchg(&n->state, &val, new));
6605 
6606 	if (unlikely(val & NAPIF_STATE_MISSED)) {
6607 		__napi_schedule(n);
6608 		return false;
6609 	}
6610 
6611 	if (timeout)
6612 		hrtimer_start(&n->timer, ns_to_ktime(timeout),
6613 			      HRTIMER_MODE_REL_PINNED);
6614 	return ret;
6615 }
6616 EXPORT_SYMBOL(napi_complete_done);
6617 
skb_defer_free_flush(struct softnet_data * sd)6618 static void skb_defer_free_flush(struct softnet_data *sd)
6619 {
6620 	struct sk_buff *skb, *next;
6621 
6622 	/* Paired with WRITE_ONCE() in skb_attempt_defer_free() */
6623 	if (!READ_ONCE(sd->defer_list))
6624 		return;
6625 
6626 	spin_lock(&sd->defer_lock);
6627 	skb = sd->defer_list;
6628 	sd->defer_list = NULL;
6629 	sd->defer_count = 0;
6630 	spin_unlock(&sd->defer_lock);
6631 
6632 	while (skb != NULL) {
6633 		next = skb->next;
6634 		napi_consume_skb(skb, 1);
6635 		skb = next;
6636 	}
6637 }
6638 
6639 #if defined(CONFIG_NET_RX_BUSY_POLL)
6640 
__busy_poll_stop(struct napi_struct * napi,bool skip_schedule)6641 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
6642 {
6643 	if (!skip_schedule) {
6644 		gro_normal_list(&napi->gro);
6645 		__napi_schedule(napi);
6646 		return;
6647 	}
6648 
6649 	/* Flush too old packets. If HZ < 1000, flush all packets */
6650 	gro_flush(&napi->gro, HZ >= 1000);
6651 	gro_normal_list(&napi->gro);
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 
dev_set_threaded(struct net_device * dev,bool threaded)6929 int dev_set_threaded(struct net_device *dev, bool threaded)
6930 {
6931 	struct napi_struct *napi;
6932 	int err = 0;
6933 
6934 	netdev_assert_locked_or_invisible(dev);
6935 
6936 	if (dev->threaded == threaded)
6937 		return 0;
6938 
6939 	if (threaded) {
6940 		list_for_each_entry(napi, &dev->napi_list, dev_list) {
6941 			if (!napi->thread) {
6942 				err = napi_kthread_create(napi);
6943 				if (err) {
6944 					threaded = false;
6945 					break;
6946 				}
6947 			}
6948 		}
6949 	}
6950 
6951 	WRITE_ONCE(dev->threaded, threaded);
6952 
6953 	/* Make sure kthread is created before THREADED bit
6954 	 * is set.
6955 	 */
6956 	smp_mb__before_atomic();
6957 
6958 	/* Setting/unsetting threaded mode on a napi might not immediately
6959 	 * take effect, if the current napi instance is actively being
6960 	 * polled. In this case, the switch between threaded mode and
6961 	 * softirq mode will happen in the next round of napi_schedule().
6962 	 * This should not cause hiccups/stalls to the live traffic.
6963 	 */
6964 	list_for_each_entry(napi, &dev->napi_list, dev_list)
6965 		assign_bit(NAPI_STATE_THREADED, &napi->state, threaded);
6966 
6967 	return err;
6968 }
6969 EXPORT_SYMBOL(dev_set_threaded);
6970 
6971 /**
6972  * netif_queue_set_napi - Associate queue with the napi
6973  * @dev: device to which NAPI and queue belong
6974  * @queue_index: Index of queue
6975  * @type: queue type as RX or TX
6976  * @napi: NAPI context, pass NULL to clear previously set NAPI
6977  *
6978  * Set queue with its corresponding napi context. This should be done after
6979  * registering the NAPI handler for the queue-vector and the queues have been
6980  * mapped to the corresponding interrupt vector.
6981  */
netif_queue_set_napi(struct net_device * dev,unsigned int queue_index,enum netdev_queue_type type,struct napi_struct * napi)6982 void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index,
6983 			  enum netdev_queue_type type, struct napi_struct *napi)
6984 {
6985 	struct netdev_rx_queue *rxq;
6986 	struct netdev_queue *txq;
6987 
6988 	if (WARN_ON_ONCE(napi && !napi->dev))
6989 		return;
6990 	netdev_ops_assert_locked_or_invisible(dev);
6991 
6992 	switch (type) {
6993 	case NETDEV_QUEUE_TYPE_RX:
6994 		rxq = __netif_get_rx_queue(dev, queue_index);
6995 		rxq->napi = napi;
6996 		return;
6997 	case NETDEV_QUEUE_TYPE_TX:
6998 		txq = netdev_get_tx_queue(dev, queue_index);
6999 		txq->napi = napi;
7000 		return;
7001 	default:
7002 		return;
7003 	}
7004 }
7005 EXPORT_SYMBOL(netif_queue_set_napi);
7006 
7007 static void
netif_napi_irq_notify(struct irq_affinity_notify * notify,const cpumask_t * mask)7008 netif_napi_irq_notify(struct irq_affinity_notify *notify,
7009 		      const cpumask_t *mask)
7010 {
7011 	struct napi_struct *napi =
7012 		container_of(notify, struct napi_struct, notify);
7013 #ifdef CONFIG_RFS_ACCEL
7014 	struct cpu_rmap *rmap = napi->dev->rx_cpu_rmap;
7015 	int err;
7016 #endif
7017 
7018 	if (napi->config && napi->dev->irq_affinity_auto)
7019 		cpumask_copy(&napi->config->affinity_mask, mask);
7020 
7021 #ifdef CONFIG_RFS_ACCEL
7022 	if (napi->dev->rx_cpu_rmap_auto) {
7023 		err = cpu_rmap_update(rmap, napi->napi_rmap_idx, mask);
7024 		if (err)
7025 			netdev_warn(napi->dev, "RMAP update failed (%d)\n",
7026 				    err);
7027 	}
7028 #endif
7029 }
7030 
7031 #ifdef CONFIG_RFS_ACCEL
netif_napi_affinity_release(struct kref * ref)7032 static void netif_napi_affinity_release(struct kref *ref)
7033 {
7034 	struct napi_struct *napi =
7035 		container_of(ref, struct napi_struct, notify.kref);
7036 	struct cpu_rmap *rmap = napi->dev->rx_cpu_rmap;
7037 
7038 	netdev_assert_locked(napi->dev);
7039 	WARN_ON(test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER,
7040 				   &napi->state));
7041 
7042 	if (!napi->dev->rx_cpu_rmap_auto)
7043 		return;
7044 	rmap->obj[napi->napi_rmap_idx] = NULL;
7045 	napi->napi_rmap_idx = -1;
7046 	cpu_rmap_put(rmap);
7047 }
7048 
netif_enable_cpu_rmap(struct net_device * dev,unsigned int num_irqs)7049 int netif_enable_cpu_rmap(struct net_device *dev, unsigned int num_irqs)
7050 {
7051 	if (dev->rx_cpu_rmap_auto)
7052 		return 0;
7053 
7054 	dev->rx_cpu_rmap = alloc_irq_cpu_rmap(num_irqs);
7055 	if (!dev->rx_cpu_rmap)
7056 		return -ENOMEM;
7057 
7058 	dev->rx_cpu_rmap_auto = true;
7059 	return 0;
7060 }
7061 EXPORT_SYMBOL(netif_enable_cpu_rmap);
7062 
netif_del_cpu_rmap(struct net_device * dev)7063 static void netif_del_cpu_rmap(struct net_device *dev)
7064 {
7065 	struct cpu_rmap *rmap = dev->rx_cpu_rmap;
7066 
7067 	if (!dev->rx_cpu_rmap_auto)
7068 		return;
7069 
7070 	/* Free the rmap */
7071 	cpu_rmap_put(rmap);
7072 	dev->rx_cpu_rmap = NULL;
7073 	dev->rx_cpu_rmap_auto = false;
7074 }
7075 
7076 #else
netif_napi_affinity_release(struct kref * ref)7077 static void netif_napi_affinity_release(struct kref *ref)
7078 {
7079 }
7080 
netif_enable_cpu_rmap(struct net_device * dev,unsigned int num_irqs)7081 int netif_enable_cpu_rmap(struct net_device *dev, unsigned int num_irqs)
7082 {
7083 	return 0;
7084 }
7085 EXPORT_SYMBOL(netif_enable_cpu_rmap);
7086 
netif_del_cpu_rmap(struct net_device * dev)7087 static void netif_del_cpu_rmap(struct net_device *dev)
7088 {
7089 }
7090 #endif
7091 
netif_set_affinity_auto(struct net_device * dev)7092 void netif_set_affinity_auto(struct net_device *dev)
7093 {
7094 	unsigned int i, maxqs, numa;
7095 
7096 	maxqs = max(dev->num_tx_queues, dev->num_rx_queues);
7097 	numa = dev_to_node(&dev->dev);
7098 
7099 	for (i = 0; i < maxqs; i++)
7100 		cpumask_set_cpu(cpumask_local_spread(i, numa),
7101 				&dev->napi_config[i].affinity_mask);
7102 
7103 	dev->irq_affinity_auto = true;
7104 }
7105 EXPORT_SYMBOL(netif_set_affinity_auto);
7106 
netif_napi_set_irq_locked(struct napi_struct * napi,int irq)7107 void netif_napi_set_irq_locked(struct napi_struct *napi, int irq)
7108 {
7109 	int rc;
7110 
7111 	netdev_assert_locked_or_invisible(napi->dev);
7112 
7113 	if (napi->irq == irq)
7114 		return;
7115 
7116 	/* Remove existing resources */
7117 	if (test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state))
7118 		irq_set_affinity_notifier(napi->irq, NULL);
7119 
7120 	napi->irq = irq;
7121 	if (irq < 0 ||
7122 	    (!napi->dev->rx_cpu_rmap_auto && !napi->dev->irq_affinity_auto))
7123 		return;
7124 
7125 	/* Abort for buggy drivers */
7126 	if (napi->dev->irq_affinity_auto && WARN_ON_ONCE(!napi->config))
7127 		return;
7128 
7129 #ifdef CONFIG_RFS_ACCEL
7130 	if (napi->dev->rx_cpu_rmap_auto) {
7131 		rc = cpu_rmap_add(napi->dev->rx_cpu_rmap, napi);
7132 		if (rc < 0)
7133 			return;
7134 
7135 		cpu_rmap_get(napi->dev->rx_cpu_rmap);
7136 		napi->napi_rmap_idx = rc;
7137 	}
7138 #endif
7139 
7140 	/* Use core IRQ notifier */
7141 	napi->notify.notify = netif_napi_irq_notify;
7142 	napi->notify.release = netif_napi_affinity_release;
7143 	rc = irq_set_affinity_notifier(irq, &napi->notify);
7144 	if (rc) {
7145 		netdev_warn(napi->dev, "Unable to set IRQ notifier (%d)\n",
7146 			    rc);
7147 		goto put_rmap;
7148 	}
7149 
7150 	set_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state);
7151 	return;
7152 
7153 put_rmap:
7154 #ifdef CONFIG_RFS_ACCEL
7155 	if (napi->dev->rx_cpu_rmap_auto) {
7156 		napi->dev->rx_cpu_rmap->obj[napi->napi_rmap_idx] = NULL;
7157 		cpu_rmap_put(napi->dev->rx_cpu_rmap);
7158 		napi->napi_rmap_idx = -1;
7159 	}
7160 #endif
7161 	napi->notify.notify = NULL;
7162 	napi->notify.release = NULL;
7163 }
7164 EXPORT_SYMBOL(netif_napi_set_irq_locked);
7165 
napi_restore_config(struct napi_struct * n)7166 static void napi_restore_config(struct napi_struct *n)
7167 {
7168 	n->defer_hard_irqs = n->config->defer_hard_irqs;
7169 	n->gro_flush_timeout = n->config->gro_flush_timeout;
7170 	n->irq_suspend_timeout = n->config->irq_suspend_timeout;
7171 
7172 	if (n->dev->irq_affinity_auto &&
7173 	    test_bit(NAPI_STATE_HAS_NOTIFIER, &n->state))
7174 		irq_set_affinity(n->irq, &n->config->affinity_mask);
7175 
7176 	/* a NAPI ID might be stored in the config, if so use it. if not, use
7177 	 * napi_hash_add to generate one for us.
7178 	 */
7179 	if (n->config->napi_id) {
7180 		napi_hash_add_with_id(n, n->config->napi_id);
7181 	} else {
7182 		napi_hash_add(n);
7183 		n->config->napi_id = n->napi_id;
7184 	}
7185 }
7186 
napi_save_config(struct napi_struct * n)7187 static void napi_save_config(struct napi_struct *n)
7188 {
7189 	n->config->defer_hard_irqs = n->defer_hard_irqs;
7190 	n->config->gro_flush_timeout = n->gro_flush_timeout;
7191 	n->config->irq_suspend_timeout = n->irq_suspend_timeout;
7192 	napi_hash_del(n);
7193 }
7194 
7195 /* Netlink wants the NAPI list to be sorted by ID, if adding a NAPI which will
7196  * inherit an existing ID try to insert it at the right position.
7197  */
7198 static void
netif_napi_dev_list_add(struct net_device * dev,struct napi_struct * napi)7199 netif_napi_dev_list_add(struct net_device *dev, struct napi_struct *napi)
7200 {
7201 	unsigned int new_id, pos_id;
7202 	struct list_head *higher;
7203 	struct napi_struct *pos;
7204 
7205 	new_id = UINT_MAX;
7206 	if (napi->config && napi->config->napi_id)
7207 		new_id = napi->config->napi_id;
7208 
7209 	higher = &dev->napi_list;
7210 	list_for_each_entry(pos, &dev->napi_list, dev_list) {
7211 		if (napi_id_valid(pos->napi_id))
7212 			pos_id = pos->napi_id;
7213 		else if (pos->config)
7214 			pos_id = pos->config->napi_id;
7215 		else
7216 			pos_id = UINT_MAX;
7217 
7218 		if (pos_id <= new_id)
7219 			break;
7220 		higher = &pos->dev_list;
7221 	}
7222 	list_add_rcu(&napi->dev_list, higher); /* adds after higher */
7223 }
7224 
7225 /* Double check that napi_get_frags() allocates skbs with
7226  * skb->head being backed by slab, not a page fragment.
7227  * This is to make sure bug fixed in 3226b158e67c
7228  * ("net: avoid 32 x truesize under-estimation for tiny skbs")
7229  * does not accidentally come back.
7230  */
napi_get_frags_check(struct napi_struct * napi)7231 static void napi_get_frags_check(struct napi_struct *napi)
7232 {
7233 	struct sk_buff *skb;
7234 
7235 	local_bh_disable();
7236 	skb = napi_get_frags(napi);
7237 	WARN_ON_ONCE(skb && skb->head_frag);
7238 	napi_free_frags(napi);
7239 	local_bh_enable();
7240 }
7241 
netif_napi_add_weight_locked(struct net_device * dev,struct napi_struct * napi,int (* poll)(struct napi_struct *,int),int weight)7242 void netif_napi_add_weight_locked(struct net_device *dev,
7243 				  struct napi_struct *napi,
7244 				  int (*poll)(struct napi_struct *, int),
7245 				  int weight)
7246 {
7247 	netdev_assert_locked(dev);
7248 	if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
7249 		return;
7250 
7251 	INIT_LIST_HEAD(&napi->poll_list);
7252 	INIT_HLIST_NODE(&napi->napi_hash_node);
7253 	hrtimer_setup(&napi->timer, napi_watchdog, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
7254 	gro_init(&napi->gro);
7255 	napi->skb = NULL;
7256 	napi->poll = poll;
7257 	if (weight > NAPI_POLL_WEIGHT)
7258 		netdev_err_once(dev, "%s() called with weight %d\n", __func__,
7259 				weight);
7260 	napi->weight = weight;
7261 	napi->dev = dev;
7262 #ifdef CONFIG_NETPOLL
7263 	napi->poll_owner = -1;
7264 #endif
7265 	napi->list_owner = -1;
7266 	set_bit(NAPI_STATE_SCHED, &napi->state);
7267 	set_bit(NAPI_STATE_NPSVC, &napi->state);
7268 	netif_napi_dev_list_add(dev, napi);
7269 
7270 	/* default settings from sysfs are applied to all NAPIs. any per-NAPI
7271 	 * configuration will be loaded in napi_enable
7272 	 */
7273 	napi_set_defer_hard_irqs(napi, READ_ONCE(dev->napi_defer_hard_irqs));
7274 	napi_set_gro_flush_timeout(napi, READ_ONCE(dev->gro_flush_timeout));
7275 
7276 	napi_get_frags_check(napi);
7277 	/* Create kthread for this napi if dev->threaded is set.
7278 	 * Clear dev->threaded if kthread creation failed so that
7279 	 * threaded mode will not be enabled in napi_enable().
7280 	 */
7281 	if (dev->threaded && napi_kthread_create(napi))
7282 		dev->threaded = false;
7283 	netif_napi_set_irq_locked(napi, -1);
7284 }
7285 EXPORT_SYMBOL(netif_napi_add_weight_locked);
7286 
napi_disable_locked(struct napi_struct * n)7287 void napi_disable_locked(struct napi_struct *n)
7288 {
7289 	unsigned long val, new;
7290 
7291 	might_sleep();
7292 	netdev_assert_locked(n->dev);
7293 
7294 	set_bit(NAPI_STATE_DISABLE, &n->state);
7295 
7296 	val = READ_ONCE(n->state);
7297 	do {
7298 		while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
7299 			usleep_range(20, 200);
7300 			val = READ_ONCE(n->state);
7301 		}
7302 
7303 		new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
7304 		new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
7305 	} while (!try_cmpxchg(&n->state, &val, new));
7306 
7307 	hrtimer_cancel(&n->timer);
7308 
7309 	if (n->config)
7310 		napi_save_config(n);
7311 	else
7312 		napi_hash_del(n);
7313 
7314 	clear_bit(NAPI_STATE_DISABLE, &n->state);
7315 }
7316 EXPORT_SYMBOL(napi_disable_locked);
7317 
7318 /**
7319  * napi_disable() - prevent NAPI from scheduling
7320  * @n: NAPI context
7321  *
7322  * Stop NAPI from being scheduled on this context.
7323  * Waits till any outstanding processing completes.
7324  * Takes netdev_lock() for associated net_device.
7325  */
napi_disable(struct napi_struct * n)7326 void napi_disable(struct napi_struct *n)
7327 {
7328 	netdev_lock(n->dev);
7329 	napi_disable_locked(n);
7330 	netdev_unlock(n->dev);
7331 }
7332 EXPORT_SYMBOL(napi_disable);
7333 
napi_enable_locked(struct napi_struct * n)7334 void napi_enable_locked(struct napi_struct *n)
7335 {
7336 	unsigned long new, val = READ_ONCE(n->state);
7337 
7338 	if (n->config)
7339 		napi_restore_config(n);
7340 	else
7341 		napi_hash_add(n);
7342 
7343 	do {
7344 		BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
7345 
7346 		new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
7347 		if (n->dev->threaded && n->thread)
7348 			new |= NAPIF_STATE_THREADED;
7349 	} while (!try_cmpxchg(&n->state, &val, new));
7350 }
7351 EXPORT_SYMBOL(napi_enable_locked);
7352 
7353 /**
7354  * napi_enable() - enable NAPI scheduling
7355  * @n: NAPI context
7356  *
7357  * Enable scheduling of a NAPI instance.
7358  * Must be paired with napi_disable().
7359  * Takes netdev_lock() for associated net_device.
7360  */
napi_enable(struct napi_struct * n)7361 void napi_enable(struct napi_struct *n)
7362 {
7363 	netdev_lock(n->dev);
7364 	napi_enable_locked(n);
7365 	netdev_unlock(n->dev);
7366 }
7367 EXPORT_SYMBOL(napi_enable);
7368 
7369 /* Must be called in process context */
__netif_napi_del_locked(struct napi_struct * napi)7370 void __netif_napi_del_locked(struct napi_struct *napi)
7371 {
7372 	netdev_assert_locked(napi->dev);
7373 
7374 	if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
7375 		return;
7376 
7377 	/* Make sure NAPI is disabled (or was never enabled). */
7378 	WARN_ON(!test_bit(NAPI_STATE_SCHED, &napi->state));
7379 
7380 	if (test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state))
7381 		irq_set_affinity_notifier(napi->irq, NULL);
7382 
7383 	if (napi->config) {
7384 		napi->index = -1;
7385 		napi->config = NULL;
7386 	}
7387 
7388 	list_del_rcu(&napi->dev_list);
7389 	napi_free_frags(napi);
7390 
7391 	gro_cleanup(&napi->gro);
7392 
7393 	if (napi->thread) {
7394 		kthread_stop(napi->thread);
7395 		napi->thread = NULL;
7396 	}
7397 }
7398 EXPORT_SYMBOL(__netif_napi_del_locked);
7399 
__napi_poll(struct napi_struct * n,bool * repoll)7400 static int __napi_poll(struct napi_struct *n, bool *repoll)
7401 {
7402 	int work, weight;
7403 
7404 	weight = n->weight;
7405 
7406 	/* This NAPI_STATE_SCHED test is for avoiding a race
7407 	 * with netpoll's poll_napi().  Only the entity which
7408 	 * obtains the lock and sees NAPI_STATE_SCHED set will
7409 	 * actually make the ->poll() call.  Therefore we avoid
7410 	 * accidentally calling ->poll() when NAPI is not scheduled.
7411 	 */
7412 	work = 0;
7413 	if (napi_is_scheduled(n)) {
7414 		work = n->poll(n, weight);
7415 		trace_napi_poll(n, work, weight);
7416 
7417 		xdp_do_check_flushed(n);
7418 	}
7419 
7420 	if (unlikely(work > weight))
7421 		netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
7422 				n->poll, work, weight);
7423 
7424 	if (likely(work < weight))
7425 		return work;
7426 
7427 	/* Drivers must not modify the NAPI state if they
7428 	 * consume the entire weight.  In such cases this code
7429 	 * still "owns" the NAPI instance and therefore can
7430 	 * move the instance around on the list at-will.
7431 	 */
7432 	if (unlikely(napi_disable_pending(n))) {
7433 		napi_complete(n);
7434 		return work;
7435 	}
7436 
7437 	/* The NAPI context has more processing work, but busy-polling
7438 	 * is preferred. Exit early.
7439 	 */
7440 	if (napi_prefer_busy_poll(n)) {
7441 		if (napi_complete_done(n, work)) {
7442 			/* If timeout is not set, we need to make sure
7443 			 * that the NAPI is re-scheduled.
7444 			 */
7445 			napi_schedule(n);
7446 		}
7447 		return work;
7448 	}
7449 
7450 	/* Flush too old packets. If HZ < 1000, flush all packets */
7451 	gro_flush(&n->gro, HZ >= 1000);
7452 	gro_normal_list(&n->gro);
7453 
7454 	/* Some drivers may have called napi_schedule
7455 	 * prior to exhausting their budget.
7456 	 */
7457 	if (unlikely(!list_empty(&n->poll_list))) {
7458 		pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
7459 			     n->dev ? n->dev->name : "backlog");
7460 		return work;
7461 	}
7462 
7463 	*repoll = true;
7464 
7465 	return work;
7466 }
7467 
napi_poll(struct napi_struct * n,struct list_head * repoll)7468 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
7469 {
7470 	bool do_repoll = false;
7471 	void *have;
7472 	int work;
7473 
7474 	list_del_init(&n->poll_list);
7475 
7476 	have = netpoll_poll_lock(n);
7477 
7478 	work = __napi_poll(n, &do_repoll);
7479 
7480 	if (do_repoll) {
7481 #if defined(CONFIG_DEBUG_NET)
7482 		if (unlikely(!napi_is_scheduled(n)))
7483 			pr_crit("repoll requested for device %s %ps but napi is not scheduled.\n",
7484 				n->dev->name, n->poll);
7485 #endif
7486 		list_add_tail(&n->poll_list, repoll);
7487 	}
7488 	netpoll_poll_unlock(have);
7489 
7490 	return work;
7491 }
7492 
napi_thread_wait(struct napi_struct * napi)7493 static int napi_thread_wait(struct napi_struct *napi)
7494 {
7495 	set_current_state(TASK_INTERRUPTIBLE);
7496 
7497 	while (!kthread_should_stop()) {
7498 		/* Testing SCHED_THREADED bit here to make sure the current
7499 		 * kthread owns this napi and could poll on this napi.
7500 		 * Testing SCHED bit is not enough because SCHED bit might be
7501 		 * set by some other busy poll thread or by napi_disable().
7502 		 */
7503 		if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) {
7504 			WARN_ON(!list_empty(&napi->poll_list));
7505 			__set_current_state(TASK_RUNNING);
7506 			return 0;
7507 		}
7508 
7509 		schedule();
7510 		set_current_state(TASK_INTERRUPTIBLE);
7511 	}
7512 	__set_current_state(TASK_RUNNING);
7513 
7514 	return -1;
7515 }
7516 
napi_threaded_poll_loop(struct napi_struct * napi)7517 static void napi_threaded_poll_loop(struct napi_struct *napi)
7518 {
7519 	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
7520 	struct softnet_data *sd;
7521 	unsigned long last_qs = jiffies;
7522 
7523 	for (;;) {
7524 		bool repoll = false;
7525 		void *have;
7526 
7527 		local_bh_disable();
7528 		bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
7529 
7530 		sd = this_cpu_ptr(&softnet_data);
7531 		sd->in_napi_threaded_poll = true;
7532 
7533 		have = netpoll_poll_lock(napi);
7534 		__napi_poll(napi, &repoll);
7535 		netpoll_poll_unlock(have);
7536 
7537 		sd->in_napi_threaded_poll = false;
7538 		barrier();
7539 
7540 		if (sd_has_rps_ipi_waiting(sd)) {
7541 			local_irq_disable();
7542 			net_rps_action_and_irq_enable(sd);
7543 		}
7544 		skb_defer_free_flush(sd);
7545 		bpf_net_ctx_clear(bpf_net_ctx);
7546 		local_bh_enable();
7547 
7548 		if (!repoll)
7549 			break;
7550 
7551 		rcu_softirq_qs_periodic(last_qs);
7552 		cond_resched();
7553 	}
7554 }
7555 
napi_threaded_poll(void * data)7556 static int napi_threaded_poll(void *data)
7557 {
7558 	struct napi_struct *napi = data;
7559 
7560 	while (!napi_thread_wait(napi))
7561 		napi_threaded_poll_loop(napi);
7562 
7563 	return 0;
7564 }
7565 
net_rx_action(void)7566 static __latent_entropy void net_rx_action(void)
7567 {
7568 	struct softnet_data *sd = this_cpu_ptr(&softnet_data);
7569 	unsigned long time_limit = jiffies +
7570 		usecs_to_jiffies(READ_ONCE(net_hotdata.netdev_budget_usecs));
7571 	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
7572 	int budget = READ_ONCE(net_hotdata.netdev_budget);
7573 	LIST_HEAD(list);
7574 	LIST_HEAD(repoll);
7575 
7576 	bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
7577 start:
7578 	sd->in_net_rx_action = true;
7579 	local_irq_disable();
7580 	list_splice_init(&sd->poll_list, &list);
7581 	local_irq_enable();
7582 
7583 	for (;;) {
7584 		struct napi_struct *n;
7585 
7586 		skb_defer_free_flush(sd);
7587 
7588 		if (list_empty(&list)) {
7589 			if (list_empty(&repoll)) {
7590 				sd->in_net_rx_action = false;
7591 				barrier();
7592 				/* We need to check if ____napi_schedule()
7593 				 * had refilled poll_list while
7594 				 * sd->in_net_rx_action was true.
7595 				 */
7596 				if (!list_empty(&sd->poll_list))
7597 					goto start;
7598 				if (!sd_has_rps_ipi_waiting(sd))
7599 					goto end;
7600 			}
7601 			break;
7602 		}
7603 
7604 		n = list_first_entry(&list, struct napi_struct, poll_list);
7605 		budget -= napi_poll(n, &repoll);
7606 
7607 		/* If softirq window is exhausted then punt.
7608 		 * Allow this to run for 2 jiffies since which will allow
7609 		 * an average latency of 1.5/HZ.
7610 		 */
7611 		if (unlikely(budget <= 0 ||
7612 			     time_after_eq(jiffies, time_limit))) {
7613 			/* Pairs with READ_ONCE() in softnet_seq_show() */
7614 			WRITE_ONCE(sd->time_squeeze, sd->time_squeeze + 1);
7615 			break;
7616 		}
7617 	}
7618 
7619 	local_irq_disable();
7620 
7621 	list_splice_tail_init(&sd->poll_list, &list);
7622 	list_splice_tail(&repoll, &list);
7623 	list_splice(&list, &sd->poll_list);
7624 	if (!list_empty(&sd->poll_list))
7625 		__raise_softirq_irqoff(NET_RX_SOFTIRQ);
7626 	else
7627 		sd->in_net_rx_action = false;
7628 
7629 	net_rps_action_and_irq_enable(sd);
7630 end:
7631 	bpf_net_ctx_clear(bpf_net_ctx);
7632 }
7633 
7634 struct netdev_adjacent {
7635 	struct net_device *dev;
7636 	netdevice_tracker dev_tracker;
7637 
7638 	/* upper master flag, there can only be one master device per list */
7639 	bool master;
7640 
7641 	/* lookup ignore flag */
7642 	bool ignore;
7643 
7644 	/* counter for the number of times this device was added to us */
7645 	u16 ref_nr;
7646 
7647 	/* private field for the users */
7648 	void *private;
7649 
7650 	struct list_head list;
7651 	struct rcu_head rcu;
7652 };
7653 
__netdev_find_adj(struct net_device * adj_dev,struct list_head * adj_list)7654 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
7655 						 struct list_head *adj_list)
7656 {
7657 	struct netdev_adjacent *adj;
7658 
7659 	list_for_each_entry(adj, adj_list, list) {
7660 		if (adj->dev == adj_dev)
7661 			return adj;
7662 	}
7663 	return NULL;
7664 }
7665 
____netdev_has_upper_dev(struct net_device * upper_dev,struct netdev_nested_priv * priv)7666 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
7667 				    struct netdev_nested_priv *priv)
7668 {
7669 	struct net_device *dev = (struct net_device *)priv->data;
7670 
7671 	return upper_dev == dev;
7672 }
7673 
7674 /**
7675  * netdev_has_upper_dev - Check if device is linked to an upper device
7676  * @dev: device
7677  * @upper_dev: upper device to check
7678  *
7679  * Find out if a device is linked to specified upper device and return true
7680  * in case it is. Note that this checks only immediate upper device,
7681  * not through a complete stack of devices. The caller must hold the RTNL lock.
7682  */
netdev_has_upper_dev(struct net_device * dev,struct net_device * upper_dev)7683 bool netdev_has_upper_dev(struct net_device *dev,
7684 			  struct net_device *upper_dev)
7685 {
7686 	struct netdev_nested_priv priv = {
7687 		.data = (void *)upper_dev,
7688 	};
7689 
7690 	ASSERT_RTNL();
7691 
7692 	return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
7693 					     &priv);
7694 }
7695 EXPORT_SYMBOL(netdev_has_upper_dev);
7696 
7697 /**
7698  * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
7699  * @dev: device
7700  * @upper_dev: upper device to check
7701  *
7702  * Find out if a device is linked to specified upper device and return true
7703  * in case it is. Note that this checks the entire upper device chain.
7704  * The caller must hold rcu lock.
7705  */
7706 
netdev_has_upper_dev_all_rcu(struct net_device * dev,struct net_device * upper_dev)7707 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
7708 				  struct net_device *upper_dev)
7709 {
7710 	struct netdev_nested_priv priv = {
7711 		.data = (void *)upper_dev,
7712 	};
7713 
7714 	return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
7715 					       &priv);
7716 }
7717 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
7718 
7719 /**
7720  * netdev_has_any_upper_dev - Check if device is linked to some device
7721  * @dev: device
7722  *
7723  * Find out if a device is linked to an upper device and return true in case
7724  * it is. The caller must hold the RTNL lock.
7725  */
netdev_has_any_upper_dev(struct net_device * dev)7726 bool netdev_has_any_upper_dev(struct net_device *dev)
7727 {
7728 	ASSERT_RTNL();
7729 
7730 	return !list_empty(&dev->adj_list.upper);
7731 }
7732 EXPORT_SYMBOL(netdev_has_any_upper_dev);
7733 
7734 /**
7735  * netdev_master_upper_dev_get - Get master upper device
7736  * @dev: device
7737  *
7738  * Find a master upper device and return pointer to it or NULL in case
7739  * it's not there. The caller must hold the RTNL lock.
7740  */
netdev_master_upper_dev_get(struct net_device * dev)7741 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
7742 {
7743 	struct netdev_adjacent *upper;
7744 
7745 	ASSERT_RTNL();
7746 
7747 	if (list_empty(&dev->adj_list.upper))
7748 		return NULL;
7749 
7750 	upper = list_first_entry(&dev->adj_list.upper,
7751 				 struct netdev_adjacent, list);
7752 	if (likely(upper->master))
7753 		return upper->dev;
7754 	return NULL;
7755 }
7756 EXPORT_SYMBOL(netdev_master_upper_dev_get);
7757 
__netdev_master_upper_dev_get(struct net_device * dev)7758 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
7759 {
7760 	struct netdev_adjacent *upper;
7761 
7762 	ASSERT_RTNL();
7763 
7764 	if (list_empty(&dev->adj_list.upper))
7765 		return NULL;
7766 
7767 	upper = list_first_entry(&dev->adj_list.upper,
7768 				 struct netdev_adjacent, list);
7769 	if (likely(upper->master) && !upper->ignore)
7770 		return upper->dev;
7771 	return NULL;
7772 }
7773 
7774 /**
7775  * netdev_has_any_lower_dev - Check if device is linked to some device
7776  * @dev: device
7777  *
7778  * Find out if a device is linked to a lower device and return true in case
7779  * it is. The caller must hold the RTNL lock.
7780  */
netdev_has_any_lower_dev(struct net_device * dev)7781 static bool netdev_has_any_lower_dev(struct net_device *dev)
7782 {
7783 	ASSERT_RTNL();
7784 
7785 	return !list_empty(&dev->adj_list.lower);
7786 }
7787 
netdev_adjacent_get_private(struct list_head * adj_list)7788 void *netdev_adjacent_get_private(struct list_head *adj_list)
7789 {
7790 	struct netdev_adjacent *adj;
7791 
7792 	adj = list_entry(adj_list, struct netdev_adjacent, list);
7793 
7794 	return adj->private;
7795 }
7796 EXPORT_SYMBOL(netdev_adjacent_get_private);
7797 
7798 /**
7799  * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
7800  * @dev: device
7801  * @iter: list_head ** of the current position
7802  *
7803  * Gets the next device from the dev's upper list, starting from iter
7804  * position. The caller must hold RCU read lock.
7805  */
netdev_upper_get_next_dev_rcu(struct net_device * dev,struct list_head ** iter)7806 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
7807 						 struct list_head **iter)
7808 {
7809 	struct netdev_adjacent *upper;
7810 
7811 	WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7812 
7813 	upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7814 
7815 	if (&upper->list == &dev->adj_list.upper)
7816 		return NULL;
7817 
7818 	*iter = &upper->list;
7819 
7820 	return upper->dev;
7821 }
7822 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
7823 
__netdev_next_upper_dev(struct net_device * dev,struct list_head ** iter,bool * ignore)7824 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
7825 						  struct list_head **iter,
7826 						  bool *ignore)
7827 {
7828 	struct netdev_adjacent *upper;
7829 
7830 	upper = list_entry((*iter)->next, struct netdev_adjacent, list);
7831 
7832 	if (&upper->list == &dev->adj_list.upper)
7833 		return NULL;
7834 
7835 	*iter = &upper->list;
7836 	*ignore = upper->ignore;
7837 
7838 	return upper->dev;
7839 }
7840 
netdev_next_upper_dev_rcu(struct net_device * dev,struct list_head ** iter)7841 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
7842 						    struct list_head **iter)
7843 {
7844 	struct netdev_adjacent *upper;
7845 
7846 	WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7847 
7848 	upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7849 
7850 	if (&upper->list == &dev->adj_list.upper)
7851 		return NULL;
7852 
7853 	*iter = &upper->list;
7854 
7855 	return upper->dev;
7856 }
7857 
__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)7858 static int __netdev_walk_all_upper_dev(struct net_device *dev,
7859 				       int (*fn)(struct net_device *dev,
7860 					 struct netdev_nested_priv *priv),
7861 				       struct netdev_nested_priv *priv)
7862 {
7863 	struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7864 	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7865 	int ret, cur = 0;
7866 	bool ignore;
7867 
7868 	now = dev;
7869 	iter = &dev->adj_list.upper;
7870 
7871 	while (1) {
7872 		if (now != dev) {
7873 			ret = fn(now, priv);
7874 			if (ret)
7875 				return ret;
7876 		}
7877 
7878 		next = NULL;
7879 		while (1) {
7880 			udev = __netdev_next_upper_dev(now, &iter, &ignore);
7881 			if (!udev)
7882 				break;
7883 			if (ignore)
7884 				continue;
7885 
7886 			next = udev;
7887 			niter = &udev->adj_list.upper;
7888 			dev_stack[cur] = now;
7889 			iter_stack[cur++] = iter;
7890 			break;
7891 		}
7892 
7893 		if (!next) {
7894 			if (!cur)
7895 				return 0;
7896 			next = dev_stack[--cur];
7897 			niter = iter_stack[cur];
7898 		}
7899 
7900 		now = next;
7901 		iter = niter;
7902 	}
7903 
7904 	return 0;
7905 }
7906 
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)7907 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
7908 				  int (*fn)(struct net_device *dev,
7909 					    struct netdev_nested_priv *priv),
7910 				  struct netdev_nested_priv *priv)
7911 {
7912 	struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7913 	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7914 	int ret, cur = 0;
7915 
7916 	now = dev;
7917 	iter = &dev->adj_list.upper;
7918 
7919 	while (1) {
7920 		if (now != dev) {
7921 			ret = fn(now, priv);
7922 			if (ret)
7923 				return ret;
7924 		}
7925 
7926 		next = NULL;
7927 		while (1) {
7928 			udev = netdev_next_upper_dev_rcu(now, &iter);
7929 			if (!udev)
7930 				break;
7931 
7932 			next = udev;
7933 			niter = &udev->adj_list.upper;
7934 			dev_stack[cur] = now;
7935 			iter_stack[cur++] = iter;
7936 			break;
7937 		}
7938 
7939 		if (!next) {
7940 			if (!cur)
7941 				return 0;
7942 			next = dev_stack[--cur];
7943 			niter = iter_stack[cur];
7944 		}
7945 
7946 		now = next;
7947 		iter = niter;
7948 	}
7949 
7950 	return 0;
7951 }
7952 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7953 
__netdev_has_upper_dev(struct net_device * dev,struct net_device * upper_dev)7954 static bool __netdev_has_upper_dev(struct net_device *dev,
7955 				   struct net_device *upper_dev)
7956 {
7957 	struct netdev_nested_priv priv = {
7958 		.flags = 0,
7959 		.data = (void *)upper_dev,
7960 	};
7961 
7962 	ASSERT_RTNL();
7963 
7964 	return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7965 					   &priv);
7966 }
7967 
7968 /**
7969  * netdev_lower_get_next_private - Get the next ->private from the
7970  *				   lower neighbour list
7971  * @dev: device
7972  * @iter: list_head ** of the current position
7973  *
7974  * Gets the next netdev_adjacent->private from the dev's lower neighbour
7975  * list, starting from iter position. The caller must hold either hold the
7976  * RTNL lock or its own locking that guarantees that the neighbour lower
7977  * list will remain unchanged.
7978  */
netdev_lower_get_next_private(struct net_device * dev,struct list_head ** iter)7979 void *netdev_lower_get_next_private(struct net_device *dev,
7980 				    struct list_head **iter)
7981 {
7982 	struct netdev_adjacent *lower;
7983 
7984 	lower = list_entry(*iter, struct netdev_adjacent, list);
7985 
7986 	if (&lower->list == &dev->adj_list.lower)
7987 		return NULL;
7988 
7989 	*iter = lower->list.next;
7990 
7991 	return lower->private;
7992 }
7993 EXPORT_SYMBOL(netdev_lower_get_next_private);
7994 
7995 /**
7996  * netdev_lower_get_next_private_rcu - Get the next ->private from the
7997  *				       lower neighbour list, RCU
7998  *				       variant
7999  * @dev: device
8000  * @iter: list_head ** of the current position
8001  *
8002  * Gets the next netdev_adjacent->private from the dev's lower neighbour
8003  * list, starting from iter position. The caller must hold RCU read lock.
8004  */
netdev_lower_get_next_private_rcu(struct net_device * dev,struct list_head ** iter)8005 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
8006 					struct list_head **iter)
8007 {
8008 	struct netdev_adjacent *lower;
8009 
8010 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
8011 
8012 	lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
8013 
8014 	if (&lower->list == &dev->adj_list.lower)
8015 		return NULL;
8016 
8017 	*iter = &lower->list;
8018 
8019 	return lower->private;
8020 }
8021 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
8022 
8023 /**
8024  * netdev_lower_get_next - Get the next device from the lower neighbour
8025  *                         list
8026  * @dev: device
8027  * @iter: list_head ** of the current position
8028  *
8029  * Gets the next netdev_adjacent from the dev's lower neighbour
8030  * list, starting from iter position. The caller must hold RTNL lock or
8031  * its own locking that guarantees that the neighbour lower
8032  * list will remain unchanged.
8033  */
netdev_lower_get_next(struct net_device * dev,struct list_head ** iter)8034 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
8035 {
8036 	struct netdev_adjacent *lower;
8037 
8038 	lower = list_entry(*iter, struct netdev_adjacent, list);
8039 
8040 	if (&lower->list == &dev->adj_list.lower)
8041 		return NULL;
8042 
8043 	*iter = lower->list.next;
8044 
8045 	return lower->dev;
8046 }
8047 EXPORT_SYMBOL(netdev_lower_get_next);
8048 
netdev_next_lower_dev(struct net_device * dev,struct list_head ** iter)8049 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
8050 						struct list_head **iter)
8051 {
8052 	struct netdev_adjacent *lower;
8053 
8054 	lower = list_entry((*iter)->next, struct netdev_adjacent, list);
8055 
8056 	if (&lower->list == &dev->adj_list.lower)
8057 		return NULL;
8058 
8059 	*iter = &lower->list;
8060 
8061 	return lower->dev;
8062 }
8063 
__netdev_next_lower_dev(struct net_device * dev,struct list_head ** iter,bool * ignore)8064 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
8065 						  struct list_head **iter,
8066 						  bool *ignore)
8067 {
8068 	struct netdev_adjacent *lower;
8069 
8070 	lower = list_entry((*iter)->next, struct netdev_adjacent, list);
8071 
8072 	if (&lower->list == &dev->adj_list.lower)
8073 		return NULL;
8074 
8075 	*iter = &lower->list;
8076 	*ignore = lower->ignore;
8077 
8078 	return lower->dev;
8079 }
8080 
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)8081 int netdev_walk_all_lower_dev(struct net_device *dev,
8082 			      int (*fn)(struct net_device *dev,
8083 					struct netdev_nested_priv *priv),
8084 			      struct netdev_nested_priv *priv)
8085 {
8086 	struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
8087 	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
8088 	int ret, cur = 0;
8089 
8090 	now = dev;
8091 	iter = &dev->adj_list.lower;
8092 
8093 	while (1) {
8094 		if (now != dev) {
8095 			ret = fn(now, priv);
8096 			if (ret)
8097 				return ret;
8098 		}
8099 
8100 		next = NULL;
8101 		while (1) {
8102 			ldev = netdev_next_lower_dev(now, &iter);
8103 			if (!ldev)
8104 				break;
8105 
8106 			next = ldev;
8107 			niter = &ldev->adj_list.lower;
8108 			dev_stack[cur] = now;
8109 			iter_stack[cur++] = iter;
8110 			break;
8111 		}
8112 
8113 		if (!next) {
8114 			if (!cur)
8115 				return 0;
8116 			next = dev_stack[--cur];
8117 			niter = iter_stack[cur];
8118 		}
8119 
8120 		now = next;
8121 		iter = niter;
8122 	}
8123 
8124 	return 0;
8125 }
8126 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
8127 
__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)8128 static int __netdev_walk_all_lower_dev(struct net_device *dev,
8129 				       int (*fn)(struct net_device *dev,
8130 					 struct netdev_nested_priv *priv),
8131 				       struct netdev_nested_priv *priv)
8132 {
8133 	struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
8134 	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
8135 	int ret, cur = 0;
8136 	bool ignore;
8137 
8138 	now = dev;
8139 	iter = &dev->adj_list.lower;
8140 
8141 	while (1) {
8142 		if (now != dev) {
8143 			ret = fn(now, priv);
8144 			if (ret)
8145 				return ret;
8146 		}
8147 
8148 		next = NULL;
8149 		while (1) {
8150 			ldev = __netdev_next_lower_dev(now, &iter, &ignore);
8151 			if (!ldev)
8152 				break;
8153 			if (ignore)
8154 				continue;
8155 
8156 			next = ldev;
8157 			niter = &ldev->adj_list.lower;
8158 			dev_stack[cur] = now;
8159 			iter_stack[cur++] = iter;
8160 			break;
8161 		}
8162 
8163 		if (!next) {
8164 			if (!cur)
8165 				return 0;
8166 			next = dev_stack[--cur];
8167 			niter = iter_stack[cur];
8168 		}
8169 
8170 		now = next;
8171 		iter = niter;
8172 	}
8173 
8174 	return 0;
8175 }
8176 
netdev_next_lower_dev_rcu(struct net_device * dev,struct list_head ** iter)8177 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
8178 					     struct list_head **iter)
8179 {
8180 	struct netdev_adjacent *lower;
8181 
8182 	lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
8183 	if (&lower->list == &dev->adj_list.lower)
8184 		return NULL;
8185 
8186 	*iter = &lower->list;
8187 
8188 	return lower->dev;
8189 }
8190 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
8191 
__netdev_upper_depth(struct net_device * dev)8192 static u8 __netdev_upper_depth(struct net_device *dev)
8193 {
8194 	struct net_device *udev;
8195 	struct list_head *iter;
8196 	u8 max_depth = 0;
8197 	bool ignore;
8198 
8199 	for (iter = &dev->adj_list.upper,
8200 	     udev = __netdev_next_upper_dev(dev, &iter, &ignore);
8201 	     udev;
8202 	     udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
8203 		if (ignore)
8204 			continue;
8205 		if (max_depth < udev->upper_level)
8206 			max_depth = udev->upper_level;
8207 	}
8208 
8209 	return max_depth;
8210 }
8211 
__netdev_lower_depth(struct net_device * dev)8212 static u8 __netdev_lower_depth(struct net_device *dev)
8213 {
8214 	struct net_device *ldev;
8215 	struct list_head *iter;
8216 	u8 max_depth = 0;
8217 	bool ignore;
8218 
8219 	for (iter = &dev->adj_list.lower,
8220 	     ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
8221 	     ldev;
8222 	     ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
8223 		if (ignore)
8224 			continue;
8225 		if (max_depth < ldev->lower_level)
8226 			max_depth = ldev->lower_level;
8227 	}
8228 
8229 	return max_depth;
8230 }
8231 
__netdev_update_upper_level(struct net_device * dev,struct netdev_nested_priv * __unused)8232 static int __netdev_update_upper_level(struct net_device *dev,
8233 				       struct netdev_nested_priv *__unused)
8234 {
8235 	dev->upper_level = __netdev_upper_depth(dev) + 1;
8236 	return 0;
8237 }
8238 
8239 #ifdef CONFIG_LOCKDEP
8240 static LIST_HEAD(net_unlink_list);
8241 
net_unlink_todo(struct net_device * dev)8242 static void net_unlink_todo(struct net_device *dev)
8243 {
8244 	if (list_empty(&dev->unlink_list))
8245 		list_add_tail(&dev->unlink_list, &net_unlink_list);
8246 }
8247 #endif
8248 
__netdev_update_lower_level(struct net_device * dev,struct netdev_nested_priv * priv)8249 static int __netdev_update_lower_level(struct net_device *dev,
8250 				       struct netdev_nested_priv *priv)
8251 {
8252 	dev->lower_level = __netdev_lower_depth(dev) + 1;
8253 
8254 #ifdef CONFIG_LOCKDEP
8255 	if (!priv)
8256 		return 0;
8257 
8258 	if (priv->flags & NESTED_SYNC_IMM)
8259 		dev->nested_level = dev->lower_level - 1;
8260 	if (priv->flags & NESTED_SYNC_TODO)
8261 		net_unlink_todo(dev);
8262 #endif
8263 	return 0;
8264 }
8265 
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)8266 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
8267 				  int (*fn)(struct net_device *dev,
8268 					    struct netdev_nested_priv *priv),
8269 				  struct netdev_nested_priv *priv)
8270 {
8271 	struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
8272 	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
8273 	int ret, cur = 0;
8274 
8275 	now = dev;
8276 	iter = &dev->adj_list.lower;
8277 
8278 	while (1) {
8279 		if (now != dev) {
8280 			ret = fn(now, priv);
8281 			if (ret)
8282 				return ret;
8283 		}
8284 
8285 		next = NULL;
8286 		while (1) {
8287 			ldev = netdev_next_lower_dev_rcu(now, &iter);
8288 			if (!ldev)
8289 				break;
8290 
8291 			next = ldev;
8292 			niter = &ldev->adj_list.lower;
8293 			dev_stack[cur] = now;
8294 			iter_stack[cur++] = iter;
8295 			break;
8296 		}
8297 
8298 		if (!next) {
8299 			if (!cur)
8300 				return 0;
8301 			next = dev_stack[--cur];
8302 			niter = iter_stack[cur];
8303 		}
8304 
8305 		now = next;
8306 		iter = niter;
8307 	}
8308 
8309 	return 0;
8310 }
8311 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
8312 
8313 /**
8314  * netdev_lower_get_first_private_rcu - Get the first ->private from the
8315  *				       lower neighbour list, RCU
8316  *				       variant
8317  * @dev: device
8318  *
8319  * Gets the first netdev_adjacent->private from the dev's lower neighbour
8320  * list. The caller must hold RCU read lock.
8321  */
netdev_lower_get_first_private_rcu(struct net_device * dev)8322 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
8323 {
8324 	struct netdev_adjacent *lower;
8325 
8326 	lower = list_first_or_null_rcu(&dev->adj_list.lower,
8327 			struct netdev_adjacent, list);
8328 	if (lower)
8329 		return lower->private;
8330 	return NULL;
8331 }
8332 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
8333 
8334 /**
8335  * netdev_master_upper_dev_get_rcu - Get master upper device
8336  * @dev: device
8337  *
8338  * Find a master upper device and return pointer to it or NULL in case
8339  * it's not there. The caller must hold the RCU read lock.
8340  */
netdev_master_upper_dev_get_rcu(struct net_device * dev)8341 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
8342 {
8343 	struct netdev_adjacent *upper;
8344 
8345 	upper = list_first_or_null_rcu(&dev->adj_list.upper,
8346 				       struct netdev_adjacent, list);
8347 	if (upper && likely(upper->master))
8348 		return upper->dev;
8349 	return NULL;
8350 }
8351 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
8352 
netdev_adjacent_sysfs_add(struct net_device * dev,struct net_device * adj_dev,struct list_head * dev_list)8353 static int netdev_adjacent_sysfs_add(struct net_device *dev,
8354 			      struct net_device *adj_dev,
8355 			      struct list_head *dev_list)
8356 {
8357 	char linkname[IFNAMSIZ+7];
8358 
8359 	sprintf(linkname, dev_list == &dev->adj_list.upper ?
8360 		"upper_%s" : "lower_%s", adj_dev->name);
8361 	return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
8362 				 linkname);
8363 }
netdev_adjacent_sysfs_del(struct net_device * dev,char * name,struct list_head * dev_list)8364 static void netdev_adjacent_sysfs_del(struct net_device *dev,
8365 			       char *name,
8366 			       struct list_head *dev_list)
8367 {
8368 	char linkname[IFNAMSIZ+7];
8369 
8370 	sprintf(linkname, dev_list == &dev->adj_list.upper ?
8371 		"upper_%s" : "lower_%s", name);
8372 	sysfs_remove_link(&(dev->dev.kobj), linkname);
8373 }
8374 
netdev_adjacent_is_neigh_list(struct net_device * dev,struct net_device * adj_dev,struct list_head * dev_list)8375 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
8376 						 struct net_device *adj_dev,
8377 						 struct list_head *dev_list)
8378 {
8379 	return (dev_list == &dev->adj_list.upper ||
8380 		dev_list == &dev->adj_list.lower) &&
8381 		net_eq(dev_net(dev), dev_net(adj_dev));
8382 }
8383 
__netdev_adjacent_dev_insert(struct net_device * dev,struct net_device * adj_dev,struct list_head * dev_list,void * private,bool master)8384 static int __netdev_adjacent_dev_insert(struct net_device *dev,
8385 					struct net_device *adj_dev,
8386 					struct list_head *dev_list,
8387 					void *private, bool master)
8388 {
8389 	struct netdev_adjacent *adj;
8390 	int ret;
8391 
8392 	adj = __netdev_find_adj(adj_dev, dev_list);
8393 
8394 	if (adj) {
8395 		adj->ref_nr += 1;
8396 		pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
8397 			 dev->name, adj_dev->name, adj->ref_nr);
8398 
8399 		return 0;
8400 	}
8401 
8402 	adj = kmalloc(sizeof(*adj), GFP_KERNEL);
8403 	if (!adj)
8404 		return -ENOMEM;
8405 
8406 	adj->dev = adj_dev;
8407 	adj->master = master;
8408 	adj->ref_nr = 1;
8409 	adj->private = private;
8410 	adj->ignore = false;
8411 	netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL);
8412 
8413 	pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
8414 		 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
8415 
8416 	if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
8417 		ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
8418 		if (ret)
8419 			goto free_adj;
8420 	}
8421 
8422 	/* Ensure that master link is always the first item in list. */
8423 	if (master) {
8424 		ret = sysfs_create_link(&(dev->dev.kobj),
8425 					&(adj_dev->dev.kobj), "master");
8426 		if (ret)
8427 			goto remove_symlinks;
8428 
8429 		list_add_rcu(&adj->list, dev_list);
8430 	} else {
8431 		list_add_tail_rcu(&adj->list, dev_list);
8432 	}
8433 
8434 	return 0;
8435 
8436 remove_symlinks:
8437 	if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
8438 		netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
8439 free_adj:
8440 	netdev_put(adj_dev, &adj->dev_tracker);
8441 	kfree(adj);
8442 
8443 	return ret;
8444 }
8445 
__netdev_adjacent_dev_remove(struct net_device * dev,struct net_device * adj_dev,u16 ref_nr,struct list_head * dev_list)8446 static void __netdev_adjacent_dev_remove(struct net_device *dev,
8447 					 struct net_device *adj_dev,
8448 					 u16 ref_nr,
8449 					 struct list_head *dev_list)
8450 {
8451 	struct netdev_adjacent *adj;
8452 
8453 	pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
8454 		 dev->name, adj_dev->name, ref_nr);
8455 
8456 	adj = __netdev_find_adj(adj_dev, dev_list);
8457 
8458 	if (!adj) {
8459 		pr_err("Adjacency does not exist for device %s from %s\n",
8460 		       dev->name, adj_dev->name);
8461 		WARN_ON(1);
8462 		return;
8463 	}
8464 
8465 	if (adj->ref_nr > ref_nr) {
8466 		pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
8467 			 dev->name, adj_dev->name, ref_nr,
8468 			 adj->ref_nr - ref_nr);
8469 		adj->ref_nr -= ref_nr;
8470 		return;
8471 	}
8472 
8473 	if (adj->master)
8474 		sysfs_remove_link(&(dev->dev.kobj), "master");
8475 
8476 	if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
8477 		netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
8478 
8479 	list_del_rcu(&adj->list);
8480 	pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
8481 		 adj_dev->name, dev->name, adj_dev->name);
8482 	netdev_put(adj_dev, &adj->dev_tracker);
8483 	kfree_rcu(adj, rcu);
8484 }
8485 
__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)8486 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
8487 					    struct net_device *upper_dev,
8488 					    struct list_head *up_list,
8489 					    struct list_head *down_list,
8490 					    void *private, bool master)
8491 {
8492 	int ret;
8493 
8494 	ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
8495 					   private, master);
8496 	if (ret)
8497 		return ret;
8498 
8499 	ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
8500 					   private, false);
8501 	if (ret) {
8502 		__netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
8503 		return ret;
8504 	}
8505 
8506 	return 0;
8507 }
8508 
__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)8509 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
8510 					       struct net_device *upper_dev,
8511 					       u16 ref_nr,
8512 					       struct list_head *up_list,
8513 					       struct list_head *down_list)
8514 {
8515 	__netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
8516 	__netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
8517 }
8518 
__netdev_adjacent_dev_link_neighbour(struct net_device * dev,struct net_device * upper_dev,void * private,bool master)8519 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
8520 						struct net_device *upper_dev,
8521 						void *private, bool master)
8522 {
8523 	return __netdev_adjacent_dev_link_lists(dev, upper_dev,
8524 						&dev->adj_list.upper,
8525 						&upper_dev->adj_list.lower,
8526 						private, master);
8527 }
8528 
__netdev_adjacent_dev_unlink_neighbour(struct net_device * dev,struct net_device * upper_dev)8529 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
8530 						   struct net_device *upper_dev)
8531 {
8532 	__netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
8533 					   &dev->adj_list.upper,
8534 					   &upper_dev->adj_list.lower);
8535 }
8536 
__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)8537 static int __netdev_upper_dev_link(struct net_device *dev,
8538 				   struct net_device *upper_dev, bool master,
8539 				   void *upper_priv, void *upper_info,
8540 				   struct netdev_nested_priv *priv,
8541 				   struct netlink_ext_ack *extack)
8542 {
8543 	struct netdev_notifier_changeupper_info changeupper_info = {
8544 		.info = {
8545 			.dev = dev,
8546 			.extack = extack,
8547 		},
8548 		.upper_dev = upper_dev,
8549 		.master = master,
8550 		.linking = true,
8551 		.upper_info = upper_info,
8552 	};
8553 	struct net_device *master_dev;
8554 	int ret = 0;
8555 
8556 	ASSERT_RTNL();
8557 
8558 	if (dev == upper_dev)
8559 		return -EBUSY;
8560 
8561 	/* To prevent loops, check if dev is not upper device to upper_dev. */
8562 	if (__netdev_has_upper_dev(upper_dev, dev))
8563 		return -EBUSY;
8564 
8565 	if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
8566 		return -EMLINK;
8567 
8568 	if (!master) {
8569 		if (__netdev_has_upper_dev(dev, upper_dev))
8570 			return -EEXIST;
8571 	} else {
8572 		master_dev = __netdev_master_upper_dev_get(dev);
8573 		if (master_dev)
8574 			return master_dev == upper_dev ? -EEXIST : -EBUSY;
8575 	}
8576 
8577 	ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
8578 					    &changeupper_info.info);
8579 	ret = notifier_to_errno(ret);
8580 	if (ret)
8581 		return ret;
8582 
8583 	ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
8584 						   master);
8585 	if (ret)
8586 		return ret;
8587 
8588 	ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
8589 					    &changeupper_info.info);
8590 	ret = notifier_to_errno(ret);
8591 	if (ret)
8592 		goto rollback;
8593 
8594 	__netdev_update_upper_level(dev, NULL);
8595 	__netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
8596 
8597 	__netdev_update_lower_level(upper_dev, priv);
8598 	__netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
8599 				    priv);
8600 
8601 	return 0;
8602 
8603 rollback:
8604 	__netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
8605 
8606 	return ret;
8607 }
8608 
8609 /**
8610  * netdev_upper_dev_link - Add a link to the upper device
8611  * @dev: device
8612  * @upper_dev: new upper device
8613  * @extack: netlink extended ack
8614  *
8615  * Adds a link to device which is upper to this one. The caller must hold
8616  * the RTNL lock. On a failure a negative errno code is returned.
8617  * On success the reference counts are adjusted and the function
8618  * returns zero.
8619  */
netdev_upper_dev_link(struct net_device * dev,struct net_device * upper_dev,struct netlink_ext_ack * extack)8620 int netdev_upper_dev_link(struct net_device *dev,
8621 			  struct net_device *upper_dev,
8622 			  struct netlink_ext_ack *extack)
8623 {
8624 	struct netdev_nested_priv priv = {
8625 		.flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
8626 		.data = NULL,
8627 	};
8628 
8629 	return __netdev_upper_dev_link(dev, upper_dev, false,
8630 				       NULL, NULL, &priv, extack);
8631 }
8632 EXPORT_SYMBOL(netdev_upper_dev_link);
8633 
8634 /**
8635  * netdev_master_upper_dev_link - Add a master link to the upper device
8636  * @dev: device
8637  * @upper_dev: new upper device
8638  * @upper_priv: upper device private
8639  * @upper_info: upper info to be passed down via notifier
8640  * @extack: netlink extended ack
8641  *
8642  * Adds a link to device which is upper to this one. In this case, only
8643  * one master upper device can be linked, although other non-master devices
8644  * might be linked as well. The caller must hold the RTNL lock.
8645  * On a failure a negative errno code is returned. On success the reference
8646  * counts are adjusted and the function returns zero.
8647  */
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)8648 int netdev_master_upper_dev_link(struct net_device *dev,
8649 				 struct net_device *upper_dev,
8650 				 void *upper_priv, void *upper_info,
8651 				 struct netlink_ext_ack *extack)
8652 {
8653 	struct netdev_nested_priv priv = {
8654 		.flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
8655 		.data = NULL,
8656 	};
8657 
8658 	return __netdev_upper_dev_link(dev, upper_dev, true,
8659 				       upper_priv, upper_info, &priv, extack);
8660 }
8661 EXPORT_SYMBOL(netdev_master_upper_dev_link);
8662 
__netdev_upper_dev_unlink(struct net_device * dev,struct net_device * upper_dev,struct netdev_nested_priv * priv)8663 static void __netdev_upper_dev_unlink(struct net_device *dev,
8664 				      struct net_device *upper_dev,
8665 				      struct netdev_nested_priv *priv)
8666 {
8667 	struct netdev_notifier_changeupper_info changeupper_info = {
8668 		.info = {
8669 			.dev = dev,
8670 		},
8671 		.upper_dev = upper_dev,
8672 		.linking = false,
8673 	};
8674 
8675 	ASSERT_RTNL();
8676 
8677 	changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
8678 
8679 	call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
8680 				      &changeupper_info.info);
8681 
8682 	__netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
8683 
8684 	call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
8685 				      &changeupper_info.info);
8686 
8687 	__netdev_update_upper_level(dev, NULL);
8688 	__netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
8689 
8690 	__netdev_update_lower_level(upper_dev, priv);
8691 	__netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
8692 				    priv);
8693 }
8694 
8695 /**
8696  * netdev_upper_dev_unlink - Removes a link to upper device
8697  * @dev: device
8698  * @upper_dev: new upper device
8699  *
8700  * Removes a link to device which is upper to this one. The caller must hold
8701  * the RTNL lock.
8702  */
netdev_upper_dev_unlink(struct net_device * dev,struct net_device * upper_dev)8703 void netdev_upper_dev_unlink(struct net_device *dev,
8704 			     struct net_device *upper_dev)
8705 {
8706 	struct netdev_nested_priv priv = {
8707 		.flags = NESTED_SYNC_TODO,
8708 		.data = NULL,
8709 	};
8710 
8711 	__netdev_upper_dev_unlink(dev, upper_dev, &priv);
8712 }
8713 EXPORT_SYMBOL(netdev_upper_dev_unlink);
8714 
__netdev_adjacent_dev_set(struct net_device * upper_dev,struct net_device * lower_dev,bool val)8715 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
8716 				      struct net_device *lower_dev,
8717 				      bool val)
8718 {
8719 	struct netdev_adjacent *adj;
8720 
8721 	adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
8722 	if (adj)
8723 		adj->ignore = val;
8724 
8725 	adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
8726 	if (adj)
8727 		adj->ignore = val;
8728 }
8729 
netdev_adjacent_dev_disable(struct net_device * upper_dev,struct net_device * lower_dev)8730 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
8731 					struct net_device *lower_dev)
8732 {
8733 	__netdev_adjacent_dev_set(upper_dev, lower_dev, true);
8734 }
8735 
netdev_adjacent_dev_enable(struct net_device * upper_dev,struct net_device * lower_dev)8736 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
8737 				       struct net_device *lower_dev)
8738 {
8739 	__netdev_adjacent_dev_set(upper_dev, lower_dev, false);
8740 }
8741 
netdev_adjacent_change_prepare(struct net_device * old_dev,struct net_device * new_dev,struct net_device * dev,struct netlink_ext_ack * extack)8742 int netdev_adjacent_change_prepare(struct net_device *old_dev,
8743 				   struct net_device *new_dev,
8744 				   struct net_device *dev,
8745 				   struct netlink_ext_ack *extack)
8746 {
8747 	struct netdev_nested_priv priv = {
8748 		.flags = 0,
8749 		.data = NULL,
8750 	};
8751 	int err;
8752 
8753 	if (!new_dev)
8754 		return 0;
8755 
8756 	if (old_dev && new_dev != old_dev)
8757 		netdev_adjacent_dev_disable(dev, old_dev);
8758 	err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
8759 				      extack);
8760 	if (err) {
8761 		if (old_dev && new_dev != old_dev)
8762 			netdev_adjacent_dev_enable(dev, old_dev);
8763 		return err;
8764 	}
8765 
8766 	return 0;
8767 }
8768 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
8769 
netdev_adjacent_change_commit(struct net_device * old_dev,struct net_device * new_dev,struct net_device * dev)8770 void netdev_adjacent_change_commit(struct net_device *old_dev,
8771 				   struct net_device *new_dev,
8772 				   struct net_device *dev)
8773 {
8774 	struct netdev_nested_priv priv = {
8775 		.flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
8776 		.data = NULL,
8777 	};
8778 
8779 	if (!new_dev || !old_dev)
8780 		return;
8781 
8782 	if (new_dev == old_dev)
8783 		return;
8784 
8785 	netdev_adjacent_dev_enable(dev, old_dev);
8786 	__netdev_upper_dev_unlink(old_dev, dev, &priv);
8787 }
8788 EXPORT_SYMBOL(netdev_adjacent_change_commit);
8789 
netdev_adjacent_change_abort(struct net_device * old_dev,struct net_device * new_dev,struct net_device * dev)8790 void netdev_adjacent_change_abort(struct net_device *old_dev,
8791 				  struct net_device *new_dev,
8792 				  struct net_device *dev)
8793 {
8794 	struct netdev_nested_priv priv = {
8795 		.flags = 0,
8796 		.data = NULL,
8797 	};
8798 
8799 	if (!new_dev)
8800 		return;
8801 
8802 	if (old_dev && new_dev != old_dev)
8803 		netdev_adjacent_dev_enable(dev, old_dev);
8804 
8805 	__netdev_upper_dev_unlink(new_dev, dev, &priv);
8806 }
8807 EXPORT_SYMBOL(netdev_adjacent_change_abort);
8808 
8809 /**
8810  * netdev_bonding_info_change - Dispatch event about slave change
8811  * @dev: device
8812  * @bonding_info: info to dispatch
8813  *
8814  * Send NETDEV_BONDING_INFO to netdev notifiers with info.
8815  * The caller must hold the RTNL lock.
8816  */
netdev_bonding_info_change(struct net_device * dev,struct netdev_bonding_info * bonding_info)8817 void netdev_bonding_info_change(struct net_device *dev,
8818 				struct netdev_bonding_info *bonding_info)
8819 {
8820 	struct netdev_notifier_bonding_info info = {
8821 		.info.dev = dev,
8822 	};
8823 
8824 	memcpy(&info.bonding_info, bonding_info,
8825 	       sizeof(struct netdev_bonding_info));
8826 	call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
8827 				      &info.info);
8828 }
8829 EXPORT_SYMBOL(netdev_bonding_info_change);
8830 
netdev_offload_xstats_enable_l3(struct net_device * dev,struct netlink_ext_ack * extack)8831 static int netdev_offload_xstats_enable_l3(struct net_device *dev,
8832 					   struct netlink_ext_ack *extack)
8833 {
8834 	struct netdev_notifier_offload_xstats_info info = {
8835 		.info.dev = dev,
8836 		.info.extack = extack,
8837 		.type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
8838 	};
8839 	int err;
8840 	int rc;
8841 
8842 	dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
8843 					 GFP_KERNEL);
8844 	if (!dev->offload_xstats_l3)
8845 		return -ENOMEM;
8846 
8847 	rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
8848 						  NETDEV_OFFLOAD_XSTATS_DISABLE,
8849 						  &info.info);
8850 	err = notifier_to_errno(rc);
8851 	if (err)
8852 		goto free_stats;
8853 
8854 	return 0;
8855 
8856 free_stats:
8857 	kfree(dev->offload_xstats_l3);
8858 	dev->offload_xstats_l3 = NULL;
8859 	return err;
8860 }
8861 
netdev_offload_xstats_enable(struct net_device * dev,enum netdev_offload_xstats_type type,struct netlink_ext_ack * extack)8862 int netdev_offload_xstats_enable(struct net_device *dev,
8863 				 enum netdev_offload_xstats_type type,
8864 				 struct netlink_ext_ack *extack)
8865 {
8866 	ASSERT_RTNL();
8867 
8868 	if (netdev_offload_xstats_enabled(dev, type))
8869 		return -EALREADY;
8870 
8871 	switch (type) {
8872 	case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8873 		return netdev_offload_xstats_enable_l3(dev, extack);
8874 	}
8875 
8876 	WARN_ON(1);
8877 	return -EINVAL;
8878 }
8879 EXPORT_SYMBOL(netdev_offload_xstats_enable);
8880 
netdev_offload_xstats_disable_l3(struct net_device * dev)8881 static void netdev_offload_xstats_disable_l3(struct net_device *dev)
8882 {
8883 	struct netdev_notifier_offload_xstats_info info = {
8884 		.info.dev = dev,
8885 		.type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
8886 	};
8887 
8888 	call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
8889 				      &info.info);
8890 	kfree(dev->offload_xstats_l3);
8891 	dev->offload_xstats_l3 = NULL;
8892 }
8893 
netdev_offload_xstats_disable(struct net_device * dev,enum netdev_offload_xstats_type type)8894 int netdev_offload_xstats_disable(struct net_device *dev,
8895 				  enum netdev_offload_xstats_type type)
8896 {
8897 	ASSERT_RTNL();
8898 
8899 	if (!netdev_offload_xstats_enabled(dev, type))
8900 		return -EALREADY;
8901 
8902 	switch (type) {
8903 	case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8904 		netdev_offload_xstats_disable_l3(dev);
8905 		return 0;
8906 	}
8907 
8908 	WARN_ON(1);
8909 	return -EINVAL;
8910 }
8911 EXPORT_SYMBOL(netdev_offload_xstats_disable);
8912 
netdev_offload_xstats_disable_all(struct net_device * dev)8913 static void netdev_offload_xstats_disable_all(struct net_device *dev)
8914 {
8915 	netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
8916 }
8917 
8918 static struct rtnl_hw_stats64 *
netdev_offload_xstats_get_ptr(const struct net_device * dev,enum netdev_offload_xstats_type type)8919 netdev_offload_xstats_get_ptr(const struct net_device *dev,
8920 			      enum netdev_offload_xstats_type type)
8921 {
8922 	switch (type) {
8923 	case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8924 		return dev->offload_xstats_l3;
8925 	}
8926 
8927 	WARN_ON(1);
8928 	return NULL;
8929 }
8930 
netdev_offload_xstats_enabled(const struct net_device * dev,enum netdev_offload_xstats_type type)8931 bool netdev_offload_xstats_enabled(const struct net_device *dev,
8932 				   enum netdev_offload_xstats_type type)
8933 {
8934 	ASSERT_RTNL();
8935 
8936 	return netdev_offload_xstats_get_ptr(dev, type);
8937 }
8938 EXPORT_SYMBOL(netdev_offload_xstats_enabled);
8939 
8940 struct netdev_notifier_offload_xstats_ru {
8941 	bool used;
8942 };
8943 
8944 struct netdev_notifier_offload_xstats_rd {
8945 	struct rtnl_hw_stats64 stats;
8946 	bool used;
8947 };
8948 
netdev_hw_stats64_add(struct rtnl_hw_stats64 * dest,const struct rtnl_hw_stats64 * src)8949 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
8950 				  const struct rtnl_hw_stats64 *src)
8951 {
8952 	dest->rx_packets	  += src->rx_packets;
8953 	dest->tx_packets	  += src->tx_packets;
8954 	dest->rx_bytes		  += src->rx_bytes;
8955 	dest->tx_bytes		  += src->tx_bytes;
8956 	dest->rx_errors		  += src->rx_errors;
8957 	dest->tx_errors		  += src->tx_errors;
8958 	dest->rx_dropped	  += src->rx_dropped;
8959 	dest->tx_dropped	  += src->tx_dropped;
8960 	dest->multicast		  += src->multicast;
8961 }
8962 
netdev_offload_xstats_get_used(struct net_device * dev,enum netdev_offload_xstats_type type,bool * p_used,struct netlink_ext_ack * extack)8963 static int netdev_offload_xstats_get_used(struct net_device *dev,
8964 					  enum netdev_offload_xstats_type type,
8965 					  bool *p_used,
8966 					  struct netlink_ext_ack *extack)
8967 {
8968 	struct netdev_notifier_offload_xstats_ru report_used = {};
8969 	struct netdev_notifier_offload_xstats_info info = {
8970 		.info.dev = dev,
8971 		.info.extack = extack,
8972 		.type = type,
8973 		.report_used = &report_used,
8974 	};
8975 	int rc;
8976 
8977 	WARN_ON(!netdev_offload_xstats_enabled(dev, type));
8978 	rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
8979 					   &info.info);
8980 	*p_used = report_used.used;
8981 	return notifier_to_errno(rc);
8982 }
8983 
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)8984 static int netdev_offload_xstats_get_stats(struct net_device *dev,
8985 					   enum netdev_offload_xstats_type type,
8986 					   struct rtnl_hw_stats64 *p_stats,
8987 					   bool *p_used,
8988 					   struct netlink_ext_ack *extack)
8989 {
8990 	struct netdev_notifier_offload_xstats_rd report_delta = {};
8991 	struct netdev_notifier_offload_xstats_info info = {
8992 		.info.dev = dev,
8993 		.info.extack = extack,
8994 		.type = type,
8995 		.report_delta = &report_delta,
8996 	};
8997 	struct rtnl_hw_stats64 *stats;
8998 	int rc;
8999 
9000 	stats = netdev_offload_xstats_get_ptr(dev, type);
9001 	if (WARN_ON(!stats))
9002 		return -EINVAL;
9003 
9004 	rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
9005 					   &info.info);
9006 
9007 	/* Cache whatever we got, even if there was an error, otherwise the
9008 	 * successful stats retrievals would get lost.
9009 	 */
9010 	netdev_hw_stats64_add(stats, &report_delta.stats);
9011 
9012 	if (p_stats)
9013 		*p_stats = *stats;
9014 	*p_used = report_delta.used;
9015 
9016 	return notifier_to_errno(rc);
9017 }
9018 
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)9019 int netdev_offload_xstats_get(struct net_device *dev,
9020 			      enum netdev_offload_xstats_type type,
9021 			      struct rtnl_hw_stats64 *p_stats, bool *p_used,
9022 			      struct netlink_ext_ack *extack)
9023 {
9024 	ASSERT_RTNL();
9025 
9026 	if (p_stats)
9027 		return netdev_offload_xstats_get_stats(dev, type, p_stats,
9028 						       p_used, extack);
9029 	else
9030 		return netdev_offload_xstats_get_used(dev, type, p_used,
9031 						      extack);
9032 }
9033 EXPORT_SYMBOL(netdev_offload_xstats_get);
9034 
9035 void
netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd * report_delta,const struct rtnl_hw_stats64 * stats)9036 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
9037 				   const struct rtnl_hw_stats64 *stats)
9038 {
9039 	report_delta->used = true;
9040 	netdev_hw_stats64_add(&report_delta->stats, stats);
9041 }
9042 EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
9043 
9044 void
netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru * report_used)9045 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
9046 {
9047 	report_used->used = true;
9048 }
9049 EXPORT_SYMBOL(netdev_offload_xstats_report_used);
9050 
netdev_offload_xstats_push_delta(struct net_device * dev,enum netdev_offload_xstats_type type,const struct rtnl_hw_stats64 * p_stats)9051 void netdev_offload_xstats_push_delta(struct net_device *dev,
9052 				      enum netdev_offload_xstats_type type,
9053 				      const struct rtnl_hw_stats64 *p_stats)
9054 {
9055 	struct rtnl_hw_stats64 *stats;
9056 
9057 	ASSERT_RTNL();
9058 
9059 	stats = netdev_offload_xstats_get_ptr(dev, type);
9060 	if (WARN_ON(!stats))
9061 		return;
9062 
9063 	netdev_hw_stats64_add(stats, p_stats);
9064 }
9065 EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
9066 
9067 /**
9068  * netdev_get_xmit_slave - Get the xmit slave of master device
9069  * @dev: device
9070  * @skb: The packet
9071  * @all_slaves: assume all the slaves are active
9072  *
9073  * The reference counters are not incremented so the caller must be
9074  * careful with locks. The caller must hold RCU lock.
9075  * %NULL is returned if no slave is found.
9076  */
9077 
netdev_get_xmit_slave(struct net_device * dev,struct sk_buff * skb,bool all_slaves)9078 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
9079 					 struct sk_buff *skb,
9080 					 bool all_slaves)
9081 {
9082 	const struct net_device_ops *ops = dev->netdev_ops;
9083 
9084 	if (!ops->ndo_get_xmit_slave)
9085 		return NULL;
9086 	return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
9087 }
9088 EXPORT_SYMBOL(netdev_get_xmit_slave);
9089 
netdev_sk_get_lower_dev(struct net_device * dev,struct sock * sk)9090 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
9091 						  struct sock *sk)
9092 {
9093 	const struct net_device_ops *ops = dev->netdev_ops;
9094 
9095 	if (!ops->ndo_sk_get_lower_dev)
9096 		return NULL;
9097 	return ops->ndo_sk_get_lower_dev(dev, sk);
9098 }
9099 
9100 /**
9101  * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
9102  * @dev: device
9103  * @sk: the socket
9104  *
9105  * %NULL is returned if no lower device is found.
9106  */
9107 
netdev_sk_get_lowest_dev(struct net_device * dev,struct sock * sk)9108 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
9109 					    struct sock *sk)
9110 {
9111 	struct net_device *lower;
9112 
9113 	lower = netdev_sk_get_lower_dev(dev, sk);
9114 	while (lower) {
9115 		dev = lower;
9116 		lower = netdev_sk_get_lower_dev(dev, sk);
9117 	}
9118 
9119 	return dev;
9120 }
9121 EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
9122 
netdev_adjacent_add_links(struct net_device * dev)9123 static void netdev_adjacent_add_links(struct net_device *dev)
9124 {
9125 	struct netdev_adjacent *iter;
9126 
9127 	struct net *net = dev_net(dev);
9128 
9129 	list_for_each_entry(iter, &dev->adj_list.upper, list) {
9130 		if (!net_eq(net, dev_net(iter->dev)))
9131 			continue;
9132 		netdev_adjacent_sysfs_add(iter->dev, dev,
9133 					  &iter->dev->adj_list.lower);
9134 		netdev_adjacent_sysfs_add(dev, iter->dev,
9135 					  &dev->adj_list.upper);
9136 	}
9137 
9138 	list_for_each_entry(iter, &dev->adj_list.lower, list) {
9139 		if (!net_eq(net, dev_net(iter->dev)))
9140 			continue;
9141 		netdev_adjacent_sysfs_add(iter->dev, dev,
9142 					  &iter->dev->adj_list.upper);
9143 		netdev_adjacent_sysfs_add(dev, iter->dev,
9144 					  &dev->adj_list.lower);
9145 	}
9146 }
9147 
netdev_adjacent_del_links(struct net_device * dev)9148 static void netdev_adjacent_del_links(struct net_device *dev)
9149 {
9150 	struct netdev_adjacent *iter;
9151 
9152 	struct net *net = dev_net(dev);
9153 
9154 	list_for_each_entry(iter, &dev->adj_list.upper, list) {
9155 		if (!net_eq(net, dev_net(iter->dev)))
9156 			continue;
9157 		netdev_adjacent_sysfs_del(iter->dev, dev->name,
9158 					  &iter->dev->adj_list.lower);
9159 		netdev_adjacent_sysfs_del(dev, iter->dev->name,
9160 					  &dev->adj_list.upper);
9161 	}
9162 
9163 	list_for_each_entry(iter, &dev->adj_list.lower, list) {
9164 		if (!net_eq(net, dev_net(iter->dev)))
9165 			continue;
9166 		netdev_adjacent_sysfs_del(iter->dev, dev->name,
9167 					  &iter->dev->adj_list.upper);
9168 		netdev_adjacent_sysfs_del(dev, iter->dev->name,
9169 					  &dev->adj_list.lower);
9170 	}
9171 }
9172 
netdev_adjacent_rename_links(struct net_device * dev,char * oldname)9173 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
9174 {
9175 	struct netdev_adjacent *iter;
9176 
9177 	struct net *net = dev_net(dev);
9178 
9179 	list_for_each_entry(iter, &dev->adj_list.upper, list) {
9180 		if (!net_eq(net, dev_net(iter->dev)))
9181 			continue;
9182 		netdev_adjacent_sysfs_del(iter->dev, oldname,
9183 					  &iter->dev->adj_list.lower);
9184 		netdev_adjacent_sysfs_add(iter->dev, dev,
9185 					  &iter->dev->adj_list.lower);
9186 	}
9187 
9188 	list_for_each_entry(iter, &dev->adj_list.lower, list) {
9189 		if (!net_eq(net, dev_net(iter->dev)))
9190 			continue;
9191 		netdev_adjacent_sysfs_del(iter->dev, oldname,
9192 					  &iter->dev->adj_list.upper);
9193 		netdev_adjacent_sysfs_add(iter->dev, dev,
9194 					  &iter->dev->adj_list.upper);
9195 	}
9196 }
9197 
netdev_lower_dev_get_private(struct net_device * dev,struct net_device * lower_dev)9198 void *netdev_lower_dev_get_private(struct net_device *dev,
9199 				   struct net_device *lower_dev)
9200 {
9201 	struct netdev_adjacent *lower;
9202 
9203 	if (!lower_dev)
9204 		return NULL;
9205 	lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
9206 	if (!lower)
9207 		return NULL;
9208 
9209 	return lower->private;
9210 }
9211 EXPORT_SYMBOL(netdev_lower_dev_get_private);
9212 
9213 
9214 /**
9215  * netdev_lower_state_changed - Dispatch event about lower device state change
9216  * @lower_dev: device
9217  * @lower_state_info: state to dispatch
9218  *
9219  * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
9220  * The caller must hold the RTNL lock.
9221  */
netdev_lower_state_changed(struct net_device * lower_dev,void * lower_state_info)9222 void netdev_lower_state_changed(struct net_device *lower_dev,
9223 				void *lower_state_info)
9224 {
9225 	struct netdev_notifier_changelowerstate_info changelowerstate_info = {
9226 		.info.dev = lower_dev,
9227 	};
9228 
9229 	ASSERT_RTNL();
9230 	changelowerstate_info.lower_state_info = lower_state_info;
9231 	call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
9232 				      &changelowerstate_info.info);
9233 }
9234 EXPORT_SYMBOL(netdev_lower_state_changed);
9235 
dev_change_rx_flags(struct net_device * dev,int flags)9236 static void dev_change_rx_flags(struct net_device *dev, int flags)
9237 {
9238 	const struct net_device_ops *ops = dev->netdev_ops;
9239 
9240 	if (ops->ndo_change_rx_flags)
9241 		ops->ndo_change_rx_flags(dev, flags);
9242 }
9243 
__dev_set_promiscuity(struct net_device * dev,int inc,bool notify)9244 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
9245 {
9246 	unsigned int old_flags = dev->flags;
9247 	unsigned int promiscuity, flags;
9248 	kuid_t uid;
9249 	kgid_t gid;
9250 
9251 	ASSERT_RTNL();
9252 
9253 	promiscuity = dev->promiscuity + inc;
9254 	if (promiscuity == 0) {
9255 		/*
9256 		 * Avoid overflow.
9257 		 * If inc causes overflow, untouch promisc and return error.
9258 		 */
9259 		if (unlikely(inc > 0)) {
9260 			netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
9261 			return -EOVERFLOW;
9262 		}
9263 		flags = old_flags & ~IFF_PROMISC;
9264 	} else {
9265 		flags = old_flags | IFF_PROMISC;
9266 	}
9267 	WRITE_ONCE(dev->promiscuity, promiscuity);
9268 	if (flags != old_flags) {
9269 		WRITE_ONCE(dev->flags, flags);
9270 		netdev_info(dev, "%s promiscuous mode\n",
9271 			    dev->flags & IFF_PROMISC ? "entered" : "left");
9272 		if (audit_enabled) {
9273 			current_uid_gid(&uid, &gid);
9274 			audit_log(audit_context(), GFP_ATOMIC,
9275 				  AUDIT_ANOM_PROMISCUOUS,
9276 				  "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
9277 				  dev->name, (dev->flags & IFF_PROMISC),
9278 				  (old_flags & IFF_PROMISC),
9279 				  from_kuid(&init_user_ns, audit_get_loginuid(current)),
9280 				  from_kuid(&init_user_ns, uid),
9281 				  from_kgid(&init_user_ns, gid),
9282 				  audit_get_sessionid(current));
9283 		}
9284 
9285 		dev_change_rx_flags(dev, IFF_PROMISC);
9286 	}
9287 	if (notify) {
9288 		/* The ops lock is only required to ensure consistent locking
9289 		 * for `NETDEV_CHANGE` notifiers. This function is sometimes
9290 		 * called without the lock, even for devices that are ops
9291 		 * locked, such as in `dev_uc_sync_multiple` when using
9292 		 * bonding or teaming.
9293 		 */
9294 		netdev_ops_assert_locked(dev);
9295 		__dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL);
9296 	}
9297 	return 0;
9298 }
9299 
netif_set_promiscuity(struct net_device * dev,int inc)9300 int netif_set_promiscuity(struct net_device *dev, int inc)
9301 {
9302 	unsigned int old_flags = dev->flags;
9303 	int err;
9304 
9305 	err = __dev_set_promiscuity(dev, inc, true);
9306 	if (err < 0)
9307 		return err;
9308 	if (dev->flags != old_flags)
9309 		dev_set_rx_mode(dev);
9310 	return err;
9311 }
9312 
netif_set_allmulti(struct net_device * dev,int inc,bool notify)9313 int netif_set_allmulti(struct net_device *dev, int inc, bool notify)
9314 {
9315 	unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
9316 	unsigned int allmulti, flags;
9317 
9318 	ASSERT_RTNL();
9319 
9320 	allmulti = dev->allmulti + inc;
9321 	if (allmulti == 0) {
9322 		/*
9323 		 * Avoid overflow.
9324 		 * If inc causes overflow, untouch allmulti and return error.
9325 		 */
9326 		if (unlikely(inc > 0)) {
9327 			netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
9328 			return -EOVERFLOW;
9329 		}
9330 		flags = old_flags & ~IFF_ALLMULTI;
9331 	} else {
9332 		flags = old_flags | IFF_ALLMULTI;
9333 	}
9334 	WRITE_ONCE(dev->allmulti, allmulti);
9335 	if (flags != old_flags) {
9336 		WRITE_ONCE(dev->flags, flags);
9337 		netdev_info(dev, "%s allmulticast mode\n",
9338 			    dev->flags & IFF_ALLMULTI ? "entered" : "left");
9339 		dev_change_rx_flags(dev, IFF_ALLMULTI);
9340 		dev_set_rx_mode(dev);
9341 		if (notify)
9342 			__dev_notify_flags(dev, old_flags,
9343 					   dev->gflags ^ old_gflags, 0, NULL);
9344 	}
9345 	return 0;
9346 }
9347 
9348 /*
9349  *	Upload unicast and multicast address lists to device and
9350  *	configure RX filtering. When the device doesn't support unicast
9351  *	filtering it is put in promiscuous mode while unicast addresses
9352  *	are present.
9353  */
__dev_set_rx_mode(struct net_device * dev)9354 void __dev_set_rx_mode(struct net_device *dev)
9355 {
9356 	const struct net_device_ops *ops = dev->netdev_ops;
9357 
9358 	/* dev_open will call this function so the list will stay sane. */
9359 	if (!(dev->flags&IFF_UP))
9360 		return;
9361 
9362 	if (!netif_device_present(dev))
9363 		return;
9364 
9365 	if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
9366 		/* Unicast addresses changes may only happen under the rtnl,
9367 		 * therefore calling __dev_set_promiscuity here is safe.
9368 		 */
9369 		if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
9370 			__dev_set_promiscuity(dev, 1, false);
9371 			dev->uc_promisc = true;
9372 		} else if (netdev_uc_empty(dev) && dev->uc_promisc) {
9373 			__dev_set_promiscuity(dev, -1, false);
9374 			dev->uc_promisc = false;
9375 		}
9376 	}
9377 
9378 	if (ops->ndo_set_rx_mode)
9379 		ops->ndo_set_rx_mode(dev);
9380 }
9381 
dev_set_rx_mode(struct net_device * dev)9382 void dev_set_rx_mode(struct net_device *dev)
9383 {
9384 	netif_addr_lock_bh(dev);
9385 	__dev_set_rx_mode(dev);
9386 	netif_addr_unlock_bh(dev);
9387 }
9388 
9389 /**
9390  *	dev_get_flags - get flags reported to userspace
9391  *	@dev: device
9392  *
9393  *	Get the combination of flag bits exported through APIs to userspace.
9394  */
dev_get_flags(const struct net_device * dev)9395 unsigned int dev_get_flags(const struct net_device *dev)
9396 {
9397 	unsigned int flags;
9398 
9399 	flags = (READ_ONCE(dev->flags) & ~(IFF_PROMISC |
9400 				IFF_ALLMULTI |
9401 				IFF_RUNNING |
9402 				IFF_LOWER_UP |
9403 				IFF_DORMANT)) |
9404 		(READ_ONCE(dev->gflags) & (IFF_PROMISC |
9405 				IFF_ALLMULTI));
9406 
9407 	if (netif_running(dev)) {
9408 		if (netif_oper_up(dev))
9409 			flags |= IFF_RUNNING;
9410 		if (netif_carrier_ok(dev))
9411 			flags |= IFF_LOWER_UP;
9412 		if (netif_dormant(dev))
9413 			flags |= IFF_DORMANT;
9414 	}
9415 
9416 	return flags;
9417 }
9418 EXPORT_SYMBOL(dev_get_flags);
9419 
__dev_change_flags(struct net_device * dev,unsigned int flags,struct netlink_ext_ack * extack)9420 int __dev_change_flags(struct net_device *dev, unsigned int flags,
9421 		       struct netlink_ext_ack *extack)
9422 {
9423 	unsigned int old_flags = dev->flags;
9424 	int ret;
9425 
9426 	ASSERT_RTNL();
9427 
9428 	/*
9429 	 *	Set the flags on our device.
9430 	 */
9431 
9432 	dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
9433 			       IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
9434 			       IFF_AUTOMEDIA)) |
9435 		     (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
9436 				    IFF_ALLMULTI));
9437 
9438 	/*
9439 	 *	Load in the correct multicast list now the flags have changed.
9440 	 */
9441 
9442 	if ((old_flags ^ flags) & IFF_MULTICAST)
9443 		dev_change_rx_flags(dev, IFF_MULTICAST);
9444 
9445 	dev_set_rx_mode(dev);
9446 
9447 	/*
9448 	 *	Have we downed the interface. We handle IFF_UP ourselves
9449 	 *	according to user attempts to set it, rather than blindly
9450 	 *	setting it.
9451 	 */
9452 
9453 	ret = 0;
9454 	if ((old_flags ^ flags) & IFF_UP) {
9455 		if (old_flags & IFF_UP)
9456 			__dev_close(dev);
9457 		else
9458 			ret = __dev_open(dev, extack);
9459 	}
9460 
9461 	if ((flags ^ dev->gflags) & IFF_PROMISC) {
9462 		int inc = (flags & IFF_PROMISC) ? 1 : -1;
9463 		old_flags = dev->flags;
9464 
9465 		dev->gflags ^= IFF_PROMISC;
9466 
9467 		if (__dev_set_promiscuity(dev, inc, false) >= 0)
9468 			if (dev->flags != old_flags)
9469 				dev_set_rx_mode(dev);
9470 	}
9471 
9472 	/* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
9473 	 * is important. Some (broken) drivers set IFF_PROMISC, when
9474 	 * IFF_ALLMULTI is requested not asking us and not reporting.
9475 	 */
9476 	if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
9477 		int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
9478 
9479 		dev->gflags ^= IFF_ALLMULTI;
9480 		netif_set_allmulti(dev, inc, false);
9481 	}
9482 
9483 	return ret;
9484 }
9485 
__dev_notify_flags(struct net_device * dev,unsigned int old_flags,unsigned int gchanges,u32 portid,const struct nlmsghdr * nlh)9486 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
9487 			unsigned int gchanges, u32 portid,
9488 			const struct nlmsghdr *nlh)
9489 {
9490 	unsigned int changes = dev->flags ^ old_flags;
9491 
9492 	if (gchanges)
9493 		rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh);
9494 
9495 	if (changes & IFF_UP) {
9496 		if (dev->flags & IFF_UP)
9497 			call_netdevice_notifiers(NETDEV_UP, dev);
9498 		else
9499 			call_netdevice_notifiers(NETDEV_DOWN, dev);
9500 	}
9501 
9502 	if (dev->flags & IFF_UP &&
9503 	    (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
9504 		struct netdev_notifier_change_info change_info = {
9505 			.info = {
9506 				.dev = dev,
9507 			},
9508 			.flags_changed = changes,
9509 		};
9510 
9511 		call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
9512 	}
9513 }
9514 
netif_change_flags(struct net_device * dev,unsigned int flags,struct netlink_ext_ack * extack)9515 int netif_change_flags(struct net_device *dev, unsigned int flags,
9516 		       struct netlink_ext_ack *extack)
9517 {
9518 	int ret;
9519 	unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
9520 
9521 	ret = __dev_change_flags(dev, flags, extack);
9522 	if (ret < 0)
9523 		return ret;
9524 
9525 	changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
9526 	__dev_notify_flags(dev, old_flags, changes, 0, NULL);
9527 	return ret;
9528 }
9529 
__dev_set_mtu(struct net_device * dev,int new_mtu)9530 int __dev_set_mtu(struct net_device *dev, int new_mtu)
9531 {
9532 	const struct net_device_ops *ops = dev->netdev_ops;
9533 
9534 	if (ops->ndo_change_mtu)
9535 		return ops->ndo_change_mtu(dev, new_mtu);
9536 
9537 	/* Pairs with all the lockless reads of dev->mtu in the stack */
9538 	WRITE_ONCE(dev->mtu, new_mtu);
9539 	return 0;
9540 }
9541 EXPORT_SYMBOL(__dev_set_mtu);
9542 
dev_validate_mtu(struct net_device * dev,int new_mtu,struct netlink_ext_ack * extack)9543 int dev_validate_mtu(struct net_device *dev, int new_mtu,
9544 		     struct netlink_ext_ack *extack)
9545 {
9546 	/* MTU must be positive, and in range */
9547 	if (new_mtu < 0 || new_mtu < dev->min_mtu) {
9548 		NL_SET_ERR_MSG(extack, "mtu less than device minimum");
9549 		return -EINVAL;
9550 	}
9551 
9552 	if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
9553 		NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
9554 		return -EINVAL;
9555 	}
9556 	return 0;
9557 }
9558 
9559 /**
9560  *	netif_set_mtu_ext - Change maximum transfer unit
9561  *	@dev: device
9562  *	@new_mtu: new transfer unit
9563  *	@extack: netlink extended ack
9564  *
9565  *	Change the maximum transfer size of the network device.
9566  */
netif_set_mtu_ext(struct net_device * dev,int new_mtu,struct netlink_ext_ack * extack)9567 int netif_set_mtu_ext(struct net_device *dev, int new_mtu,
9568 		      struct netlink_ext_ack *extack)
9569 {
9570 	int err, orig_mtu;
9571 
9572 	if (new_mtu == dev->mtu)
9573 		return 0;
9574 
9575 	err = dev_validate_mtu(dev, new_mtu, extack);
9576 	if (err)
9577 		return err;
9578 
9579 	if (!netif_device_present(dev))
9580 		return -ENODEV;
9581 
9582 	err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
9583 	err = notifier_to_errno(err);
9584 	if (err)
9585 		return err;
9586 
9587 	orig_mtu = dev->mtu;
9588 	err = __dev_set_mtu(dev, new_mtu);
9589 
9590 	if (!err) {
9591 		err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
9592 						   orig_mtu);
9593 		err = notifier_to_errno(err);
9594 		if (err) {
9595 			/* setting mtu back and notifying everyone again,
9596 			 * so that they have a chance to revert changes.
9597 			 */
9598 			__dev_set_mtu(dev, orig_mtu);
9599 			call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
9600 						     new_mtu);
9601 		}
9602 	}
9603 	return err;
9604 }
9605 
netif_set_mtu(struct net_device * dev,int new_mtu)9606 int netif_set_mtu(struct net_device *dev, int new_mtu)
9607 {
9608 	struct netlink_ext_ack extack;
9609 	int err;
9610 
9611 	memset(&extack, 0, sizeof(extack));
9612 	err = netif_set_mtu_ext(dev, new_mtu, &extack);
9613 	if (err && extack._msg)
9614 		net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
9615 	return err;
9616 }
9617 EXPORT_SYMBOL(netif_set_mtu);
9618 
netif_change_tx_queue_len(struct net_device * dev,unsigned long new_len)9619 int netif_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
9620 {
9621 	unsigned int orig_len = dev->tx_queue_len;
9622 	int res;
9623 
9624 	if (new_len != (unsigned int)new_len)
9625 		return -ERANGE;
9626 
9627 	if (new_len != orig_len) {
9628 		WRITE_ONCE(dev->tx_queue_len, new_len);
9629 		res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
9630 		res = notifier_to_errno(res);
9631 		if (res)
9632 			goto err_rollback;
9633 		res = dev_qdisc_change_tx_queue_len(dev);
9634 		if (res)
9635 			goto err_rollback;
9636 	}
9637 
9638 	return 0;
9639 
9640 err_rollback:
9641 	netdev_err(dev, "refused to change device tx_queue_len\n");
9642 	WRITE_ONCE(dev->tx_queue_len, orig_len);
9643 	return res;
9644 }
9645 
netif_set_group(struct net_device * dev,int new_group)9646 void netif_set_group(struct net_device *dev, int new_group)
9647 {
9648 	dev->group = new_group;
9649 }
9650 
9651 /**
9652  *	dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
9653  *	@dev: device
9654  *	@addr: new address
9655  *	@extack: netlink extended ack
9656  */
dev_pre_changeaddr_notify(struct net_device * dev,const char * addr,struct netlink_ext_ack * extack)9657 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
9658 			      struct netlink_ext_ack *extack)
9659 {
9660 	struct netdev_notifier_pre_changeaddr_info info = {
9661 		.info.dev = dev,
9662 		.info.extack = extack,
9663 		.dev_addr = addr,
9664 	};
9665 	int rc;
9666 
9667 	rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
9668 	return notifier_to_errno(rc);
9669 }
9670 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
9671 
netif_set_mac_address(struct net_device * dev,struct sockaddr_storage * ss,struct netlink_ext_ack * extack)9672 int netif_set_mac_address(struct net_device *dev, struct sockaddr_storage *ss,
9673 			  struct netlink_ext_ack *extack)
9674 {
9675 	const struct net_device_ops *ops = dev->netdev_ops;
9676 	int err;
9677 
9678 	if (!ops->ndo_set_mac_address)
9679 		return -EOPNOTSUPP;
9680 	if (ss->ss_family != dev->type)
9681 		return -EINVAL;
9682 	if (!netif_device_present(dev))
9683 		return -ENODEV;
9684 	err = dev_pre_changeaddr_notify(dev, ss->__data, extack);
9685 	if (err)
9686 		return err;
9687 	if (memcmp(dev->dev_addr, ss->__data, dev->addr_len)) {
9688 		err = ops->ndo_set_mac_address(dev, ss);
9689 		if (err)
9690 			return err;
9691 	}
9692 	dev->addr_assign_type = NET_ADDR_SET;
9693 	call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
9694 	add_device_randomness(dev->dev_addr, dev->addr_len);
9695 	return 0;
9696 }
9697 
9698 DECLARE_RWSEM(dev_addr_sem);
9699 
9700 /* "sa" is a true struct sockaddr with limited "sa_data" member. */
dev_get_mac_address(struct sockaddr * sa,struct net * net,char * dev_name)9701 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
9702 {
9703 	size_t size = sizeof(sa->sa_data_min);
9704 	struct net_device *dev;
9705 	int ret = 0;
9706 
9707 	down_read(&dev_addr_sem);
9708 	rcu_read_lock();
9709 
9710 	dev = dev_get_by_name_rcu(net, dev_name);
9711 	if (!dev) {
9712 		ret = -ENODEV;
9713 		goto unlock;
9714 	}
9715 	if (!dev->addr_len)
9716 		memset(sa->sa_data, 0, size);
9717 	else
9718 		memcpy(sa->sa_data, dev->dev_addr,
9719 		       min_t(size_t, size, dev->addr_len));
9720 	sa->sa_family = dev->type;
9721 
9722 unlock:
9723 	rcu_read_unlock();
9724 	up_read(&dev_addr_sem);
9725 	return ret;
9726 }
9727 EXPORT_SYMBOL(dev_get_mac_address);
9728 
netif_change_carrier(struct net_device * dev,bool new_carrier)9729 int netif_change_carrier(struct net_device *dev, bool new_carrier)
9730 {
9731 	const struct net_device_ops *ops = dev->netdev_ops;
9732 
9733 	if (!ops->ndo_change_carrier)
9734 		return -EOPNOTSUPP;
9735 	if (!netif_device_present(dev))
9736 		return -ENODEV;
9737 	return ops->ndo_change_carrier(dev, new_carrier);
9738 }
9739 
9740 /**
9741  *	dev_get_phys_port_id - Get device physical port ID
9742  *	@dev: device
9743  *	@ppid: port ID
9744  *
9745  *	Get device physical port ID
9746  */
dev_get_phys_port_id(struct net_device * dev,struct netdev_phys_item_id * ppid)9747 int dev_get_phys_port_id(struct net_device *dev,
9748 			 struct netdev_phys_item_id *ppid)
9749 {
9750 	const struct net_device_ops *ops = dev->netdev_ops;
9751 
9752 	if (!ops->ndo_get_phys_port_id)
9753 		return -EOPNOTSUPP;
9754 	return ops->ndo_get_phys_port_id(dev, ppid);
9755 }
9756 
9757 /**
9758  *	dev_get_phys_port_name - Get device physical port name
9759  *	@dev: device
9760  *	@name: port name
9761  *	@len: limit of bytes to copy to name
9762  *
9763  *	Get device physical port name
9764  */
dev_get_phys_port_name(struct net_device * dev,char * name,size_t len)9765 int dev_get_phys_port_name(struct net_device *dev,
9766 			   char *name, size_t len)
9767 {
9768 	const struct net_device_ops *ops = dev->netdev_ops;
9769 	int err;
9770 
9771 	if (ops->ndo_get_phys_port_name) {
9772 		err = ops->ndo_get_phys_port_name(dev, name, len);
9773 		if (err != -EOPNOTSUPP)
9774 			return err;
9775 	}
9776 	return devlink_compat_phys_port_name_get(dev, name, len);
9777 }
9778 
9779 /**
9780  *	dev_get_port_parent_id - Get the device's port parent identifier
9781  *	@dev: network device
9782  *	@ppid: pointer to a storage for the port's parent identifier
9783  *	@recurse: allow/disallow recursion to lower devices
9784  *
9785  *	Get the devices's port parent identifier
9786  */
dev_get_port_parent_id(struct net_device * dev,struct netdev_phys_item_id * ppid,bool recurse)9787 int dev_get_port_parent_id(struct net_device *dev,
9788 			   struct netdev_phys_item_id *ppid,
9789 			   bool recurse)
9790 {
9791 	const struct net_device_ops *ops = dev->netdev_ops;
9792 	struct netdev_phys_item_id first = { };
9793 	struct net_device *lower_dev;
9794 	struct list_head *iter;
9795 	int err;
9796 
9797 	if (ops->ndo_get_port_parent_id) {
9798 		err = ops->ndo_get_port_parent_id(dev, ppid);
9799 		if (err != -EOPNOTSUPP)
9800 			return err;
9801 	}
9802 
9803 	err = devlink_compat_switch_id_get(dev, ppid);
9804 	if (!recurse || err != -EOPNOTSUPP)
9805 		return err;
9806 
9807 	netdev_for_each_lower_dev(dev, lower_dev, iter) {
9808 		err = dev_get_port_parent_id(lower_dev, ppid, true);
9809 		if (err)
9810 			break;
9811 		if (!first.id_len)
9812 			first = *ppid;
9813 		else if (memcmp(&first, ppid, sizeof(*ppid)))
9814 			return -EOPNOTSUPP;
9815 	}
9816 
9817 	return err;
9818 }
9819 EXPORT_SYMBOL(dev_get_port_parent_id);
9820 
9821 /**
9822  *	netdev_port_same_parent_id - Indicate if two network devices have
9823  *	the same port parent identifier
9824  *	@a: first network device
9825  *	@b: second network device
9826  */
netdev_port_same_parent_id(struct net_device * a,struct net_device * b)9827 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
9828 {
9829 	struct netdev_phys_item_id a_id = { };
9830 	struct netdev_phys_item_id b_id = { };
9831 
9832 	if (dev_get_port_parent_id(a, &a_id, true) ||
9833 	    dev_get_port_parent_id(b, &b_id, true))
9834 		return false;
9835 
9836 	return netdev_phys_item_id_same(&a_id, &b_id);
9837 }
9838 EXPORT_SYMBOL(netdev_port_same_parent_id);
9839 
netif_change_proto_down(struct net_device * dev,bool proto_down)9840 int netif_change_proto_down(struct net_device *dev, bool proto_down)
9841 {
9842 	if (!dev->change_proto_down)
9843 		return -EOPNOTSUPP;
9844 	if (!netif_device_present(dev))
9845 		return -ENODEV;
9846 	if (proto_down)
9847 		netif_carrier_off(dev);
9848 	else
9849 		netif_carrier_on(dev);
9850 	WRITE_ONCE(dev->proto_down, proto_down);
9851 	return 0;
9852 }
9853 
9854 /**
9855  *	netdev_change_proto_down_reason_locked - proto down reason
9856  *
9857  *	@dev: device
9858  *	@mask: proto down mask
9859  *	@value: proto down value
9860  */
netdev_change_proto_down_reason_locked(struct net_device * dev,unsigned long mask,u32 value)9861 void netdev_change_proto_down_reason_locked(struct net_device *dev,
9862 					    unsigned long mask, u32 value)
9863 {
9864 	u32 proto_down_reason;
9865 	int b;
9866 
9867 	if (!mask) {
9868 		proto_down_reason = value;
9869 	} else {
9870 		proto_down_reason = dev->proto_down_reason;
9871 		for_each_set_bit(b, &mask, 32) {
9872 			if (value & (1 << b))
9873 				proto_down_reason |= BIT(b);
9874 			else
9875 				proto_down_reason &= ~BIT(b);
9876 		}
9877 	}
9878 	WRITE_ONCE(dev->proto_down_reason, proto_down_reason);
9879 }
9880 
9881 struct bpf_xdp_link {
9882 	struct bpf_link link;
9883 	struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
9884 	int flags;
9885 };
9886 
dev_xdp_mode(struct net_device * dev,u32 flags)9887 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
9888 {
9889 	if (flags & XDP_FLAGS_HW_MODE)
9890 		return XDP_MODE_HW;
9891 	if (flags & XDP_FLAGS_DRV_MODE)
9892 		return XDP_MODE_DRV;
9893 	if (flags & XDP_FLAGS_SKB_MODE)
9894 		return XDP_MODE_SKB;
9895 	return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
9896 }
9897 
dev_xdp_bpf_op(struct net_device * dev,enum bpf_xdp_mode mode)9898 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
9899 {
9900 	switch (mode) {
9901 	case XDP_MODE_SKB:
9902 		return generic_xdp_install;
9903 	case XDP_MODE_DRV:
9904 	case XDP_MODE_HW:
9905 		return dev->netdev_ops->ndo_bpf;
9906 	default:
9907 		return NULL;
9908 	}
9909 }
9910 
dev_xdp_link(struct net_device * dev,enum bpf_xdp_mode mode)9911 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
9912 					 enum bpf_xdp_mode mode)
9913 {
9914 	return dev->xdp_state[mode].link;
9915 }
9916 
dev_xdp_prog(struct net_device * dev,enum bpf_xdp_mode mode)9917 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
9918 				     enum bpf_xdp_mode mode)
9919 {
9920 	struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
9921 
9922 	if (link)
9923 		return link->link.prog;
9924 	return dev->xdp_state[mode].prog;
9925 }
9926 
dev_xdp_prog_count(struct net_device * dev)9927 u8 dev_xdp_prog_count(struct net_device *dev)
9928 {
9929 	u8 count = 0;
9930 	int i;
9931 
9932 	for (i = 0; i < __MAX_XDP_MODE; i++)
9933 		if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
9934 			count++;
9935 	return count;
9936 }
9937 EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
9938 
dev_xdp_sb_prog_count(struct net_device * dev)9939 u8 dev_xdp_sb_prog_count(struct net_device *dev)
9940 {
9941 	u8 count = 0;
9942 	int i;
9943 
9944 	for (i = 0; i < __MAX_XDP_MODE; i++)
9945 		if (dev->xdp_state[i].prog &&
9946 		    !dev->xdp_state[i].prog->aux->xdp_has_frags)
9947 			count++;
9948 	return count;
9949 }
9950 
netif_xdp_propagate(struct net_device * dev,struct netdev_bpf * bpf)9951 int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
9952 {
9953 	if (!dev->netdev_ops->ndo_bpf)
9954 		return -EOPNOTSUPP;
9955 
9956 	if (dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED &&
9957 	    bpf->command == XDP_SETUP_PROG &&
9958 	    bpf->prog && !bpf->prog->aux->xdp_has_frags) {
9959 		NL_SET_ERR_MSG(bpf->extack,
9960 			       "unable to propagate XDP to device using tcp-data-split");
9961 		return -EBUSY;
9962 	}
9963 
9964 	if (dev_get_min_mp_channel_count(dev)) {
9965 		NL_SET_ERR_MSG(bpf->extack, "unable to propagate XDP to device using memory provider");
9966 		return -EBUSY;
9967 	}
9968 
9969 	return dev->netdev_ops->ndo_bpf(dev, bpf);
9970 }
9971 EXPORT_SYMBOL_GPL(netif_xdp_propagate);
9972 
dev_xdp_prog_id(struct net_device * dev,enum bpf_xdp_mode mode)9973 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
9974 {
9975 	struct bpf_prog *prog = dev_xdp_prog(dev, mode);
9976 
9977 	return prog ? prog->aux->id : 0;
9978 }
9979 
dev_xdp_set_link(struct net_device * dev,enum bpf_xdp_mode mode,struct bpf_xdp_link * link)9980 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
9981 			     struct bpf_xdp_link *link)
9982 {
9983 	dev->xdp_state[mode].link = link;
9984 	dev->xdp_state[mode].prog = NULL;
9985 }
9986 
dev_xdp_set_prog(struct net_device * dev,enum bpf_xdp_mode mode,struct bpf_prog * prog)9987 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
9988 			     struct bpf_prog *prog)
9989 {
9990 	dev->xdp_state[mode].link = NULL;
9991 	dev->xdp_state[mode].prog = prog;
9992 }
9993 
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)9994 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
9995 			   bpf_op_t bpf_op, struct netlink_ext_ack *extack,
9996 			   u32 flags, struct bpf_prog *prog)
9997 {
9998 	struct netdev_bpf xdp;
9999 	int err;
10000 
10001 	netdev_ops_assert_locked(dev);
10002 
10003 	if (dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED &&
10004 	    prog && !prog->aux->xdp_has_frags) {
10005 		NL_SET_ERR_MSG(extack, "unable to install XDP to device using tcp-data-split");
10006 		return -EBUSY;
10007 	}
10008 
10009 	if (dev_get_min_mp_channel_count(dev)) {
10010 		NL_SET_ERR_MSG(extack, "unable to install XDP to device using memory provider");
10011 		return -EBUSY;
10012 	}
10013 
10014 	memset(&xdp, 0, sizeof(xdp));
10015 	xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
10016 	xdp.extack = extack;
10017 	xdp.flags = flags;
10018 	xdp.prog = prog;
10019 
10020 	/* Drivers assume refcnt is already incremented (i.e, prog pointer is
10021 	 * "moved" into driver), so they don't increment it on their own, but
10022 	 * they do decrement refcnt when program is detached or replaced.
10023 	 * Given net_device also owns link/prog, we need to bump refcnt here
10024 	 * to prevent drivers from underflowing it.
10025 	 */
10026 	if (prog)
10027 		bpf_prog_inc(prog);
10028 	err = bpf_op(dev, &xdp);
10029 	if (err) {
10030 		if (prog)
10031 			bpf_prog_put(prog);
10032 		return err;
10033 	}
10034 
10035 	if (mode != XDP_MODE_HW)
10036 		bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
10037 
10038 	return 0;
10039 }
10040 
dev_xdp_uninstall(struct net_device * dev)10041 static void dev_xdp_uninstall(struct net_device *dev)
10042 {
10043 	struct bpf_xdp_link *link;
10044 	struct bpf_prog *prog;
10045 	enum bpf_xdp_mode mode;
10046 	bpf_op_t bpf_op;
10047 
10048 	ASSERT_RTNL();
10049 
10050 	for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
10051 		prog = dev_xdp_prog(dev, mode);
10052 		if (!prog)
10053 			continue;
10054 
10055 		bpf_op = dev_xdp_bpf_op(dev, mode);
10056 		if (!bpf_op)
10057 			continue;
10058 
10059 		WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
10060 
10061 		/* auto-detach link from net device */
10062 		link = dev_xdp_link(dev, mode);
10063 		if (link)
10064 			link->dev = NULL;
10065 		else
10066 			bpf_prog_put(prog);
10067 
10068 		dev_xdp_set_link(dev, mode, NULL);
10069 	}
10070 }
10071 
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)10072 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
10073 			  struct bpf_xdp_link *link, struct bpf_prog *new_prog,
10074 			  struct bpf_prog *old_prog, u32 flags)
10075 {
10076 	unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
10077 	struct bpf_prog *cur_prog;
10078 	struct net_device *upper;
10079 	struct list_head *iter;
10080 	enum bpf_xdp_mode mode;
10081 	bpf_op_t bpf_op;
10082 	int err;
10083 
10084 	ASSERT_RTNL();
10085 
10086 	/* either link or prog attachment, never both */
10087 	if (link && (new_prog || old_prog))
10088 		return -EINVAL;
10089 	/* link supports only XDP mode flags */
10090 	if (link && (flags & ~XDP_FLAGS_MODES)) {
10091 		NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
10092 		return -EINVAL;
10093 	}
10094 	/* just one XDP mode bit should be set, zero defaults to drv/skb mode */
10095 	if (num_modes > 1) {
10096 		NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
10097 		return -EINVAL;
10098 	}
10099 	/* avoid ambiguity if offload + drv/skb mode progs are both loaded */
10100 	if (!num_modes && dev_xdp_prog_count(dev) > 1) {
10101 		NL_SET_ERR_MSG(extack,
10102 			       "More than one program loaded, unset mode is ambiguous");
10103 		return -EINVAL;
10104 	}
10105 	/* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
10106 	if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
10107 		NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
10108 		return -EINVAL;
10109 	}
10110 
10111 	mode = dev_xdp_mode(dev, flags);
10112 	/* can't replace attached link */
10113 	if (dev_xdp_link(dev, mode)) {
10114 		NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
10115 		return -EBUSY;
10116 	}
10117 
10118 	/* don't allow if an upper device already has a program */
10119 	netdev_for_each_upper_dev_rcu(dev, upper, iter) {
10120 		if (dev_xdp_prog_count(upper) > 0) {
10121 			NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
10122 			return -EEXIST;
10123 		}
10124 	}
10125 
10126 	cur_prog = dev_xdp_prog(dev, mode);
10127 	/* can't replace attached prog with link */
10128 	if (link && cur_prog) {
10129 		NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
10130 		return -EBUSY;
10131 	}
10132 	if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
10133 		NL_SET_ERR_MSG(extack, "Active program does not match expected");
10134 		return -EEXIST;
10135 	}
10136 
10137 	/* put effective new program into new_prog */
10138 	if (link)
10139 		new_prog = link->link.prog;
10140 
10141 	if (new_prog) {
10142 		bool offload = mode == XDP_MODE_HW;
10143 		enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
10144 					       ? XDP_MODE_DRV : XDP_MODE_SKB;
10145 
10146 		if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
10147 			NL_SET_ERR_MSG(extack, "XDP program already attached");
10148 			return -EBUSY;
10149 		}
10150 		if (!offload && dev_xdp_prog(dev, other_mode)) {
10151 			NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
10152 			return -EEXIST;
10153 		}
10154 		if (!offload && bpf_prog_is_offloaded(new_prog->aux)) {
10155 			NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
10156 			return -EINVAL;
10157 		}
10158 		if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) {
10159 			NL_SET_ERR_MSG(extack, "Program bound to different device");
10160 			return -EINVAL;
10161 		}
10162 		if (bpf_prog_is_dev_bound(new_prog->aux) && mode == XDP_MODE_SKB) {
10163 			NL_SET_ERR_MSG(extack, "Can't attach device-bound programs in generic mode");
10164 			return -EINVAL;
10165 		}
10166 		if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
10167 			NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
10168 			return -EINVAL;
10169 		}
10170 		if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
10171 			NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
10172 			return -EINVAL;
10173 		}
10174 	}
10175 
10176 	/* don't call drivers if the effective program didn't change */
10177 	if (new_prog != cur_prog) {
10178 		bpf_op = dev_xdp_bpf_op(dev, mode);
10179 		if (!bpf_op) {
10180 			NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
10181 			return -EOPNOTSUPP;
10182 		}
10183 
10184 		err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
10185 		if (err)
10186 			return err;
10187 	}
10188 
10189 	if (link)
10190 		dev_xdp_set_link(dev, mode, link);
10191 	else
10192 		dev_xdp_set_prog(dev, mode, new_prog);
10193 	if (cur_prog)
10194 		bpf_prog_put(cur_prog);
10195 
10196 	return 0;
10197 }
10198 
dev_xdp_attach_link(struct net_device * dev,struct netlink_ext_ack * extack,struct bpf_xdp_link * link)10199 static int dev_xdp_attach_link(struct net_device *dev,
10200 			       struct netlink_ext_ack *extack,
10201 			       struct bpf_xdp_link *link)
10202 {
10203 	return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
10204 }
10205 
dev_xdp_detach_link(struct net_device * dev,struct netlink_ext_ack * extack,struct bpf_xdp_link * link)10206 static int dev_xdp_detach_link(struct net_device *dev,
10207 			       struct netlink_ext_ack *extack,
10208 			       struct bpf_xdp_link *link)
10209 {
10210 	enum bpf_xdp_mode mode;
10211 	bpf_op_t bpf_op;
10212 
10213 	ASSERT_RTNL();
10214 
10215 	mode = dev_xdp_mode(dev, link->flags);
10216 	if (dev_xdp_link(dev, mode) != link)
10217 		return -EINVAL;
10218 
10219 	bpf_op = dev_xdp_bpf_op(dev, mode);
10220 	WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
10221 	dev_xdp_set_link(dev, mode, NULL);
10222 	return 0;
10223 }
10224 
bpf_xdp_link_release(struct bpf_link * link)10225 static void bpf_xdp_link_release(struct bpf_link *link)
10226 {
10227 	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
10228 
10229 	rtnl_lock();
10230 
10231 	/* if racing with net_device's tear down, xdp_link->dev might be
10232 	 * already NULL, in which case link was already auto-detached
10233 	 */
10234 	if (xdp_link->dev) {
10235 		netdev_lock_ops(xdp_link->dev);
10236 		WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
10237 		netdev_unlock_ops(xdp_link->dev);
10238 		xdp_link->dev = NULL;
10239 	}
10240 
10241 	rtnl_unlock();
10242 }
10243 
bpf_xdp_link_detach(struct bpf_link * link)10244 static int bpf_xdp_link_detach(struct bpf_link *link)
10245 {
10246 	bpf_xdp_link_release(link);
10247 	return 0;
10248 }
10249 
bpf_xdp_link_dealloc(struct bpf_link * link)10250 static void bpf_xdp_link_dealloc(struct bpf_link *link)
10251 {
10252 	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
10253 
10254 	kfree(xdp_link);
10255 }
10256 
bpf_xdp_link_show_fdinfo(const struct bpf_link * link,struct seq_file * seq)10257 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
10258 				     struct seq_file *seq)
10259 {
10260 	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
10261 	u32 ifindex = 0;
10262 
10263 	rtnl_lock();
10264 	if (xdp_link->dev)
10265 		ifindex = xdp_link->dev->ifindex;
10266 	rtnl_unlock();
10267 
10268 	seq_printf(seq, "ifindex:\t%u\n", ifindex);
10269 }
10270 
bpf_xdp_link_fill_link_info(const struct bpf_link * link,struct bpf_link_info * info)10271 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
10272 				       struct bpf_link_info *info)
10273 {
10274 	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
10275 	u32 ifindex = 0;
10276 
10277 	rtnl_lock();
10278 	if (xdp_link->dev)
10279 		ifindex = xdp_link->dev->ifindex;
10280 	rtnl_unlock();
10281 
10282 	info->xdp.ifindex = ifindex;
10283 	return 0;
10284 }
10285 
bpf_xdp_link_update(struct bpf_link * link,struct bpf_prog * new_prog,struct bpf_prog * old_prog)10286 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
10287 			       struct bpf_prog *old_prog)
10288 {
10289 	struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
10290 	enum bpf_xdp_mode mode;
10291 	bpf_op_t bpf_op;
10292 	int err = 0;
10293 
10294 	rtnl_lock();
10295 
10296 	/* link might have been auto-released already, so fail */
10297 	if (!xdp_link->dev) {
10298 		err = -ENOLINK;
10299 		goto out_unlock;
10300 	}
10301 
10302 	if (old_prog && link->prog != old_prog) {
10303 		err = -EPERM;
10304 		goto out_unlock;
10305 	}
10306 	old_prog = link->prog;
10307 	if (old_prog->type != new_prog->type ||
10308 	    old_prog->expected_attach_type != new_prog->expected_attach_type) {
10309 		err = -EINVAL;
10310 		goto out_unlock;
10311 	}
10312 
10313 	if (old_prog == new_prog) {
10314 		/* no-op, don't disturb drivers */
10315 		bpf_prog_put(new_prog);
10316 		goto out_unlock;
10317 	}
10318 
10319 	netdev_lock_ops(xdp_link->dev);
10320 	mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
10321 	bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
10322 	err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
10323 			      xdp_link->flags, new_prog);
10324 	netdev_unlock_ops(xdp_link->dev);
10325 	if (err)
10326 		goto out_unlock;
10327 
10328 	old_prog = xchg(&link->prog, new_prog);
10329 	bpf_prog_put(old_prog);
10330 
10331 out_unlock:
10332 	rtnl_unlock();
10333 	return err;
10334 }
10335 
10336 static const struct bpf_link_ops bpf_xdp_link_lops = {
10337 	.release = bpf_xdp_link_release,
10338 	.dealloc = bpf_xdp_link_dealloc,
10339 	.detach = bpf_xdp_link_detach,
10340 	.show_fdinfo = bpf_xdp_link_show_fdinfo,
10341 	.fill_link_info = bpf_xdp_link_fill_link_info,
10342 	.update_prog = bpf_xdp_link_update,
10343 };
10344 
bpf_xdp_link_attach(const union bpf_attr * attr,struct bpf_prog * prog)10345 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
10346 {
10347 	struct net *net = current->nsproxy->net_ns;
10348 	struct bpf_link_primer link_primer;
10349 	struct netlink_ext_ack extack = {};
10350 	struct bpf_xdp_link *link;
10351 	struct net_device *dev;
10352 	int err, fd;
10353 
10354 	rtnl_lock();
10355 	dev = dev_get_by_index(net, attr->link_create.target_ifindex);
10356 	if (!dev) {
10357 		rtnl_unlock();
10358 		return -EINVAL;
10359 	}
10360 
10361 	link = kzalloc(sizeof(*link), GFP_USER);
10362 	if (!link) {
10363 		err = -ENOMEM;
10364 		goto unlock;
10365 	}
10366 
10367 	bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
10368 	link->dev = dev;
10369 	link->flags = attr->link_create.flags;
10370 
10371 	err = bpf_link_prime(&link->link, &link_primer);
10372 	if (err) {
10373 		kfree(link);
10374 		goto unlock;
10375 	}
10376 
10377 	netdev_lock_ops(dev);
10378 	err = dev_xdp_attach_link(dev, &extack, link);
10379 	netdev_unlock_ops(dev);
10380 	rtnl_unlock();
10381 
10382 	if (err) {
10383 		link->dev = NULL;
10384 		bpf_link_cleanup(&link_primer);
10385 		trace_bpf_xdp_link_attach_failed(extack._msg);
10386 		goto out_put_dev;
10387 	}
10388 
10389 	fd = bpf_link_settle(&link_primer);
10390 	/* link itself doesn't hold dev's refcnt to not complicate shutdown */
10391 	dev_put(dev);
10392 	return fd;
10393 
10394 unlock:
10395 	rtnl_unlock();
10396 
10397 out_put_dev:
10398 	dev_put(dev);
10399 	return err;
10400 }
10401 
10402 /**
10403  *	dev_change_xdp_fd - set or clear a bpf program for a device rx path
10404  *	@dev: device
10405  *	@extack: netlink extended ack
10406  *	@fd: new program fd or negative value to clear
10407  *	@expected_fd: old program fd that userspace expects to replace or clear
10408  *	@flags: xdp-related flags
10409  *
10410  *	Set or clear a bpf program for a device
10411  */
dev_change_xdp_fd(struct net_device * dev,struct netlink_ext_ack * extack,int fd,int expected_fd,u32 flags)10412 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
10413 		      int fd, int expected_fd, u32 flags)
10414 {
10415 	enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
10416 	struct bpf_prog *new_prog = NULL, *old_prog = NULL;
10417 	int err;
10418 
10419 	ASSERT_RTNL();
10420 
10421 	if (fd >= 0) {
10422 		new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
10423 						 mode != XDP_MODE_SKB);
10424 		if (IS_ERR(new_prog))
10425 			return PTR_ERR(new_prog);
10426 	}
10427 
10428 	if (expected_fd >= 0) {
10429 		old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
10430 						 mode != XDP_MODE_SKB);
10431 		if (IS_ERR(old_prog)) {
10432 			err = PTR_ERR(old_prog);
10433 			old_prog = NULL;
10434 			goto err_out;
10435 		}
10436 	}
10437 
10438 	err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
10439 
10440 err_out:
10441 	if (err && new_prog)
10442 		bpf_prog_put(new_prog);
10443 	if (old_prog)
10444 		bpf_prog_put(old_prog);
10445 	return err;
10446 }
10447 
dev_get_min_mp_channel_count(const struct net_device * dev)10448 u32 dev_get_min_mp_channel_count(const struct net_device *dev)
10449 {
10450 	int i;
10451 
10452 	netdev_ops_assert_locked(dev);
10453 
10454 	for (i = dev->real_num_rx_queues - 1; i >= 0; i--)
10455 		if (dev->_rx[i].mp_params.mp_priv)
10456 			/* The channel count is the idx plus 1. */
10457 			return i + 1;
10458 
10459 	return 0;
10460 }
10461 
10462 /**
10463  * dev_index_reserve() - allocate an ifindex in a namespace
10464  * @net: the applicable net namespace
10465  * @ifindex: requested ifindex, pass %0 to get one allocated
10466  *
10467  * Allocate a ifindex for a new device. Caller must either use the ifindex
10468  * to store the device (via list_netdevice()) or call dev_index_release()
10469  * to give the index up.
10470  *
10471  * Return: a suitable unique value for a new device interface number or -errno.
10472  */
dev_index_reserve(struct net * net,u32 ifindex)10473 static int dev_index_reserve(struct net *net, u32 ifindex)
10474 {
10475 	int err;
10476 
10477 	if (ifindex > INT_MAX) {
10478 		DEBUG_NET_WARN_ON_ONCE(1);
10479 		return -EINVAL;
10480 	}
10481 
10482 	if (!ifindex)
10483 		err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL,
10484 				      xa_limit_31b, &net->ifindex, GFP_KERNEL);
10485 	else
10486 		err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL);
10487 	if (err < 0)
10488 		return err;
10489 
10490 	return ifindex;
10491 }
10492 
dev_index_release(struct net * net,int ifindex)10493 static void dev_index_release(struct net *net, int ifindex)
10494 {
10495 	/* Expect only unused indexes, unlist_netdevice() removes the used */
10496 	WARN_ON(xa_erase(&net->dev_by_index, ifindex));
10497 }
10498 
from_cleanup_net(void)10499 static bool from_cleanup_net(void)
10500 {
10501 #ifdef CONFIG_NET_NS
10502 	return current == READ_ONCE(cleanup_net_task);
10503 #else
10504 	return false;
10505 #endif
10506 }
10507 
10508 /* Delayed registration/unregisteration */
10509 LIST_HEAD(net_todo_list);
10510 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
10511 atomic_t dev_unreg_count = ATOMIC_INIT(0);
10512 
net_set_todo(struct net_device * dev)10513 static void net_set_todo(struct net_device *dev)
10514 {
10515 	list_add_tail(&dev->todo_list, &net_todo_list);
10516 }
10517 
netdev_sync_upper_features(struct net_device * lower,struct net_device * upper,netdev_features_t features)10518 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
10519 	struct net_device *upper, netdev_features_t features)
10520 {
10521 	netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
10522 	netdev_features_t feature;
10523 	int feature_bit;
10524 
10525 	for_each_netdev_feature(upper_disables, feature_bit) {
10526 		feature = __NETIF_F_BIT(feature_bit);
10527 		if (!(upper->wanted_features & feature)
10528 		    && (features & feature)) {
10529 			netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
10530 				   &feature, upper->name);
10531 			features &= ~feature;
10532 		}
10533 	}
10534 
10535 	return features;
10536 }
10537 
netdev_sync_lower_features(struct net_device * upper,struct net_device * lower,netdev_features_t features)10538 static void netdev_sync_lower_features(struct net_device *upper,
10539 	struct net_device *lower, netdev_features_t features)
10540 {
10541 	netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
10542 	netdev_features_t feature;
10543 	int feature_bit;
10544 
10545 	for_each_netdev_feature(upper_disables, feature_bit) {
10546 		feature = __NETIF_F_BIT(feature_bit);
10547 		if (!(features & feature) && (lower->features & feature)) {
10548 			netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
10549 				   &feature, lower->name);
10550 			netdev_lock_ops(lower);
10551 			lower->wanted_features &= ~feature;
10552 			__netdev_update_features(lower);
10553 
10554 			if (unlikely(lower->features & feature))
10555 				netdev_WARN(upper, "failed to disable %pNF on %s!\n",
10556 					    &feature, lower->name);
10557 			else
10558 				netdev_features_change(lower);
10559 			netdev_unlock_ops(lower);
10560 		}
10561 	}
10562 }
10563 
netdev_has_ip_or_hw_csum(netdev_features_t features)10564 static bool netdev_has_ip_or_hw_csum(netdev_features_t features)
10565 {
10566 	netdev_features_t ip_csum_mask = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
10567 	bool ip_csum = (features & ip_csum_mask) == ip_csum_mask;
10568 	bool hw_csum = features & NETIF_F_HW_CSUM;
10569 
10570 	return ip_csum || hw_csum;
10571 }
10572 
netdev_fix_features(struct net_device * dev,netdev_features_t features)10573 static netdev_features_t netdev_fix_features(struct net_device *dev,
10574 	netdev_features_t features)
10575 {
10576 	/* Fix illegal checksum combinations */
10577 	if ((features & NETIF_F_HW_CSUM) &&
10578 	    (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
10579 		netdev_warn(dev, "mixed HW and IP checksum settings.\n");
10580 		features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
10581 	}
10582 
10583 	/* TSO requires that SG is present as well. */
10584 	if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
10585 		netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
10586 		features &= ~NETIF_F_ALL_TSO;
10587 	}
10588 
10589 	if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
10590 					!(features & NETIF_F_IP_CSUM)) {
10591 		netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
10592 		features &= ~NETIF_F_TSO;
10593 		features &= ~NETIF_F_TSO_ECN;
10594 	}
10595 
10596 	if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
10597 					 !(features & NETIF_F_IPV6_CSUM)) {
10598 		netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
10599 		features &= ~NETIF_F_TSO6;
10600 	}
10601 
10602 	/* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
10603 	if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
10604 		features &= ~NETIF_F_TSO_MANGLEID;
10605 
10606 	/* TSO ECN requires that TSO is present as well. */
10607 	if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
10608 		features &= ~NETIF_F_TSO_ECN;
10609 
10610 	/* Software GSO depends on SG. */
10611 	if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
10612 		netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
10613 		features &= ~NETIF_F_GSO;
10614 	}
10615 
10616 	/* GSO partial features require GSO partial be set */
10617 	if ((features & dev->gso_partial_features) &&
10618 	    !(features & NETIF_F_GSO_PARTIAL)) {
10619 		netdev_dbg(dev,
10620 			   "Dropping partially supported GSO features since no GSO partial.\n");
10621 		features &= ~dev->gso_partial_features;
10622 	}
10623 
10624 	if (!(features & NETIF_F_RXCSUM)) {
10625 		/* NETIF_F_GRO_HW implies doing RXCSUM since every packet
10626 		 * successfully merged by hardware must also have the
10627 		 * checksum verified by hardware.  If the user does not
10628 		 * want to enable RXCSUM, logically, we should disable GRO_HW.
10629 		 */
10630 		if (features & NETIF_F_GRO_HW) {
10631 			netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
10632 			features &= ~NETIF_F_GRO_HW;
10633 		}
10634 	}
10635 
10636 	/* LRO/HW-GRO features cannot be combined with RX-FCS */
10637 	if (features & NETIF_F_RXFCS) {
10638 		if (features & NETIF_F_LRO) {
10639 			netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
10640 			features &= ~NETIF_F_LRO;
10641 		}
10642 
10643 		if (features & NETIF_F_GRO_HW) {
10644 			netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
10645 			features &= ~NETIF_F_GRO_HW;
10646 		}
10647 	}
10648 
10649 	if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
10650 		netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
10651 		features &= ~NETIF_F_LRO;
10652 	}
10653 
10654 	if ((features & NETIF_F_HW_TLS_TX) && !netdev_has_ip_or_hw_csum(features)) {
10655 		netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
10656 		features &= ~NETIF_F_HW_TLS_TX;
10657 	}
10658 
10659 	if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
10660 		netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
10661 		features &= ~NETIF_F_HW_TLS_RX;
10662 	}
10663 
10664 	if ((features & NETIF_F_GSO_UDP_L4) && !netdev_has_ip_or_hw_csum(features)) {
10665 		netdev_dbg(dev, "Dropping USO feature since no CSUM feature.\n");
10666 		features &= ~NETIF_F_GSO_UDP_L4;
10667 	}
10668 
10669 	return features;
10670 }
10671 
__netdev_update_features(struct net_device * dev)10672 int __netdev_update_features(struct net_device *dev)
10673 {
10674 	struct net_device *upper, *lower;
10675 	netdev_features_t features;
10676 	struct list_head *iter;
10677 	int err = -1;
10678 
10679 	ASSERT_RTNL();
10680 	netdev_ops_assert_locked(dev);
10681 
10682 	features = netdev_get_wanted_features(dev);
10683 
10684 	if (dev->netdev_ops->ndo_fix_features)
10685 		features = dev->netdev_ops->ndo_fix_features(dev, features);
10686 
10687 	/* driver might be less strict about feature dependencies */
10688 	features = netdev_fix_features(dev, features);
10689 
10690 	/* some features can't be enabled if they're off on an upper device */
10691 	netdev_for_each_upper_dev_rcu(dev, upper, iter)
10692 		features = netdev_sync_upper_features(dev, upper, features);
10693 
10694 	if (dev->features == features)
10695 		goto sync_lower;
10696 
10697 	netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
10698 		&dev->features, &features);
10699 
10700 	if (dev->netdev_ops->ndo_set_features)
10701 		err = dev->netdev_ops->ndo_set_features(dev, features);
10702 	else
10703 		err = 0;
10704 
10705 	if (unlikely(err < 0)) {
10706 		netdev_err(dev,
10707 			"set_features() failed (%d); wanted %pNF, left %pNF\n",
10708 			err, &features, &dev->features);
10709 		/* return non-0 since some features might have changed and
10710 		 * it's better to fire a spurious notification than miss it
10711 		 */
10712 		return -1;
10713 	}
10714 
10715 sync_lower:
10716 	/* some features must be disabled on lower devices when disabled
10717 	 * on an upper device (think: bonding master or bridge)
10718 	 */
10719 	netdev_for_each_lower_dev(dev, lower, iter)
10720 		netdev_sync_lower_features(dev, lower, features);
10721 
10722 	if (!err) {
10723 		netdev_features_t diff = features ^ dev->features;
10724 
10725 		if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
10726 			/* udp_tunnel_{get,drop}_rx_info both need
10727 			 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
10728 			 * device, or they won't do anything.
10729 			 * Thus we need to update dev->features
10730 			 * *before* calling udp_tunnel_get_rx_info,
10731 			 * but *after* calling udp_tunnel_drop_rx_info.
10732 			 */
10733 			if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
10734 				dev->features = features;
10735 				udp_tunnel_get_rx_info(dev);
10736 			} else {
10737 				udp_tunnel_drop_rx_info(dev);
10738 			}
10739 		}
10740 
10741 		if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
10742 			if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
10743 				dev->features = features;
10744 				err |= vlan_get_rx_ctag_filter_info(dev);
10745 			} else {
10746 				vlan_drop_rx_ctag_filter_info(dev);
10747 			}
10748 		}
10749 
10750 		if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
10751 			if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
10752 				dev->features = features;
10753 				err |= vlan_get_rx_stag_filter_info(dev);
10754 			} else {
10755 				vlan_drop_rx_stag_filter_info(dev);
10756 			}
10757 		}
10758 
10759 		dev->features = features;
10760 	}
10761 
10762 	return err < 0 ? 0 : 1;
10763 }
10764 
10765 /**
10766  *	netdev_update_features - recalculate device features
10767  *	@dev: the device to check
10768  *
10769  *	Recalculate dev->features set and send notifications if it
10770  *	has changed. Should be called after driver or hardware dependent
10771  *	conditions might have changed that influence the features.
10772  */
netdev_update_features(struct net_device * dev)10773 void netdev_update_features(struct net_device *dev)
10774 {
10775 	if (__netdev_update_features(dev))
10776 		netdev_features_change(dev);
10777 }
10778 EXPORT_SYMBOL(netdev_update_features);
10779 
10780 /**
10781  *	netdev_change_features - recalculate device features
10782  *	@dev: the device to check
10783  *
10784  *	Recalculate dev->features set and send notifications even
10785  *	if they have not changed. Should be called instead of
10786  *	netdev_update_features() if also dev->vlan_features might
10787  *	have changed to allow the changes to be propagated to stacked
10788  *	VLAN devices.
10789  */
netdev_change_features(struct net_device * dev)10790 void netdev_change_features(struct net_device *dev)
10791 {
10792 	__netdev_update_features(dev);
10793 	netdev_features_change(dev);
10794 }
10795 EXPORT_SYMBOL(netdev_change_features);
10796 
10797 /**
10798  *	netif_stacked_transfer_operstate -	transfer operstate
10799  *	@rootdev: the root or lower level device to transfer state from
10800  *	@dev: the device to transfer operstate to
10801  *
10802  *	Transfer operational state from root to device. This is normally
10803  *	called when a stacking relationship exists between the root
10804  *	device and the device(a leaf device).
10805  */
netif_stacked_transfer_operstate(const struct net_device * rootdev,struct net_device * dev)10806 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
10807 					struct net_device *dev)
10808 {
10809 	if (rootdev->operstate == IF_OPER_DORMANT)
10810 		netif_dormant_on(dev);
10811 	else
10812 		netif_dormant_off(dev);
10813 
10814 	if (rootdev->operstate == IF_OPER_TESTING)
10815 		netif_testing_on(dev);
10816 	else
10817 		netif_testing_off(dev);
10818 
10819 	if (netif_carrier_ok(rootdev))
10820 		netif_carrier_on(dev);
10821 	else
10822 		netif_carrier_off(dev);
10823 }
10824 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
10825 
netif_alloc_rx_queues(struct net_device * dev)10826 static int netif_alloc_rx_queues(struct net_device *dev)
10827 {
10828 	unsigned int i, count = dev->num_rx_queues;
10829 	struct netdev_rx_queue *rx;
10830 	size_t sz = count * sizeof(*rx);
10831 	int err = 0;
10832 
10833 	BUG_ON(count < 1);
10834 
10835 	rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10836 	if (!rx)
10837 		return -ENOMEM;
10838 
10839 	dev->_rx = rx;
10840 
10841 	for (i = 0; i < count; i++) {
10842 		rx[i].dev = dev;
10843 
10844 		/* XDP RX-queue setup */
10845 		err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
10846 		if (err < 0)
10847 			goto err_rxq_info;
10848 	}
10849 	return 0;
10850 
10851 err_rxq_info:
10852 	/* Rollback successful reg's and free other resources */
10853 	while (i--)
10854 		xdp_rxq_info_unreg(&rx[i].xdp_rxq);
10855 	kvfree(dev->_rx);
10856 	dev->_rx = NULL;
10857 	return err;
10858 }
10859 
netif_free_rx_queues(struct net_device * dev)10860 static void netif_free_rx_queues(struct net_device *dev)
10861 {
10862 	unsigned int i, count = dev->num_rx_queues;
10863 
10864 	/* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
10865 	if (!dev->_rx)
10866 		return;
10867 
10868 	for (i = 0; i < count; i++)
10869 		xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
10870 
10871 	kvfree(dev->_rx);
10872 }
10873 
netdev_init_one_queue(struct net_device * dev,struct netdev_queue * queue,void * _unused)10874 static void netdev_init_one_queue(struct net_device *dev,
10875 				  struct netdev_queue *queue, void *_unused)
10876 {
10877 	/* Initialize queue lock */
10878 	spin_lock_init(&queue->_xmit_lock);
10879 	netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
10880 	queue->xmit_lock_owner = -1;
10881 	netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
10882 	queue->dev = dev;
10883 #ifdef CONFIG_BQL
10884 	dql_init(&queue->dql, HZ);
10885 #endif
10886 }
10887 
netif_free_tx_queues(struct net_device * dev)10888 static void netif_free_tx_queues(struct net_device *dev)
10889 {
10890 	kvfree(dev->_tx);
10891 }
10892 
netif_alloc_netdev_queues(struct net_device * dev)10893 static int netif_alloc_netdev_queues(struct net_device *dev)
10894 {
10895 	unsigned int count = dev->num_tx_queues;
10896 	struct netdev_queue *tx;
10897 	size_t sz = count * sizeof(*tx);
10898 
10899 	if (count < 1 || count > 0xffff)
10900 		return -EINVAL;
10901 
10902 	tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10903 	if (!tx)
10904 		return -ENOMEM;
10905 
10906 	dev->_tx = tx;
10907 
10908 	netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
10909 	spin_lock_init(&dev->tx_global_lock);
10910 
10911 	return 0;
10912 }
10913 
netif_tx_stop_all_queues(struct net_device * dev)10914 void netif_tx_stop_all_queues(struct net_device *dev)
10915 {
10916 	unsigned int i;
10917 
10918 	for (i = 0; i < dev->num_tx_queues; i++) {
10919 		struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
10920 
10921 		netif_tx_stop_queue(txq);
10922 	}
10923 }
10924 EXPORT_SYMBOL(netif_tx_stop_all_queues);
10925 
netdev_do_alloc_pcpu_stats(struct net_device * dev)10926 static int netdev_do_alloc_pcpu_stats(struct net_device *dev)
10927 {
10928 	void __percpu *v;
10929 
10930 	/* Drivers implementing ndo_get_peer_dev must support tstat
10931 	 * accounting, so that skb_do_redirect() can bump the dev's
10932 	 * RX stats upon network namespace switch.
10933 	 */
10934 	if (dev->netdev_ops->ndo_get_peer_dev &&
10935 	    dev->pcpu_stat_type != NETDEV_PCPU_STAT_TSTATS)
10936 		return -EOPNOTSUPP;
10937 
10938 	switch (dev->pcpu_stat_type) {
10939 	case NETDEV_PCPU_STAT_NONE:
10940 		return 0;
10941 	case NETDEV_PCPU_STAT_LSTATS:
10942 		v = dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats);
10943 		break;
10944 	case NETDEV_PCPU_STAT_TSTATS:
10945 		v = dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
10946 		break;
10947 	case NETDEV_PCPU_STAT_DSTATS:
10948 		v = dev->dstats = netdev_alloc_pcpu_stats(struct pcpu_dstats);
10949 		break;
10950 	default:
10951 		return -EINVAL;
10952 	}
10953 
10954 	return v ? 0 : -ENOMEM;
10955 }
10956 
netdev_do_free_pcpu_stats(struct net_device * dev)10957 static void netdev_do_free_pcpu_stats(struct net_device *dev)
10958 {
10959 	switch (dev->pcpu_stat_type) {
10960 	case NETDEV_PCPU_STAT_NONE:
10961 		return;
10962 	case NETDEV_PCPU_STAT_LSTATS:
10963 		free_percpu(dev->lstats);
10964 		break;
10965 	case NETDEV_PCPU_STAT_TSTATS:
10966 		free_percpu(dev->tstats);
10967 		break;
10968 	case NETDEV_PCPU_STAT_DSTATS:
10969 		free_percpu(dev->dstats);
10970 		break;
10971 	}
10972 }
10973 
netdev_free_phy_link_topology(struct net_device * dev)10974 static void netdev_free_phy_link_topology(struct net_device *dev)
10975 {
10976 	struct phy_link_topology *topo = dev->link_topo;
10977 
10978 	if (IS_ENABLED(CONFIG_PHYLIB) && topo) {
10979 		xa_destroy(&topo->phys);
10980 		kfree(topo);
10981 		dev->link_topo = NULL;
10982 	}
10983 }
10984 
10985 /**
10986  * register_netdevice() - register a network device
10987  * @dev: device to register
10988  *
10989  * Take a prepared network device structure and make it externally accessible.
10990  * A %NETDEV_REGISTER message is sent to the netdev notifier chain.
10991  * Callers must hold the rtnl lock - you may want register_netdev()
10992  * instead of this.
10993  */
register_netdevice(struct net_device * dev)10994 int register_netdevice(struct net_device *dev)
10995 {
10996 	int ret;
10997 	struct net *net = dev_net(dev);
10998 
10999 	BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
11000 		     NETDEV_FEATURE_COUNT);
11001 	BUG_ON(dev_boot_phase);
11002 	ASSERT_RTNL();
11003 
11004 	might_sleep();
11005 
11006 	/* When net_device's are persistent, this will be fatal. */
11007 	BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
11008 	BUG_ON(!net);
11009 
11010 	ret = ethtool_check_ops(dev->ethtool_ops);
11011 	if (ret)
11012 		return ret;
11013 
11014 	/* rss ctx ID 0 is reserved for the default context, start from 1 */
11015 	xa_init_flags(&dev->ethtool->rss_ctx, XA_FLAGS_ALLOC1);
11016 	mutex_init(&dev->ethtool->rss_lock);
11017 
11018 	spin_lock_init(&dev->addr_list_lock);
11019 	netdev_set_addr_lockdep_class(dev);
11020 
11021 	ret = dev_get_valid_name(net, dev, dev->name);
11022 	if (ret < 0)
11023 		goto out;
11024 
11025 	ret = -ENOMEM;
11026 	dev->name_node = netdev_name_node_head_alloc(dev);
11027 	if (!dev->name_node)
11028 		goto out;
11029 
11030 	/* Init, if this function is available */
11031 	if (dev->netdev_ops->ndo_init) {
11032 		ret = dev->netdev_ops->ndo_init(dev);
11033 		if (ret) {
11034 			if (ret > 0)
11035 				ret = -EIO;
11036 			goto err_free_name;
11037 		}
11038 	}
11039 
11040 	if (((dev->hw_features | dev->features) &
11041 	     NETIF_F_HW_VLAN_CTAG_FILTER) &&
11042 	    (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
11043 	     !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
11044 		netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
11045 		ret = -EINVAL;
11046 		goto err_uninit;
11047 	}
11048 
11049 	ret = netdev_do_alloc_pcpu_stats(dev);
11050 	if (ret)
11051 		goto err_uninit;
11052 
11053 	ret = dev_index_reserve(net, dev->ifindex);
11054 	if (ret < 0)
11055 		goto err_free_pcpu;
11056 	dev->ifindex = ret;
11057 
11058 	/* Transfer changeable features to wanted_features and enable
11059 	 * software offloads (GSO and GRO).
11060 	 */
11061 	dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
11062 	dev->features |= NETIF_F_SOFT_FEATURES;
11063 
11064 	if (dev->udp_tunnel_nic_info) {
11065 		dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
11066 		dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
11067 	}
11068 
11069 	dev->wanted_features = dev->features & dev->hw_features;
11070 
11071 	if (!(dev->flags & IFF_LOOPBACK))
11072 		dev->hw_features |= NETIF_F_NOCACHE_COPY;
11073 
11074 	/* If IPv4 TCP segmentation offload is supported we should also
11075 	 * allow the device to enable segmenting the frame with the option
11076 	 * of ignoring a static IP ID value.  This doesn't enable the
11077 	 * feature itself but allows the user to enable it later.
11078 	 */
11079 	if (dev->hw_features & NETIF_F_TSO)
11080 		dev->hw_features |= NETIF_F_TSO_MANGLEID;
11081 	if (dev->vlan_features & NETIF_F_TSO)
11082 		dev->vlan_features |= NETIF_F_TSO_MANGLEID;
11083 	if (dev->mpls_features & NETIF_F_TSO)
11084 		dev->mpls_features |= NETIF_F_TSO_MANGLEID;
11085 	if (dev->hw_enc_features & NETIF_F_TSO)
11086 		dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
11087 
11088 	/* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
11089 	 */
11090 	dev->vlan_features |= NETIF_F_HIGHDMA;
11091 
11092 	/* Make NETIF_F_SG inheritable to tunnel devices.
11093 	 */
11094 	dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
11095 
11096 	/* Make NETIF_F_SG inheritable to MPLS.
11097 	 */
11098 	dev->mpls_features |= NETIF_F_SG;
11099 
11100 	ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
11101 	ret = notifier_to_errno(ret);
11102 	if (ret)
11103 		goto err_ifindex_release;
11104 
11105 	ret = netdev_register_kobject(dev);
11106 
11107 	netdev_lock(dev);
11108 	WRITE_ONCE(dev->reg_state, ret ? NETREG_UNREGISTERED : NETREG_REGISTERED);
11109 	netdev_unlock(dev);
11110 
11111 	if (ret)
11112 		goto err_uninit_notify;
11113 
11114 	netdev_lock_ops(dev);
11115 	__netdev_update_features(dev);
11116 	netdev_unlock_ops(dev);
11117 
11118 	/*
11119 	 *	Default initial state at registry is that the
11120 	 *	device is present.
11121 	 */
11122 
11123 	set_bit(__LINK_STATE_PRESENT, &dev->state);
11124 
11125 	linkwatch_init_dev(dev);
11126 
11127 	dev_init_scheduler(dev);
11128 
11129 	netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL);
11130 	list_netdevice(dev);
11131 
11132 	add_device_randomness(dev->dev_addr, dev->addr_len);
11133 
11134 	/* If the device has permanent device address, driver should
11135 	 * set dev_addr and also addr_assign_type should be set to
11136 	 * NET_ADDR_PERM (default value).
11137 	 */
11138 	if (dev->addr_assign_type == NET_ADDR_PERM)
11139 		memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
11140 
11141 	/* Notify protocols, that a new device appeared. */
11142 	netdev_lock_ops(dev);
11143 	ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
11144 	netdev_unlock_ops(dev);
11145 	ret = notifier_to_errno(ret);
11146 	if (ret) {
11147 		/* Expect explicit free_netdev() on failure */
11148 		dev->needs_free_netdev = false;
11149 		unregister_netdevice_queue(dev, NULL);
11150 		goto out;
11151 	}
11152 	/*
11153 	 *	Prevent userspace races by waiting until the network
11154 	 *	device is fully setup before sending notifications.
11155 	 */
11156 	if (!(dev->rtnl_link_ops && dev->rtnl_link_initializing))
11157 		rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
11158 
11159 out:
11160 	return ret;
11161 
11162 err_uninit_notify:
11163 	call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
11164 err_ifindex_release:
11165 	dev_index_release(net, dev->ifindex);
11166 err_free_pcpu:
11167 	netdev_do_free_pcpu_stats(dev);
11168 err_uninit:
11169 	if (dev->netdev_ops->ndo_uninit)
11170 		dev->netdev_ops->ndo_uninit(dev);
11171 	if (dev->priv_destructor)
11172 		dev->priv_destructor(dev);
11173 err_free_name:
11174 	netdev_name_node_free(dev->name_node);
11175 	goto out;
11176 }
11177 EXPORT_SYMBOL(register_netdevice);
11178 
11179 /* Initialize the core of a dummy net device.
11180  * The setup steps dummy netdevs need which normal netdevs get by going
11181  * through register_netdevice().
11182  */
init_dummy_netdev(struct net_device * dev)11183 static void init_dummy_netdev(struct net_device *dev)
11184 {
11185 	/* make sure we BUG if trying to hit standard
11186 	 * register/unregister code path
11187 	 */
11188 	dev->reg_state = NETREG_DUMMY;
11189 
11190 	/* a dummy interface is started by default */
11191 	set_bit(__LINK_STATE_PRESENT, &dev->state);
11192 	set_bit(__LINK_STATE_START, &dev->state);
11193 
11194 	/* Note : We dont allocate pcpu_refcnt for dummy devices,
11195 	 * because users of this 'device' dont need to change
11196 	 * its refcount.
11197 	 */
11198 }
11199 
11200 /**
11201  *	register_netdev	- register a network device
11202  *	@dev: device to register
11203  *
11204  *	Take a completed network device structure and add it to the kernel
11205  *	interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
11206  *	chain. 0 is returned on success. A negative errno code is returned
11207  *	on a failure to set up the device, or if the name is a duplicate.
11208  *
11209  *	This is a wrapper around register_netdevice that takes the rtnl semaphore
11210  *	and expands the device name if you passed a format string to
11211  *	alloc_netdev.
11212  */
register_netdev(struct net_device * dev)11213 int register_netdev(struct net_device *dev)
11214 {
11215 	struct net *net = dev_net(dev);
11216 	int err;
11217 
11218 	if (rtnl_net_lock_killable(net))
11219 		return -EINTR;
11220 
11221 	err = register_netdevice(dev);
11222 
11223 	rtnl_net_unlock(net);
11224 
11225 	return err;
11226 }
11227 EXPORT_SYMBOL(register_netdev);
11228 
netdev_refcnt_read(const struct net_device * dev)11229 int netdev_refcnt_read(const struct net_device *dev)
11230 {
11231 #ifdef CONFIG_PCPU_DEV_REFCNT
11232 	int i, refcnt = 0;
11233 
11234 	for_each_possible_cpu(i)
11235 		refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
11236 	return refcnt;
11237 #else
11238 	return refcount_read(&dev->dev_refcnt);
11239 #endif
11240 }
11241 EXPORT_SYMBOL(netdev_refcnt_read);
11242 
11243 int netdev_unregister_timeout_secs __read_mostly = 10;
11244 
11245 #define WAIT_REFS_MIN_MSECS 1
11246 #define WAIT_REFS_MAX_MSECS 250
11247 /**
11248  * netdev_wait_allrefs_any - wait until all references are gone.
11249  * @list: list of net_devices to wait on
11250  *
11251  * This is called when unregistering network devices.
11252  *
11253  * Any protocol or device that holds a reference should register
11254  * for netdevice notification, and cleanup and put back the
11255  * reference if they receive an UNREGISTER event.
11256  * We can get stuck here if buggy protocols don't correctly
11257  * call dev_put.
11258  */
netdev_wait_allrefs_any(struct list_head * list)11259 static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
11260 {
11261 	unsigned long rebroadcast_time, warning_time;
11262 	struct net_device *dev;
11263 	int wait = 0;
11264 
11265 	rebroadcast_time = warning_time = jiffies;
11266 
11267 	list_for_each_entry(dev, list, todo_list)
11268 		if (netdev_refcnt_read(dev) == 1)
11269 			return dev;
11270 
11271 	while (true) {
11272 		if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
11273 			rtnl_lock();
11274 
11275 			/* Rebroadcast unregister notification */
11276 			list_for_each_entry(dev, list, todo_list)
11277 				call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11278 
11279 			__rtnl_unlock();
11280 			rcu_barrier();
11281 			rtnl_lock();
11282 
11283 			list_for_each_entry(dev, list, todo_list)
11284 				if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
11285 					     &dev->state)) {
11286 					/* We must not have linkwatch events
11287 					 * pending on unregister. If this
11288 					 * happens, we simply run the queue
11289 					 * unscheduled, resulting in a noop
11290 					 * for this device.
11291 					 */
11292 					linkwatch_run_queue();
11293 					break;
11294 				}
11295 
11296 			__rtnl_unlock();
11297 
11298 			rebroadcast_time = jiffies;
11299 		}
11300 
11301 		rcu_barrier();
11302 
11303 		if (!wait) {
11304 			wait = WAIT_REFS_MIN_MSECS;
11305 		} else {
11306 			msleep(wait);
11307 			wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
11308 		}
11309 
11310 		list_for_each_entry(dev, list, todo_list)
11311 			if (netdev_refcnt_read(dev) == 1)
11312 				return dev;
11313 
11314 		if (time_after(jiffies, warning_time +
11315 			       READ_ONCE(netdev_unregister_timeout_secs) * HZ)) {
11316 			list_for_each_entry(dev, list, todo_list) {
11317 				pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
11318 					 dev->name, netdev_refcnt_read(dev));
11319 				ref_tracker_dir_print(&dev->refcnt_tracker, 10);
11320 			}
11321 
11322 			warning_time = jiffies;
11323 		}
11324 	}
11325 }
11326 
11327 /* The sequence is:
11328  *
11329  *	rtnl_lock();
11330  *	...
11331  *	register_netdevice(x1);
11332  *	register_netdevice(x2);
11333  *	...
11334  *	unregister_netdevice(y1);
11335  *	unregister_netdevice(y2);
11336  *      ...
11337  *	rtnl_unlock();
11338  *	free_netdev(y1);
11339  *	free_netdev(y2);
11340  *
11341  * We are invoked by rtnl_unlock().
11342  * This allows us to deal with problems:
11343  * 1) We can delete sysfs objects which invoke hotplug
11344  *    without deadlocking with linkwatch via keventd.
11345  * 2) Since we run with the RTNL semaphore not held, we can sleep
11346  *    safely in order to wait for the netdev refcnt to drop to zero.
11347  *
11348  * We must not return until all unregister events added during
11349  * the interval the lock was held have been completed.
11350  */
netdev_run_todo(void)11351 void netdev_run_todo(void)
11352 {
11353 	struct net_device *dev, *tmp;
11354 	struct list_head list;
11355 	int cnt;
11356 #ifdef CONFIG_LOCKDEP
11357 	struct list_head unlink_list;
11358 
11359 	list_replace_init(&net_unlink_list, &unlink_list);
11360 
11361 	while (!list_empty(&unlink_list)) {
11362 		dev = list_first_entry(&unlink_list, struct net_device,
11363 				       unlink_list);
11364 		list_del_init(&dev->unlink_list);
11365 		dev->nested_level = dev->lower_level - 1;
11366 	}
11367 #endif
11368 
11369 	/* Snapshot list, allow later requests */
11370 	list_replace_init(&net_todo_list, &list);
11371 
11372 	__rtnl_unlock();
11373 
11374 	/* Wait for rcu callbacks to finish before next phase */
11375 	if (!list_empty(&list))
11376 		rcu_barrier();
11377 
11378 	list_for_each_entry_safe(dev, tmp, &list, todo_list) {
11379 		if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
11380 			netdev_WARN(dev, "run_todo but not unregistering\n");
11381 			list_del(&dev->todo_list);
11382 			continue;
11383 		}
11384 
11385 		netdev_lock(dev);
11386 		WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERED);
11387 		netdev_unlock(dev);
11388 		linkwatch_sync_dev(dev);
11389 	}
11390 
11391 	cnt = 0;
11392 	while (!list_empty(&list)) {
11393 		dev = netdev_wait_allrefs_any(&list);
11394 		list_del(&dev->todo_list);
11395 
11396 		/* paranoia */
11397 		BUG_ON(netdev_refcnt_read(dev) != 1);
11398 		BUG_ON(!list_empty(&dev->ptype_all));
11399 		BUG_ON(!list_empty(&dev->ptype_specific));
11400 		WARN_ON(rcu_access_pointer(dev->ip_ptr));
11401 		WARN_ON(rcu_access_pointer(dev->ip6_ptr));
11402 
11403 		netdev_do_free_pcpu_stats(dev);
11404 		if (dev->priv_destructor)
11405 			dev->priv_destructor(dev);
11406 		if (dev->needs_free_netdev)
11407 			free_netdev(dev);
11408 
11409 		cnt++;
11410 
11411 		/* Free network device */
11412 		kobject_put(&dev->dev.kobj);
11413 	}
11414 	if (cnt && atomic_sub_and_test(cnt, &dev_unreg_count))
11415 		wake_up(&netdev_unregistering_wq);
11416 }
11417 
11418 /* Collate per-cpu network dstats statistics
11419  *
11420  * Read per-cpu network statistics from dev->dstats and populate the related
11421  * fields in @s.
11422  */
dev_fetch_dstats(struct rtnl_link_stats64 * s,const struct pcpu_dstats __percpu * dstats)11423 static void dev_fetch_dstats(struct rtnl_link_stats64 *s,
11424 			     const struct pcpu_dstats __percpu *dstats)
11425 {
11426 	int cpu;
11427 
11428 	for_each_possible_cpu(cpu) {
11429 		u64 rx_packets, rx_bytes, rx_drops;
11430 		u64 tx_packets, tx_bytes, tx_drops;
11431 		const struct pcpu_dstats *stats;
11432 		unsigned int start;
11433 
11434 		stats = per_cpu_ptr(dstats, cpu);
11435 		do {
11436 			start = u64_stats_fetch_begin(&stats->syncp);
11437 			rx_packets = u64_stats_read(&stats->rx_packets);
11438 			rx_bytes   = u64_stats_read(&stats->rx_bytes);
11439 			rx_drops   = u64_stats_read(&stats->rx_drops);
11440 			tx_packets = u64_stats_read(&stats->tx_packets);
11441 			tx_bytes   = u64_stats_read(&stats->tx_bytes);
11442 			tx_drops   = u64_stats_read(&stats->tx_drops);
11443 		} while (u64_stats_fetch_retry(&stats->syncp, start));
11444 
11445 		s->rx_packets += rx_packets;
11446 		s->rx_bytes   += rx_bytes;
11447 		s->rx_dropped += rx_drops;
11448 		s->tx_packets += tx_packets;
11449 		s->tx_bytes   += tx_bytes;
11450 		s->tx_dropped += tx_drops;
11451 	}
11452 }
11453 
11454 /* ndo_get_stats64 implementation for dtstats-based accounting.
11455  *
11456  * Populate @s from dev->stats and dev->dstats. This is used internally by the
11457  * core for NETDEV_PCPU_STAT_DSTAT-type stats collection.
11458  */
dev_get_dstats64(const struct net_device * dev,struct rtnl_link_stats64 * s)11459 static void dev_get_dstats64(const struct net_device *dev,
11460 			     struct rtnl_link_stats64 *s)
11461 {
11462 	netdev_stats_to_stats64(s, &dev->stats);
11463 	dev_fetch_dstats(s, dev->dstats);
11464 }
11465 
11466 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
11467  * all the same fields in the same order as net_device_stats, with only
11468  * the type differing, but rtnl_link_stats64 may have additional fields
11469  * at the end for newer counters.
11470  */
netdev_stats_to_stats64(struct rtnl_link_stats64 * stats64,const struct net_device_stats * netdev_stats)11471 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
11472 			     const struct net_device_stats *netdev_stats)
11473 {
11474 	size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t);
11475 	const atomic_long_t *src = (atomic_long_t *)netdev_stats;
11476 	u64 *dst = (u64 *)stats64;
11477 
11478 	BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
11479 	for (i = 0; i < n; i++)
11480 		dst[i] = (unsigned long)atomic_long_read(&src[i]);
11481 	/* zero out counters that only exist in rtnl_link_stats64 */
11482 	memset((char *)stats64 + n * sizeof(u64), 0,
11483 	       sizeof(*stats64) - n * sizeof(u64));
11484 }
11485 EXPORT_SYMBOL(netdev_stats_to_stats64);
11486 
netdev_core_stats_alloc(struct net_device * dev)11487 static __cold struct net_device_core_stats __percpu *netdev_core_stats_alloc(
11488 		struct net_device *dev)
11489 {
11490 	struct net_device_core_stats __percpu *p;
11491 
11492 	p = alloc_percpu_gfp(struct net_device_core_stats,
11493 			     GFP_ATOMIC | __GFP_NOWARN);
11494 
11495 	if (p && cmpxchg(&dev->core_stats, NULL, p))
11496 		free_percpu(p);
11497 
11498 	/* This READ_ONCE() pairs with the cmpxchg() above */
11499 	return READ_ONCE(dev->core_stats);
11500 }
11501 
netdev_core_stats_inc(struct net_device * dev,u32 offset)11502 noinline void netdev_core_stats_inc(struct net_device *dev, u32 offset)
11503 {
11504 	/* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
11505 	struct net_device_core_stats __percpu *p = READ_ONCE(dev->core_stats);
11506 	unsigned long __percpu *field;
11507 
11508 	if (unlikely(!p)) {
11509 		p = netdev_core_stats_alloc(dev);
11510 		if (!p)
11511 			return;
11512 	}
11513 
11514 	field = (unsigned long __percpu *)((void __percpu *)p + offset);
11515 	this_cpu_inc(*field);
11516 }
11517 EXPORT_SYMBOL_GPL(netdev_core_stats_inc);
11518 
11519 /**
11520  *	dev_get_stats	- get network device statistics
11521  *	@dev: device to get statistics from
11522  *	@storage: place to store stats
11523  *
11524  *	Get network statistics from device. Return @storage.
11525  *	The device driver may provide its own method by setting
11526  *	dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
11527  *	otherwise the internal statistics structure is used.
11528  */
dev_get_stats(struct net_device * dev,struct rtnl_link_stats64 * storage)11529 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
11530 					struct rtnl_link_stats64 *storage)
11531 {
11532 	const struct net_device_ops *ops = dev->netdev_ops;
11533 	const struct net_device_core_stats __percpu *p;
11534 
11535 	/*
11536 	 * IPv{4,6} and udp tunnels share common stat helpers and use
11537 	 * different stat type (NETDEV_PCPU_STAT_TSTATS vs
11538 	 * NETDEV_PCPU_STAT_DSTATS). Ensure the accounting is consistent.
11539 	 */
11540 	BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, rx_bytes) !=
11541 		     offsetof(struct pcpu_dstats, rx_bytes));
11542 	BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, rx_packets) !=
11543 		     offsetof(struct pcpu_dstats, rx_packets));
11544 	BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, tx_bytes) !=
11545 		     offsetof(struct pcpu_dstats, tx_bytes));
11546 	BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, tx_packets) !=
11547 		     offsetof(struct pcpu_dstats, tx_packets));
11548 
11549 	if (ops->ndo_get_stats64) {
11550 		memset(storage, 0, sizeof(*storage));
11551 		ops->ndo_get_stats64(dev, storage);
11552 	} else if (ops->ndo_get_stats) {
11553 		netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
11554 	} else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_TSTATS) {
11555 		dev_get_tstats64(dev, storage);
11556 	} else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_DSTATS) {
11557 		dev_get_dstats64(dev, storage);
11558 	} else {
11559 		netdev_stats_to_stats64(storage, &dev->stats);
11560 	}
11561 
11562 	/* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
11563 	p = READ_ONCE(dev->core_stats);
11564 	if (p) {
11565 		const struct net_device_core_stats *core_stats;
11566 		int i;
11567 
11568 		for_each_possible_cpu(i) {
11569 			core_stats = per_cpu_ptr(p, i);
11570 			storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
11571 			storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
11572 			storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
11573 			storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped);
11574 		}
11575 	}
11576 	return storage;
11577 }
11578 EXPORT_SYMBOL(dev_get_stats);
11579 
11580 /**
11581  *	dev_fetch_sw_netstats - get per-cpu network device statistics
11582  *	@s: place to store stats
11583  *	@netstats: per-cpu network stats to read from
11584  *
11585  *	Read per-cpu network statistics and populate the related fields in @s.
11586  */
dev_fetch_sw_netstats(struct rtnl_link_stats64 * s,const struct pcpu_sw_netstats __percpu * netstats)11587 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
11588 			   const struct pcpu_sw_netstats __percpu *netstats)
11589 {
11590 	int cpu;
11591 
11592 	for_each_possible_cpu(cpu) {
11593 		u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
11594 		const struct pcpu_sw_netstats *stats;
11595 		unsigned int start;
11596 
11597 		stats = per_cpu_ptr(netstats, cpu);
11598 		do {
11599 			start = u64_stats_fetch_begin(&stats->syncp);
11600 			rx_packets = u64_stats_read(&stats->rx_packets);
11601 			rx_bytes   = u64_stats_read(&stats->rx_bytes);
11602 			tx_packets = u64_stats_read(&stats->tx_packets);
11603 			tx_bytes   = u64_stats_read(&stats->tx_bytes);
11604 		} while (u64_stats_fetch_retry(&stats->syncp, start));
11605 
11606 		s->rx_packets += rx_packets;
11607 		s->rx_bytes   += rx_bytes;
11608 		s->tx_packets += tx_packets;
11609 		s->tx_bytes   += tx_bytes;
11610 	}
11611 }
11612 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
11613 
11614 /**
11615  *	dev_get_tstats64 - ndo_get_stats64 implementation
11616  *	@dev: device to get statistics from
11617  *	@s: place to store stats
11618  *
11619  *	Populate @s from dev->stats and dev->tstats. Can be used as
11620  *	ndo_get_stats64() callback.
11621  */
dev_get_tstats64(struct net_device * dev,struct rtnl_link_stats64 * s)11622 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
11623 {
11624 	netdev_stats_to_stats64(s, &dev->stats);
11625 	dev_fetch_sw_netstats(s, dev->tstats);
11626 }
11627 EXPORT_SYMBOL_GPL(dev_get_tstats64);
11628 
dev_ingress_queue_create(struct net_device * dev)11629 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
11630 {
11631 	struct netdev_queue *queue = dev_ingress_queue(dev);
11632 
11633 #ifdef CONFIG_NET_CLS_ACT
11634 	if (queue)
11635 		return queue;
11636 	queue = kzalloc(sizeof(*queue), GFP_KERNEL);
11637 	if (!queue)
11638 		return NULL;
11639 	netdev_init_one_queue(dev, queue, NULL);
11640 	RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
11641 	RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc);
11642 	rcu_assign_pointer(dev->ingress_queue, queue);
11643 #endif
11644 	return queue;
11645 }
11646 
11647 static const struct ethtool_ops default_ethtool_ops;
11648 
netdev_set_default_ethtool_ops(struct net_device * dev,const struct ethtool_ops * ops)11649 void netdev_set_default_ethtool_ops(struct net_device *dev,
11650 				    const struct ethtool_ops *ops)
11651 {
11652 	if (dev->ethtool_ops == &default_ethtool_ops)
11653 		dev->ethtool_ops = ops;
11654 }
11655 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
11656 
11657 /**
11658  * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default
11659  * @dev: netdev to enable the IRQ coalescing on
11660  *
11661  * Sets a conservative default for SW IRQ coalescing. Users can use
11662  * sysfs attributes to override the default values.
11663  */
netdev_sw_irq_coalesce_default_on(struct net_device * dev)11664 void netdev_sw_irq_coalesce_default_on(struct net_device *dev)
11665 {
11666 	WARN_ON(dev->reg_state == NETREG_REGISTERED);
11667 
11668 	if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
11669 		netdev_set_gro_flush_timeout(dev, 20000);
11670 		netdev_set_defer_hard_irqs(dev, 1);
11671 	}
11672 }
11673 EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on);
11674 
11675 /**
11676  * alloc_netdev_mqs - allocate network device
11677  * @sizeof_priv: size of private data to allocate space for
11678  * @name: device name format string
11679  * @name_assign_type: origin of device name
11680  * @setup: callback to initialize device
11681  * @txqs: the number of TX subqueues to allocate
11682  * @rxqs: the number of RX subqueues to allocate
11683  *
11684  * Allocates a struct net_device with private data area for driver use
11685  * and performs basic initialization.  Also allocates subqueue structs
11686  * for each queue on the device.
11687  */
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)11688 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
11689 		unsigned char name_assign_type,
11690 		void (*setup)(struct net_device *),
11691 		unsigned int txqs, unsigned int rxqs)
11692 {
11693 	struct net_device *dev;
11694 	size_t napi_config_sz;
11695 	unsigned int maxqs;
11696 
11697 	BUG_ON(strlen(name) >= sizeof(dev->name));
11698 
11699 	if (txqs < 1) {
11700 		pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
11701 		return NULL;
11702 	}
11703 
11704 	if (rxqs < 1) {
11705 		pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
11706 		return NULL;
11707 	}
11708 
11709 	maxqs = max(txqs, rxqs);
11710 
11711 	dev = kvzalloc(struct_size(dev, priv, sizeof_priv),
11712 		       GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
11713 	if (!dev)
11714 		return NULL;
11715 
11716 	dev->priv_len = sizeof_priv;
11717 
11718 	ref_tracker_dir_init(&dev->refcnt_tracker, 128, name);
11719 #ifdef CONFIG_PCPU_DEV_REFCNT
11720 	dev->pcpu_refcnt = alloc_percpu(int);
11721 	if (!dev->pcpu_refcnt)
11722 		goto free_dev;
11723 	__dev_hold(dev);
11724 #else
11725 	refcount_set(&dev->dev_refcnt, 1);
11726 #endif
11727 
11728 	if (dev_addr_init(dev))
11729 		goto free_pcpu;
11730 
11731 	dev_mc_init(dev);
11732 	dev_uc_init(dev);
11733 
11734 	dev_net_set(dev, &init_net);
11735 
11736 	dev->gso_max_size = GSO_LEGACY_MAX_SIZE;
11737 	dev->xdp_zc_max_segs = 1;
11738 	dev->gso_max_segs = GSO_MAX_SEGS;
11739 	dev->gro_max_size = GRO_LEGACY_MAX_SIZE;
11740 	dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE;
11741 	dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE;
11742 	dev->tso_max_size = TSO_LEGACY_MAX_SIZE;
11743 	dev->tso_max_segs = TSO_MAX_SEGS;
11744 	dev->upper_level = 1;
11745 	dev->lower_level = 1;
11746 #ifdef CONFIG_LOCKDEP
11747 	dev->nested_level = 0;
11748 	INIT_LIST_HEAD(&dev->unlink_list);
11749 #endif
11750 
11751 	INIT_LIST_HEAD(&dev->napi_list);
11752 	INIT_LIST_HEAD(&dev->unreg_list);
11753 	INIT_LIST_HEAD(&dev->close_list);
11754 	INIT_LIST_HEAD(&dev->link_watch_list);
11755 	INIT_LIST_HEAD(&dev->adj_list.upper);
11756 	INIT_LIST_HEAD(&dev->adj_list.lower);
11757 	INIT_LIST_HEAD(&dev->ptype_all);
11758 	INIT_LIST_HEAD(&dev->ptype_specific);
11759 	INIT_LIST_HEAD(&dev->net_notifier_list);
11760 #ifdef CONFIG_NET_SCHED
11761 	hash_init(dev->qdisc_hash);
11762 #endif
11763 
11764 	mutex_init(&dev->lock);
11765 
11766 	dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
11767 	setup(dev);
11768 
11769 	if (!dev->tx_queue_len) {
11770 		dev->priv_flags |= IFF_NO_QUEUE;
11771 		dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
11772 	}
11773 
11774 	dev->num_tx_queues = txqs;
11775 	dev->real_num_tx_queues = txqs;
11776 	if (netif_alloc_netdev_queues(dev))
11777 		goto free_all;
11778 
11779 	dev->num_rx_queues = rxqs;
11780 	dev->real_num_rx_queues = rxqs;
11781 	if (netif_alloc_rx_queues(dev))
11782 		goto free_all;
11783 	dev->ethtool = kzalloc(sizeof(*dev->ethtool), GFP_KERNEL_ACCOUNT);
11784 	if (!dev->ethtool)
11785 		goto free_all;
11786 
11787 	dev->cfg = kzalloc(sizeof(*dev->cfg), GFP_KERNEL_ACCOUNT);
11788 	if (!dev->cfg)
11789 		goto free_all;
11790 	dev->cfg_pending = dev->cfg;
11791 
11792 	napi_config_sz = array_size(maxqs, sizeof(*dev->napi_config));
11793 	dev->napi_config = kvzalloc(napi_config_sz, GFP_KERNEL_ACCOUNT);
11794 	if (!dev->napi_config)
11795 		goto free_all;
11796 
11797 	strscpy(dev->name, name);
11798 	dev->name_assign_type = name_assign_type;
11799 	dev->group = INIT_NETDEV_GROUP;
11800 	if (!dev->ethtool_ops)
11801 		dev->ethtool_ops = &default_ethtool_ops;
11802 
11803 	nf_hook_netdev_init(dev);
11804 
11805 	return dev;
11806 
11807 free_all:
11808 	free_netdev(dev);
11809 	return NULL;
11810 
11811 free_pcpu:
11812 #ifdef CONFIG_PCPU_DEV_REFCNT
11813 	free_percpu(dev->pcpu_refcnt);
11814 free_dev:
11815 #endif
11816 	kvfree(dev);
11817 	return NULL;
11818 }
11819 EXPORT_SYMBOL(alloc_netdev_mqs);
11820 
netdev_napi_exit(struct net_device * dev)11821 static void netdev_napi_exit(struct net_device *dev)
11822 {
11823 	if (!list_empty(&dev->napi_list)) {
11824 		struct napi_struct *p, *n;
11825 
11826 		netdev_lock(dev);
11827 		list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
11828 			__netif_napi_del_locked(p);
11829 		netdev_unlock(dev);
11830 
11831 		synchronize_net();
11832 	}
11833 
11834 	kvfree(dev->napi_config);
11835 }
11836 
11837 /**
11838  * free_netdev - free network device
11839  * @dev: device
11840  *
11841  * This function does the last stage of destroying an allocated device
11842  * interface. The reference to the device object is released. If this
11843  * is the last reference then it will be freed.Must be called in process
11844  * context.
11845  */
free_netdev(struct net_device * dev)11846 void free_netdev(struct net_device *dev)
11847 {
11848 	might_sleep();
11849 
11850 	/* When called immediately after register_netdevice() failed the unwind
11851 	 * handling may still be dismantling the device. Handle that case by
11852 	 * deferring the free.
11853 	 */
11854 	if (dev->reg_state == NETREG_UNREGISTERING) {
11855 		ASSERT_RTNL();
11856 		dev->needs_free_netdev = true;
11857 		return;
11858 	}
11859 
11860 	WARN_ON(dev->cfg != dev->cfg_pending);
11861 	kfree(dev->cfg);
11862 	kfree(dev->ethtool);
11863 	netif_free_tx_queues(dev);
11864 	netif_free_rx_queues(dev);
11865 
11866 	kfree(rcu_dereference_protected(dev->ingress_queue, 1));
11867 
11868 	/* Flush device addresses */
11869 	dev_addr_flush(dev);
11870 
11871 	netdev_napi_exit(dev);
11872 
11873 	netif_del_cpu_rmap(dev);
11874 
11875 	ref_tracker_dir_exit(&dev->refcnt_tracker);
11876 #ifdef CONFIG_PCPU_DEV_REFCNT
11877 	free_percpu(dev->pcpu_refcnt);
11878 	dev->pcpu_refcnt = NULL;
11879 #endif
11880 	free_percpu(dev->core_stats);
11881 	dev->core_stats = NULL;
11882 	free_percpu(dev->xdp_bulkq);
11883 	dev->xdp_bulkq = NULL;
11884 
11885 	netdev_free_phy_link_topology(dev);
11886 
11887 	mutex_destroy(&dev->lock);
11888 
11889 	/*  Compatibility with error handling in drivers */
11890 	if (dev->reg_state == NETREG_UNINITIALIZED ||
11891 	    dev->reg_state == NETREG_DUMMY) {
11892 		kvfree(dev);
11893 		return;
11894 	}
11895 
11896 	BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
11897 	WRITE_ONCE(dev->reg_state, NETREG_RELEASED);
11898 
11899 	/* will free via device release */
11900 	put_device(&dev->dev);
11901 }
11902 EXPORT_SYMBOL(free_netdev);
11903 
11904 /**
11905  * alloc_netdev_dummy - Allocate and initialize a dummy net device.
11906  * @sizeof_priv: size of private data to allocate space for
11907  *
11908  * Return: the allocated net_device on success, NULL otherwise
11909  */
alloc_netdev_dummy(int sizeof_priv)11910 struct net_device *alloc_netdev_dummy(int sizeof_priv)
11911 {
11912 	return alloc_netdev(sizeof_priv, "dummy#", NET_NAME_UNKNOWN,
11913 			    init_dummy_netdev);
11914 }
11915 EXPORT_SYMBOL_GPL(alloc_netdev_dummy);
11916 
11917 /**
11918  *	synchronize_net -  Synchronize with packet receive processing
11919  *
11920  *	Wait for packets currently being received to be done.
11921  *	Does not block later packets from starting.
11922  */
synchronize_net(void)11923 void synchronize_net(void)
11924 {
11925 	might_sleep();
11926 	if (from_cleanup_net() || rtnl_is_locked())
11927 		synchronize_rcu_expedited();
11928 	else
11929 		synchronize_rcu();
11930 }
11931 EXPORT_SYMBOL(synchronize_net);
11932 
netdev_rss_contexts_free(struct net_device * dev)11933 static void netdev_rss_contexts_free(struct net_device *dev)
11934 {
11935 	struct ethtool_rxfh_context *ctx;
11936 	unsigned long context;
11937 
11938 	mutex_lock(&dev->ethtool->rss_lock);
11939 	xa_for_each(&dev->ethtool->rss_ctx, context, ctx) {
11940 		struct ethtool_rxfh_param rxfh;
11941 
11942 		rxfh.indir = ethtool_rxfh_context_indir(ctx);
11943 		rxfh.key = ethtool_rxfh_context_key(ctx);
11944 		rxfh.hfunc = ctx->hfunc;
11945 		rxfh.input_xfrm = ctx->input_xfrm;
11946 		rxfh.rss_context = context;
11947 		rxfh.rss_delete = true;
11948 
11949 		xa_erase(&dev->ethtool->rss_ctx, context);
11950 		if (dev->ethtool_ops->create_rxfh_context)
11951 			dev->ethtool_ops->remove_rxfh_context(dev, ctx,
11952 							      context, NULL);
11953 		else
11954 			dev->ethtool_ops->set_rxfh(dev, &rxfh, NULL);
11955 		kfree(ctx);
11956 	}
11957 	xa_destroy(&dev->ethtool->rss_ctx);
11958 	mutex_unlock(&dev->ethtool->rss_lock);
11959 }
11960 
11961 /**
11962  *	unregister_netdevice_queue - remove device from the kernel
11963  *	@dev: device
11964  *	@head: list
11965  *
11966  *	This function shuts down a device interface and removes it
11967  *	from the kernel tables.
11968  *	If head not NULL, device is queued to be unregistered later.
11969  *
11970  *	Callers must hold the rtnl semaphore.  You may want
11971  *	unregister_netdev() instead of this.
11972  */
11973 
unregister_netdevice_queue(struct net_device * dev,struct list_head * head)11974 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
11975 {
11976 	ASSERT_RTNL();
11977 
11978 	if (head) {
11979 		list_move_tail(&dev->unreg_list, head);
11980 	} else {
11981 		LIST_HEAD(single);
11982 
11983 		list_add(&dev->unreg_list, &single);
11984 		unregister_netdevice_many(&single);
11985 	}
11986 }
11987 EXPORT_SYMBOL(unregister_netdevice_queue);
11988 
dev_memory_provider_uninstall(struct net_device * dev)11989 static void dev_memory_provider_uninstall(struct net_device *dev)
11990 {
11991 	unsigned int i;
11992 
11993 	for (i = 0; i < dev->real_num_rx_queues; i++) {
11994 		struct netdev_rx_queue *rxq = &dev->_rx[i];
11995 		struct pp_memory_provider_params *p = &rxq->mp_params;
11996 
11997 		if (p->mp_ops && p->mp_ops->uninstall)
11998 			p->mp_ops->uninstall(rxq->mp_params.mp_priv, rxq);
11999 	}
12000 }
12001 
unregister_netdevice_many_notify(struct list_head * head,u32 portid,const struct nlmsghdr * nlh)12002 void unregister_netdevice_many_notify(struct list_head *head,
12003 				      u32 portid, const struct nlmsghdr *nlh)
12004 {
12005 	struct net_device *dev, *tmp;
12006 	LIST_HEAD(close_head);
12007 	int cnt = 0;
12008 
12009 	BUG_ON(dev_boot_phase);
12010 	ASSERT_RTNL();
12011 
12012 	if (list_empty(head))
12013 		return;
12014 
12015 	list_for_each_entry_safe(dev, tmp, head, unreg_list) {
12016 		/* Some devices call without registering
12017 		 * for initialization unwind. Remove those
12018 		 * devices and proceed with the remaining.
12019 		 */
12020 		if (dev->reg_state == NETREG_UNINITIALIZED) {
12021 			pr_debug("unregister_netdevice: device %s/%p never was registered\n",
12022 				 dev->name, dev);
12023 
12024 			WARN_ON(1);
12025 			list_del(&dev->unreg_list);
12026 			continue;
12027 		}
12028 		dev->dismantle = true;
12029 		BUG_ON(dev->reg_state != NETREG_REGISTERED);
12030 	}
12031 
12032 	/* If device is running, close it first. Start with ops locked... */
12033 	list_for_each_entry(dev, head, unreg_list) {
12034 		if (netdev_need_ops_lock(dev)) {
12035 			list_add_tail(&dev->close_list, &close_head);
12036 			netdev_lock(dev);
12037 		}
12038 	}
12039 	dev_close_many(&close_head, true);
12040 	/* ... now unlock them and go over the rest. */
12041 	list_for_each_entry(dev, head, unreg_list) {
12042 		if (netdev_need_ops_lock(dev))
12043 			netdev_unlock(dev);
12044 		else
12045 			list_add_tail(&dev->close_list, &close_head);
12046 	}
12047 	dev_close_many(&close_head, true);
12048 
12049 	list_for_each_entry(dev, head, unreg_list) {
12050 		/* And unlink it from device chain. */
12051 		unlist_netdevice(dev);
12052 		netdev_lock(dev);
12053 		WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERING);
12054 		netdev_unlock(dev);
12055 	}
12056 	flush_all_backlogs();
12057 
12058 	synchronize_net();
12059 
12060 	list_for_each_entry(dev, head, unreg_list) {
12061 		struct sk_buff *skb = NULL;
12062 
12063 		/* Shutdown queueing discipline. */
12064 		netdev_lock_ops(dev);
12065 		dev_shutdown(dev);
12066 		dev_tcx_uninstall(dev);
12067 		dev_xdp_uninstall(dev);
12068 		dev_memory_provider_uninstall(dev);
12069 		netdev_unlock_ops(dev);
12070 		bpf_dev_bound_netdev_unregister(dev);
12071 
12072 		netdev_offload_xstats_disable_all(dev);
12073 
12074 		/* Notify protocols, that we are about to destroy
12075 		 * this device. They should clean all the things.
12076 		 */
12077 		call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
12078 
12079 		if (!(dev->rtnl_link_ops && dev->rtnl_link_initializing))
12080 			skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
12081 						     GFP_KERNEL, NULL, 0,
12082 						     portid, nlh);
12083 
12084 		/*
12085 		 *	Flush the unicast and multicast chains
12086 		 */
12087 		dev_uc_flush(dev);
12088 		dev_mc_flush(dev);
12089 
12090 		netdev_name_node_alt_flush(dev);
12091 		netdev_name_node_free(dev->name_node);
12092 
12093 		netdev_rss_contexts_free(dev);
12094 
12095 		call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
12096 
12097 		if (dev->netdev_ops->ndo_uninit)
12098 			dev->netdev_ops->ndo_uninit(dev);
12099 
12100 		mutex_destroy(&dev->ethtool->rss_lock);
12101 
12102 		net_shaper_flush_netdev(dev);
12103 
12104 		if (skb)
12105 			rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh);
12106 
12107 		/* Notifier chain MUST detach us all upper devices. */
12108 		WARN_ON(netdev_has_any_upper_dev(dev));
12109 		WARN_ON(netdev_has_any_lower_dev(dev));
12110 
12111 		/* Remove entries from kobject tree */
12112 		netdev_unregister_kobject(dev);
12113 #ifdef CONFIG_XPS
12114 		/* Remove XPS queueing entries */
12115 		netif_reset_xps_queues_gt(dev, 0);
12116 #endif
12117 	}
12118 
12119 	synchronize_net();
12120 
12121 	list_for_each_entry(dev, head, unreg_list) {
12122 		netdev_put(dev, &dev->dev_registered_tracker);
12123 		net_set_todo(dev);
12124 		cnt++;
12125 	}
12126 	atomic_add(cnt, &dev_unreg_count);
12127 
12128 	list_del(head);
12129 }
12130 
12131 /**
12132  *	unregister_netdevice_many - unregister many devices
12133  *	@head: list of devices
12134  *
12135  *  Note: As most callers use a stack allocated list_head,
12136  *  we force a list_del() to make sure stack won't be corrupted later.
12137  */
unregister_netdevice_many(struct list_head * head)12138 void unregister_netdevice_many(struct list_head *head)
12139 {
12140 	unregister_netdevice_many_notify(head, 0, NULL);
12141 }
12142 EXPORT_SYMBOL(unregister_netdevice_many);
12143 
12144 /**
12145  *	unregister_netdev - remove device from the kernel
12146  *	@dev: device
12147  *
12148  *	This function shuts down a device interface and removes it
12149  *	from the kernel tables.
12150  *
12151  *	This is just a wrapper for unregister_netdevice that takes
12152  *	the rtnl semaphore.  In general you want to use this and not
12153  *	unregister_netdevice.
12154  */
unregister_netdev(struct net_device * dev)12155 void unregister_netdev(struct net_device *dev)
12156 {
12157 	rtnl_net_dev_lock(dev);
12158 	unregister_netdevice(dev);
12159 	rtnl_net_dev_unlock(dev);
12160 }
12161 EXPORT_SYMBOL(unregister_netdev);
12162 
__dev_change_net_namespace(struct net_device * dev,struct net * net,const char * pat,int new_ifindex,struct netlink_ext_ack * extack)12163 int __dev_change_net_namespace(struct net_device *dev, struct net *net,
12164 			       const char *pat, int new_ifindex,
12165 			       struct netlink_ext_ack *extack)
12166 {
12167 	struct netdev_name_node *name_node;
12168 	struct net *net_old = dev_net(dev);
12169 	char new_name[IFNAMSIZ] = {};
12170 	int err, new_nsid;
12171 
12172 	ASSERT_RTNL();
12173 
12174 	/* Don't allow namespace local devices to be moved. */
12175 	err = -EINVAL;
12176 	if (dev->netns_immutable) {
12177 		NL_SET_ERR_MSG(extack, "The interface netns is immutable");
12178 		goto out;
12179 	}
12180 
12181 	/* Ensure the device has been registered */
12182 	if (dev->reg_state != NETREG_REGISTERED) {
12183 		NL_SET_ERR_MSG(extack, "The interface isn't registered");
12184 		goto out;
12185 	}
12186 
12187 	/* Get out if there is nothing todo */
12188 	err = 0;
12189 	if (net_eq(net_old, net))
12190 		goto out;
12191 
12192 	/* Pick the destination device name, and ensure
12193 	 * we can use it in the destination network namespace.
12194 	 */
12195 	err = -EEXIST;
12196 	if (netdev_name_in_use(net, dev->name)) {
12197 		/* We get here if we can't use the current device name */
12198 		if (!pat) {
12199 			NL_SET_ERR_MSG(extack,
12200 				       "An interface with the same name exists in the target netns");
12201 			goto out;
12202 		}
12203 		err = dev_prep_valid_name(net, dev, pat, new_name, EEXIST);
12204 		if (err < 0) {
12205 			NL_SET_ERR_MSG_FMT(extack,
12206 					   "Unable to use '%s' for the new interface name in the target netns",
12207 					   pat);
12208 			goto out;
12209 		}
12210 	}
12211 	/* Check that none of the altnames conflicts. */
12212 	err = -EEXIST;
12213 	netdev_for_each_altname(dev, name_node) {
12214 		if (netdev_name_in_use(net, name_node->name)) {
12215 			NL_SET_ERR_MSG_FMT(extack,
12216 					   "An interface with the altname %s exists in the target netns",
12217 					   name_node->name);
12218 			goto out;
12219 		}
12220 	}
12221 
12222 	/* Check that new_ifindex isn't used yet. */
12223 	if (new_ifindex) {
12224 		err = dev_index_reserve(net, new_ifindex);
12225 		if (err < 0) {
12226 			NL_SET_ERR_MSG_FMT(extack,
12227 					   "The ifindex %d is not available in the target netns",
12228 					   new_ifindex);
12229 			goto out;
12230 		}
12231 	} else {
12232 		/* If there is an ifindex conflict assign a new one */
12233 		err = dev_index_reserve(net, dev->ifindex);
12234 		if (err == -EBUSY)
12235 			err = dev_index_reserve(net, 0);
12236 		if (err < 0) {
12237 			NL_SET_ERR_MSG(extack,
12238 				       "Unable to allocate a new ifindex in the target netns");
12239 			goto out;
12240 		}
12241 		new_ifindex = err;
12242 	}
12243 
12244 	/*
12245 	 * And now a mini version of register_netdevice unregister_netdevice.
12246 	 */
12247 
12248 	netdev_lock_ops(dev);
12249 	/* If device is running close it first. */
12250 	netif_close(dev);
12251 	/* And unlink it from device chain */
12252 	unlist_netdevice(dev);
12253 
12254 	if (!netdev_need_ops_lock(dev))
12255 		netdev_lock(dev);
12256 	dev->moving_ns = true;
12257 	netdev_unlock(dev);
12258 
12259 	synchronize_net();
12260 
12261 	/* Shutdown queueing discipline. */
12262 	netdev_lock_ops(dev);
12263 	dev_shutdown(dev);
12264 	netdev_unlock_ops(dev);
12265 
12266 	/* Notify protocols, that we are about to destroy
12267 	 * this device. They should clean all the things.
12268 	 *
12269 	 * Note that dev->reg_state stays at NETREG_REGISTERED.
12270 	 * This is wanted because this way 8021q and macvlan know
12271 	 * the device is just moving and can keep their slaves up.
12272 	 */
12273 	call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
12274 	rcu_barrier();
12275 
12276 	new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
12277 
12278 	rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
12279 			    new_ifindex);
12280 
12281 	/*
12282 	 *	Flush the unicast and multicast chains
12283 	 */
12284 	dev_uc_flush(dev);
12285 	dev_mc_flush(dev);
12286 
12287 	/* Send a netdev-removed uevent to the old namespace */
12288 	kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
12289 	netdev_adjacent_del_links(dev);
12290 
12291 	/* Move per-net netdevice notifiers that are following the netdevice */
12292 	move_netdevice_notifiers_dev_net(dev, net);
12293 
12294 	/* Actually switch the network namespace */
12295 	netdev_lock(dev);
12296 	dev_net_set(dev, net);
12297 	netdev_unlock(dev);
12298 	dev->ifindex = new_ifindex;
12299 
12300 	if (new_name[0]) {
12301 		/* Rename the netdev to prepared name */
12302 		write_seqlock_bh(&netdev_rename_lock);
12303 		strscpy(dev->name, new_name, IFNAMSIZ);
12304 		write_sequnlock_bh(&netdev_rename_lock);
12305 	}
12306 
12307 	/* Fixup kobjects */
12308 	dev_set_uevent_suppress(&dev->dev, 1);
12309 	err = device_rename(&dev->dev, dev->name);
12310 	dev_set_uevent_suppress(&dev->dev, 0);
12311 	WARN_ON(err);
12312 
12313 	/* Send a netdev-add uevent to the new namespace */
12314 	kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
12315 	netdev_adjacent_add_links(dev);
12316 
12317 	/* Adapt owner in case owning user namespace of target network
12318 	 * namespace is different from the original one.
12319 	 */
12320 	err = netdev_change_owner(dev, net_old, net);
12321 	WARN_ON(err);
12322 
12323 	netdev_lock(dev);
12324 	dev->moving_ns = false;
12325 	if (!netdev_need_ops_lock(dev))
12326 		netdev_unlock(dev);
12327 
12328 	/* Add the device back in the hashes */
12329 	list_netdevice(dev);
12330 	/* Notify protocols, that a new device appeared. */
12331 	call_netdevice_notifiers(NETDEV_REGISTER, dev);
12332 	netdev_unlock_ops(dev);
12333 
12334 	/*
12335 	 *	Prevent userspace races by waiting until the network
12336 	 *	device is fully setup before sending notifications.
12337 	 */
12338 	rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
12339 
12340 	synchronize_net();
12341 	err = 0;
12342 out:
12343 	return err;
12344 }
12345 
dev_cpu_dead(unsigned int oldcpu)12346 static int dev_cpu_dead(unsigned int oldcpu)
12347 {
12348 	struct sk_buff **list_skb;
12349 	struct sk_buff *skb;
12350 	unsigned int cpu;
12351 	struct softnet_data *sd, *oldsd, *remsd = NULL;
12352 
12353 	local_irq_disable();
12354 	cpu = smp_processor_id();
12355 	sd = &per_cpu(softnet_data, cpu);
12356 	oldsd = &per_cpu(softnet_data, oldcpu);
12357 
12358 	/* Find end of our completion_queue. */
12359 	list_skb = &sd->completion_queue;
12360 	while (*list_skb)
12361 		list_skb = &(*list_skb)->next;
12362 	/* Append completion queue from offline CPU. */
12363 	*list_skb = oldsd->completion_queue;
12364 	oldsd->completion_queue = NULL;
12365 
12366 	/* Append output queue from offline CPU. */
12367 	if (oldsd->output_queue) {
12368 		*sd->output_queue_tailp = oldsd->output_queue;
12369 		sd->output_queue_tailp = oldsd->output_queue_tailp;
12370 		oldsd->output_queue = NULL;
12371 		oldsd->output_queue_tailp = &oldsd->output_queue;
12372 	}
12373 	/* Append NAPI poll list from offline CPU, with one exception :
12374 	 * process_backlog() must be called by cpu owning percpu backlog.
12375 	 * We properly handle process_queue & input_pkt_queue later.
12376 	 */
12377 	while (!list_empty(&oldsd->poll_list)) {
12378 		struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
12379 							    struct napi_struct,
12380 							    poll_list);
12381 
12382 		list_del_init(&napi->poll_list);
12383 		if (napi->poll == process_backlog)
12384 			napi->state &= NAPIF_STATE_THREADED;
12385 		else
12386 			____napi_schedule(sd, napi);
12387 	}
12388 
12389 	raise_softirq_irqoff(NET_TX_SOFTIRQ);
12390 	local_irq_enable();
12391 
12392 	if (!use_backlog_threads()) {
12393 #ifdef CONFIG_RPS
12394 		remsd = oldsd->rps_ipi_list;
12395 		oldsd->rps_ipi_list = NULL;
12396 #endif
12397 		/* send out pending IPI's on offline CPU */
12398 		net_rps_send_ipi(remsd);
12399 	}
12400 
12401 	/* Process offline CPU's input_pkt_queue */
12402 	while ((skb = __skb_dequeue(&oldsd->process_queue))) {
12403 		netif_rx(skb);
12404 		rps_input_queue_head_incr(oldsd);
12405 	}
12406 	while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
12407 		netif_rx(skb);
12408 		rps_input_queue_head_incr(oldsd);
12409 	}
12410 
12411 	return 0;
12412 }
12413 
12414 /**
12415  *	netdev_increment_features - increment feature set by one
12416  *	@all: current feature set
12417  *	@one: new feature set
12418  *	@mask: mask feature set
12419  *
12420  *	Computes a new feature set after adding a device with feature set
12421  *	@one to the master device with current feature set @all.  Will not
12422  *	enable anything that is off in @mask. Returns the new feature set.
12423  */
netdev_increment_features(netdev_features_t all,netdev_features_t one,netdev_features_t mask)12424 netdev_features_t netdev_increment_features(netdev_features_t all,
12425 	netdev_features_t one, netdev_features_t mask)
12426 {
12427 	if (mask & NETIF_F_HW_CSUM)
12428 		mask |= NETIF_F_CSUM_MASK;
12429 	mask |= NETIF_F_VLAN_CHALLENGED;
12430 
12431 	all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
12432 	all &= one | ~NETIF_F_ALL_FOR_ALL;
12433 
12434 	/* If one device supports hw checksumming, set for all. */
12435 	if (all & NETIF_F_HW_CSUM)
12436 		all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
12437 
12438 	return all;
12439 }
12440 EXPORT_SYMBOL(netdev_increment_features);
12441 
netdev_create_hash(void)12442 static struct hlist_head * __net_init netdev_create_hash(void)
12443 {
12444 	int i;
12445 	struct hlist_head *hash;
12446 
12447 	hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
12448 	if (hash != NULL)
12449 		for (i = 0; i < NETDEV_HASHENTRIES; i++)
12450 			INIT_HLIST_HEAD(&hash[i]);
12451 
12452 	return hash;
12453 }
12454 
12455 /* Initialize per network namespace state */
netdev_init(struct net * net)12456 static int __net_init netdev_init(struct net *net)
12457 {
12458 	BUILD_BUG_ON(GRO_HASH_BUCKETS >
12459 		     BITS_PER_BYTE * sizeof_field(struct gro_node, bitmask));
12460 
12461 	INIT_LIST_HEAD(&net->dev_base_head);
12462 
12463 	net->dev_name_head = netdev_create_hash();
12464 	if (net->dev_name_head == NULL)
12465 		goto err_name;
12466 
12467 	net->dev_index_head = netdev_create_hash();
12468 	if (net->dev_index_head == NULL)
12469 		goto err_idx;
12470 
12471 	xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1);
12472 
12473 	RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
12474 
12475 	return 0;
12476 
12477 err_idx:
12478 	kfree(net->dev_name_head);
12479 err_name:
12480 	return -ENOMEM;
12481 }
12482 
12483 /**
12484  *	netdev_drivername - network driver for the device
12485  *	@dev: network device
12486  *
12487  *	Determine network driver for device.
12488  */
netdev_drivername(const struct net_device * dev)12489 const char *netdev_drivername(const struct net_device *dev)
12490 {
12491 	const struct device_driver *driver;
12492 	const struct device *parent;
12493 	const char *empty = "";
12494 
12495 	parent = dev->dev.parent;
12496 	if (!parent)
12497 		return empty;
12498 
12499 	driver = parent->driver;
12500 	if (driver && driver->name)
12501 		return driver->name;
12502 	return empty;
12503 }
12504 
__netdev_printk(const char * level,const struct net_device * dev,struct va_format * vaf)12505 static void __netdev_printk(const char *level, const struct net_device *dev,
12506 			    struct va_format *vaf)
12507 {
12508 	if (dev && dev->dev.parent) {
12509 		dev_printk_emit(level[1] - '0',
12510 				dev->dev.parent,
12511 				"%s %s %s%s: %pV",
12512 				dev_driver_string(dev->dev.parent),
12513 				dev_name(dev->dev.parent),
12514 				netdev_name(dev), netdev_reg_state(dev),
12515 				vaf);
12516 	} else if (dev) {
12517 		printk("%s%s%s: %pV",
12518 		       level, netdev_name(dev), netdev_reg_state(dev), vaf);
12519 	} else {
12520 		printk("%s(NULL net_device): %pV", level, vaf);
12521 	}
12522 }
12523 
netdev_printk(const char * level,const struct net_device * dev,const char * format,...)12524 void netdev_printk(const char *level, const struct net_device *dev,
12525 		   const char *format, ...)
12526 {
12527 	struct va_format vaf;
12528 	va_list args;
12529 
12530 	va_start(args, format);
12531 
12532 	vaf.fmt = format;
12533 	vaf.va = &args;
12534 
12535 	__netdev_printk(level, dev, &vaf);
12536 
12537 	va_end(args);
12538 }
12539 EXPORT_SYMBOL(netdev_printk);
12540 
12541 #define define_netdev_printk_level(func, level)			\
12542 void func(const struct net_device *dev, const char *fmt, ...)	\
12543 {								\
12544 	struct va_format vaf;					\
12545 	va_list args;						\
12546 								\
12547 	va_start(args, fmt);					\
12548 								\
12549 	vaf.fmt = fmt;						\
12550 	vaf.va = &args;						\
12551 								\
12552 	__netdev_printk(level, dev, &vaf);			\
12553 								\
12554 	va_end(args);						\
12555 }								\
12556 EXPORT_SYMBOL(func);
12557 
12558 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
12559 define_netdev_printk_level(netdev_alert, KERN_ALERT);
12560 define_netdev_printk_level(netdev_crit, KERN_CRIT);
12561 define_netdev_printk_level(netdev_err, KERN_ERR);
12562 define_netdev_printk_level(netdev_warn, KERN_WARNING);
12563 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
12564 define_netdev_printk_level(netdev_info, KERN_INFO);
12565 
netdev_exit(struct net * net)12566 static void __net_exit netdev_exit(struct net *net)
12567 {
12568 	kfree(net->dev_name_head);
12569 	kfree(net->dev_index_head);
12570 	xa_destroy(&net->dev_by_index);
12571 	if (net != &init_net)
12572 		WARN_ON_ONCE(!list_empty(&net->dev_base_head));
12573 }
12574 
12575 static struct pernet_operations __net_initdata netdev_net_ops = {
12576 	.init = netdev_init,
12577 	.exit = netdev_exit,
12578 };
12579 
default_device_exit_net(struct net * net)12580 static void __net_exit default_device_exit_net(struct net *net)
12581 {
12582 	struct netdev_name_node *name_node, *tmp;
12583 	struct net_device *dev, *aux;
12584 	/*
12585 	 * Push all migratable network devices back to the
12586 	 * initial network namespace
12587 	 */
12588 	ASSERT_RTNL();
12589 	for_each_netdev_safe(net, dev, aux) {
12590 		int err;
12591 		char fb_name[IFNAMSIZ];
12592 
12593 		/* Ignore unmoveable devices (i.e. loopback) */
12594 		if (dev->netns_immutable)
12595 			continue;
12596 
12597 		/* Leave virtual devices for the generic cleanup */
12598 		if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
12599 			continue;
12600 
12601 		/* Push remaining network devices to init_net */
12602 		snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
12603 		if (netdev_name_in_use(&init_net, fb_name))
12604 			snprintf(fb_name, IFNAMSIZ, "dev%%d");
12605 
12606 		netdev_for_each_altname_safe(dev, name_node, tmp)
12607 			if (netdev_name_in_use(&init_net, name_node->name))
12608 				__netdev_name_node_alt_destroy(name_node);
12609 
12610 		err = dev_change_net_namespace(dev, &init_net, fb_name);
12611 		if (err) {
12612 			pr_emerg("%s: failed to move %s to init_net: %d\n",
12613 				 __func__, dev->name, err);
12614 			BUG();
12615 		}
12616 	}
12617 }
12618 
default_device_exit_batch(struct list_head * net_list)12619 static void __net_exit default_device_exit_batch(struct list_head *net_list)
12620 {
12621 	/* At exit all network devices most be removed from a network
12622 	 * namespace.  Do this in the reverse order of registration.
12623 	 * Do this across as many network namespaces as possible to
12624 	 * improve batching efficiency.
12625 	 */
12626 	struct net_device *dev;
12627 	struct net *net;
12628 	LIST_HEAD(dev_kill_list);
12629 
12630 	rtnl_lock();
12631 	list_for_each_entry(net, net_list, exit_list) {
12632 		default_device_exit_net(net);
12633 		cond_resched();
12634 	}
12635 
12636 	list_for_each_entry(net, net_list, exit_list) {
12637 		for_each_netdev_reverse(net, dev) {
12638 			if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
12639 				dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
12640 			else
12641 				unregister_netdevice_queue(dev, &dev_kill_list);
12642 		}
12643 	}
12644 	unregister_netdevice_many(&dev_kill_list);
12645 	rtnl_unlock();
12646 }
12647 
12648 static struct pernet_operations __net_initdata default_device_ops = {
12649 	.exit_batch = default_device_exit_batch,
12650 };
12651 
net_dev_struct_check(void)12652 static void __init net_dev_struct_check(void)
12653 {
12654 	/* TX read-mostly hotpath */
12655 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, priv_flags_fast);
12656 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, netdev_ops);
12657 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, header_ops);
12658 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, _tx);
12659 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, real_num_tx_queues);
12660 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_size);
12661 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_ipv4_max_size);
12662 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_segs);
12663 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_partial_features);
12664 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, num_tc);
12665 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, mtu);
12666 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, needed_headroom);
12667 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tc_to_txq);
12668 #ifdef CONFIG_XPS
12669 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, xps_maps);
12670 #endif
12671 #ifdef CONFIG_NETFILTER_EGRESS
12672 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, nf_hooks_egress);
12673 #endif
12674 #ifdef CONFIG_NET_XGRESS
12675 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tcx_egress);
12676 #endif
12677 	CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_tx, 160);
12678 
12679 	/* TXRX read-mostly hotpath */
12680 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, lstats);
12681 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, state);
12682 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, flags);
12683 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, hard_header_len);
12684 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, features);
12685 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, ip6_ptr);
12686 	CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_txrx, 46);
12687 
12688 	/* RX read-mostly hotpath */
12689 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ptype_specific);
12690 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ifindex);
12691 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, real_num_rx_queues);
12692 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, _rx);
12693 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_max_size);
12694 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_ipv4_max_size);
12695 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler);
12696 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler_data);
12697 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, nd_net);
12698 #ifdef CONFIG_NETPOLL
12699 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, npinfo);
12700 #endif
12701 #ifdef CONFIG_NET_XGRESS
12702 	CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, tcx_ingress);
12703 #endif
12704 	CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_rx, 92);
12705 }
12706 
12707 /*
12708  *	Initialize the DEV module. At boot time this walks the device list and
12709  *	unhooks any devices that fail to initialise (normally hardware not
12710  *	present) and leaves us with a valid list of present and active devices.
12711  *
12712  */
12713 
12714 /* We allocate 256 pages for each CPU if PAGE_SHIFT is 12 */
12715 #define SYSTEM_PERCPU_PAGE_POOL_SIZE	((1 << 20) / PAGE_SIZE)
12716 
net_page_pool_create(int cpuid)12717 static int net_page_pool_create(int cpuid)
12718 {
12719 #if IS_ENABLED(CONFIG_PAGE_POOL)
12720 	struct page_pool_params page_pool_params = {
12721 		.pool_size = SYSTEM_PERCPU_PAGE_POOL_SIZE,
12722 		.flags = PP_FLAG_SYSTEM_POOL,
12723 		.nid = cpu_to_mem(cpuid),
12724 	};
12725 	struct page_pool *pp_ptr;
12726 	int err;
12727 
12728 	pp_ptr = page_pool_create_percpu(&page_pool_params, cpuid);
12729 	if (IS_ERR(pp_ptr))
12730 		return -ENOMEM;
12731 
12732 	err = xdp_reg_page_pool(pp_ptr);
12733 	if (err) {
12734 		page_pool_destroy(pp_ptr);
12735 		return err;
12736 	}
12737 
12738 	per_cpu(system_page_pool.pool, cpuid) = pp_ptr;
12739 #endif
12740 	return 0;
12741 }
12742 
backlog_napi_should_run(unsigned int cpu)12743 static int backlog_napi_should_run(unsigned int cpu)
12744 {
12745 	struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
12746 	struct napi_struct *napi = &sd->backlog;
12747 
12748 	return test_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
12749 }
12750 
run_backlog_napi(unsigned int cpu)12751 static void run_backlog_napi(unsigned int cpu)
12752 {
12753 	struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
12754 
12755 	napi_threaded_poll_loop(&sd->backlog);
12756 }
12757 
backlog_napi_setup(unsigned int cpu)12758 static void backlog_napi_setup(unsigned int cpu)
12759 {
12760 	struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
12761 	struct napi_struct *napi = &sd->backlog;
12762 
12763 	napi->thread = this_cpu_read(backlog_napi);
12764 	set_bit(NAPI_STATE_THREADED, &napi->state);
12765 }
12766 
12767 static struct smp_hotplug_thread backlog_threads = {
12768 	.store			= &backlog_napi,
12769 	.thread_should_run	= backlog_napi_should_run,
12770 	.thread_fn		= run_backlog_napi,
12771 	.thread_comm		= "backlog_napi/%u",
12772 	.setup			= backlog_napi_setup,
12773 };
12774 
12775 /*
12776  *       This is called single threaded during boot, so no need
12777  *       to take the rtnl semaphore.
12778  */
net_dev_init(void)12779 static int __init net_dev_init(void)
12780 {
12781 	int i, rc = -ENOMEM;
12782 
12783 	BUG_ON(!dev_boot_phase);
12784 
12785 	net_dev_struct_check();
12786 
12787 	if (dev_proc_init())
12788 		goto out;
12789 
12790 	if (netdev_kobject_init())
12791 		goto out;
12792 
12793 	for (i = 0; i < PTYPE_HASH_SIZE; i++)
12794 		INIT_LIST_HEAD(&ptype_base[i]);
12795 
12796 	if (register_pernet_subsys(&netdev_net_ops))
12797 		goto out;
12798 
12799 	/*
12800 	 *	Initialise the packet receive queues.
12801 	 */
12802 
12803 	flush_backlogs_fallback = flush_backlogs_alloc();
12804 	if (!flush_backlogs_fallback)
12805 		goto out;
12806 
12807 	for_each_possible_cpu(i) {
12808 		struct softnet_data *sd = &per_cpu(softnet_data, i);
12809 
12810 		skb_queue_head_init(&sd->input_pkt_queue);
12811 		skb_queue_head_init(&sd->process_queue);
12812 #ifdef CONFIG_XFRM_OFFLOAD
12813 		skb_queue_head_init(&sd->xfrm_backlog);
12814 #endif
12815 		INIT_LIST_HEAD(&sd->poll_list);
12816 		sd->output_queue_tailp = &sd->output_queue;
12817 #ifdef CONFIG_RPS
12818 		INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
12819 		sd->cpu = i;
12820 #endif
12821 		INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd);
12822 		spin_lock_init(&sd->defer_lock);
12823 
12824 		gro_init(&sd->backlog.gro);
12825 		sd->backlog.poll = process_backlog;
12826 		sd->backlog.weight = weight_p;
12827 		INIT_LIST_HEAD(&sd->backlog.poll_list);
12828 
12829 		if (net_page_pool_create(i))
12830 			goto out;
12831 	}
12832 	if (use_backlog_threads())
12833 		smpboot_register_percpu_thread(&backlog_threads);
12834 
12835 	dev_boot_phase = 0;
12836 
12837 	/* The loopback device is special if any other network devices
12838 	 * is present in a network namespace the loopback device must
12839 	 * be present. Since we now dynamically allocate and free the
12840 	 * loopback device ensure this invariant is maintained by
12841 	 * keeping the loopback device as the first device on the
12842 	 * list of network devices.  Ensuring the loopback devices
12843 	 * is the first device that appears and the last network device
12844 	 * that disappears.
12845 	 */
12846 	if (register_pernet_device(&loopback_net_ops))
12847 		goto out;
12848 
12849 	if (register_pernet_device(&default_device_ops))
12850 		goto out;
12851 
12852 	open_softirq(NET_TX_SOFTIRQ, net_tx_action);
12853 	open_softirq(NET_RX_SOFTIRQ, net_rx_action);
12854 
12855 	rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
12856 				       NULL, dev_cpu_dead);
12857 	WARN_ON(rc < 0);
12858 	rc = 0;
12859 
12860 	/* avoid static key IPIs to isolated CPUs */
12861 	if (housekeeping_enabled(HK_TYPE_MISC))
12862 		net_enable_timestamp();
12863 out:
12864 	if (rc < 0) {
12865 		for_each_possible_cpu(i) {
12866 			struct page_pool *pp_ptr;
12867 
12868 			pp_ptr = per_cpu(system_page_pool.pool, i);
12869 			if (!pp_ptr)
12870 				continue;
12871 
12872 			xdp_unreg_page_pool(pp_ptr);
12873 			page_pool_destroy(pp_ptr);
12874 			per_cpu(system_page_pool.pool, i) = NULL;
12875 		}
12876 	}
12877 
12878 	return rc;
12879 }
12880 
12881 subsys_initcall(net_dev_init);
12882