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