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