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 if (dev->num_tc) {
2632 /* Do not allow XPS on subordinate device directly */
2633 num_tc = dev->num_tc;
2634 if (num_tc < 0)
2635 return -EINVAL;
2636
2637 /* If queue belongs to subordinate dev use its map */
2638 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2639
2640 tc = netdev_txq_to_tc(dev, index);
2641 if (tc < 0)
2642 return -EINVAL;
2643 }
2644
2645 mutex_lock(&xps_map_mutex);
2646 if (is_rxqs_map) {
2647 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2648 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2649 nr_ids = dev->num_rx_queues;
2650 } else {
2651 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2652 if (num_possible_cpus() > 1) {
2653 online_mask = cpumask_bits(cpu_online_mask);
2654 possible_mask = cpumask_bits(cpu_possible_mask);
2655 }
2656 dev_maps = xmap_dereference(dev->xps_cpus_map);
2657 nr_ids = nr_cpu_ids;
2658 }
2659
2660 if (maps_sz < L1_CACHE_BYTES)
2661 maps_sz = L1_CACHE_BYTES;
2662
2663 /* allocate memory for queue storage */
2664 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2665 j < nr_ids;) {
2666 if (!new_dev_maps)
2667 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2668 if (!new_dev_maps) {
2669 mutex_unlock(&xps_map_mutex);
2670 return -ENOMEM;
2671 }
2672
2673 tci = j * num_tc + tc;
2674 map = dev_maps ? xmap_dereference(dev_maps->attr_map[tci]) :
2675 NULL;
2676
2677 map = expand_xps_map(map, j, index, is_rxqs_map);
2678 if (!map)
2679 goto error;
2680
2681 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2682 }
2683
2684 if (!new_dev_maps)
2685 goto out_no_new_maps;
2686
2687 if (!dev_maps) {
2688 /* Increment static keys at most once per type */
2689 static_key_slow_inc_cpuslocked(&xps_needed);
2690 if (is_rxqs_map)
2691 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2692 }
2693
2694 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2695 j < nr_ids;) {
2696 /* copy maps belonging to foreign traffic classes */
2697 for (i = tc, tci = j * num_tc; dev_maps && i--; tci++) {
2698 /* fill in the new device map from the old device map */
2699 map = xmap_dereference(dev_maps->attr_map[tci]);
2700 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2701 }
2702
2703 /* We need to explicitly update tci as prevous loop
2704 * could break out early if dev_maps is NULL.
2705 */
2706 tci = j * num_tc + tc;
2707
2708 if (netif_attr_test_mask(j, mask, nr_ids) &&
2709 netif_attr_test_online(j, online_mask, nr_ids)) {
2710 /* add tx-queue to CPU/rx-queue maps */
2711 int pos = 0;
2712
2713 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2714 while ((pos < map->len) && (map->queues[pos] != index))
2715 pos++;
2716
2717 if (pos == map->len)
2718 map->queues[map->len++] = index;
2719 #ifdef CONFIG_NUMA
2720 if (!is_rxqs_map) {
2721 if (numa_node_id == -2)
2722 numa_node_id = cpu_to_node(j);
2723 else if (numa_node_id != cpu_to_node(j))
2724 numa_node_id = -1;
2725 }
2726 #endif
2727 } else if (dev_maps) {
2728 /* fill in the new device map from the old device map */
2729 map = xmap_dereference(dev_maps->attr_map[tci]);
2730 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2731 }
2732
2733 /* copy maps belonging to foreign traffic classes */
2734 for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
2735 /* fill in the new device map from the old device map */
2736 map = xmap_dereference(dev_maps->attr_map[tci]);
2737 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2738 }
2739 }
2740
2741 if (is_rxqs_map)
2742 rcu_assign_pointer(dev->xps_rxqs_map, new_dev_maps);
2743 else
2744 rcu_assign_pointer(dev->xps_cpus_map, new_dev_maps);
2745
2746 /* Cleanup old maps */
2747 if (!dev_maps)
2748 goto out_no_old_maps;
2749
2750 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2751 j < nr_ids;) {
2752 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2753 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2754 map = xmap_dereference(dev_maps->attr_map[tci]);
2755 if (map && map != new_map)
2756 kfree_rcu(map, rcu);
2757 }
2758 }
2759
2760 kfree_rcu(dev_maps, rcu);
2761
2762 out_no_old_maps:
2763 dev_maps = new_dev_maps;
2764 active = true;
2765
2766 out_no_new_maps:
2767 if (!is_rxqs_map) {
2768 /* update Tx queue numa node */
2769 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2770 (numa_node_id >= 0) ?
2771 numa_node_id : NUMA_NO_NODE);
2772 }
2773
2774 if (!dev_maps)
2775 goto out_no_maps;
2776
2777 /* removes tx-queue from unused CPUs/rx-queues */
2778 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2779 j < nr_ids;) {
2780 for (i = tc, tci = j * num_tc; i--; tci++)
2781 active |= remove_xps_queue(dev_maps, tci, index);
2782 if (!netif_attr_test_mask(j, mask, nr_ids) ||
2783 !netif_attr_test_online(j, online_mask, nr_ids))
2784 active |= remove_xps_queue(dev_maps, tci, index);
2785 for (i = num_tc - tc, tci++; --i; tci++)
2786 active |= remove_xps_queue(dev_maps, tci, index);
2787 }
2788
2789 /* free map if not active */
2790 if (!active)
2791 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2792
2793 out_no_maps:
2794 mutex_unlock(&xps_map_mutex);
2795
2796 return 0;
2797 error:
2798 /* remove any maps that we added */
2799 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2800 j < nr_ids;) {
2801 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2802 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2803 map = dev_maps ?
2804 xmap_dereference(dev_maps->attr_map[tci]) :
2805 NULL;
2806 if (new_map && new_map != map)
2807 kfree(new_map);
2808 }
2809 }
2810
2811 mutex_unlock(&xps_map_mutex);
2812
2813 kfree(new_dev_maps);
2814 return -ENOMEM;
2815 }
2816 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2817
netif_set_xps_queue(struct net_device * dev,const struct cpumask * mask,u16 index)2818 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2819 u16 index)
2820 {
2821 int ret;
2822
2823 cpus_read_lock();
2824 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, false);
2825 cpus_read_unlock();
2826
2827 return ret;
2828 }
2829 EXPORT_SYMBOL(netif_set_xps_queue);
2830
2831 #endif
netdev_unbind_all_sb_channels(struct net_device * dev)2832 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2833 {
2834 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2835
2836 /* Unbind any subordinate channels */
2837 while (txq-- != &dev->_tx[0]) {
2838 if (txq->sb_dev)
2839 netdev_unbind_sb_channel(dev, txq->sb_dev);
2840 }
2841 }
2842
netdev_reset_tc(struct net_device * dev)2843 void netdev_reset_tc(struct net_device *dev)
2844 {
2845 #ifdef CONFIG_XPS
2846 netif_reset_xps_queues_gt(dev, 0);
2847 #endif
2848 netdev_unbind_all_sb_channels(dev);
2849
2850 /* Reset TC configuration of device */
2851 dev->num_tc = 0;
2852 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2853 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2854 }
2855 EXPORT_SYMBOL(netdev_reset_tc);
2856
netdev_set_tc_queue(struct net_device * dev,u8 tc,u16 count,u16 offset)2857 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2858 {
2859 if (tc >= dev->num_tc)
2860 return -EINVAL;
2861
2862 #ifdef CONFIG_XPS
2863 netif_reset_xps_queues(dev, offset, count);
2864 #endif
2865 dev->tc_to_txq[tc].count = count;
2866 dev->tc_to_txq[tc].offset = offset;
2867 return 0;
2868 }
2869 EXPORT_SYMBOL(netdev_set_tc_queue);
2870
netdev_set_num_tc(struct net_device * dev,u8 num_tc)2871 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2872 {
2873 if (num_tc > TC_MAX_QUEUE)
2874 return -EINVAL;
2875
2876 #ifdef CONFIG_XPS
2877 netif_reset_xps_queues_gt(dev, 0);
2878 #endif
2879 netdev_unbind_all_sb_channels(dev);
2880
2881 dev->num_tc = num_tc;
2882 return 0;
2883 }
2884 EXPORT_SYMBOL(netdev_set_num_tc);
2885
netdev_unbind_sb_channel(struct net_device * dev,struct net_device * sb_dev)2886 void netdev_unbind_sb_channel(struct net_device *dev,
2887 struct net_device *sb_dev)
2888 {
2889 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2890
2891 #ifdef CONFIG_XPS
2892 netif_reset_xps_queues_gt(sb_dev, 0);
2893 #endif
2894 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2895 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2896
2897 while (txq-- != &dev->_tx[0]) {
2898 if (txq->sb_dev == sb_dev)
2899 txq->sb_dev = NULL;
2900 }
2901 }
2902 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2903
netdev_bind_sb_channel_queue(struct net_device * dev,struct net_device * sb_dev,u8 tc,u16 count,u16 offset)2904 int netdev_bind_sb_channel_queue(struct net_device *dev,
2905 struct net_device *sb_dev,
2906 u8 tc, u16 count, u16 offset)
2907 {
2908 /* Make certain the sb_dev and dev are already configured */
2909 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2910 return -EINVAL;
2911
2912 /* We cannot hand out queues we don't have */
2913 if ((offset + count) > dev->real_num_tx_queues)
2914 return -EINVAL;
2915
2916 /* Record the mapping */
2917 sb_dev->tc_to_txq[tc].count = count;
2918 sb_dev->tc_to_txq[tc].offset = offset;
2919
2920 /* Provide a way for Tx queue to find the tc_to_txq map or
2921 * XPS map for itself.
2922 */
2923 while (count--)
2924 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2925
2926 return 0;
2927 }
2928 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2929
netdev_set_sb_channel(struct net_device * dev,u16 channel)2930 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2931 {
2932 /* Do not use a multiqueue device to represent a subordinate channel */
2933 if (netif_is_multiqueue(dev))
2934 return -ENODEV;
2935
2936 /* We allow channels 1 - 32767 to be used for subordinate channels.
2937 * Channel 0 is meant to be "native" mode and used only to represent
2938 * the main root device. We allow writing 0 to reset the device back
2939 * to normal mode after being used as a subordinate channel.
2940 */
2941 if (channel > S16_MAX)
2942 return -EINVAL;
2943
2944 dev->num_tc = -channel;
2945
2946 return 0;
2947 }
2948 EXPORT_SYMBOL(netdev_set_sb_channel);
2949
2950 /*
2951 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2952 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2953 */
netif_set_real_num_tx_queues(struct net_device * dev,unsigned int txq)2954 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2955 {
2956 bool disabling;
2957 int rc;
2958
2959 disabling = txq < dev->real_num_tx_queues;
2960
2961 if (txq < 1 || txq > dev->num_tx_queues)
2962 return -EINVAL;
2963
2964 if (dev->reg_state == NETREG_REGISTERED ||
2965 dev->reg_state == NETREG_UNREGISTERING) {
2966 ASSERT_RTNL();
2967
2968 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2969 txq);
2970 if (rc)
2971 return rc;
2972
2973 if (dev->num_tc)
2974 netif_setup_tc(dev, txq);
2975
2976 dev_qdisc_change_real_num_tx(dev, txq);
2977
2978 dev->real_num_tx_queues = txq;
2979
2980 if (disabling) {
2981 synchronize_net();
2982 qdisc_reset_all_tx_gt(dev, txq);
2983 #ifdef CONFIG_XPS
2984 netif_reset_xps_queues_gt(dev, txq);
2985 #endif
2986 }
2987 } else {
2988 dev->real_num_tx_queues = txq;
2989 }
2990
2991 return 0;
2992 }
2993 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2994
2995 #ifdef CONFIG_SYSFS
2996 /**
2997 * netif_set_real_num_rx_queues - set actual number of RX queues used
2998 * @dev: Network device
2999 * @rxq: Actual number of RX queues
3000 *
3001 * This must be called either with the rtnl_lock held or before
3002 * registration of the net device. Returns 0 on success, or a
3003 * negative error code. If called before registration, it always
3004 * succeeds.
3005 */
netif_set_real_num_rx_queues(struct net_device * dev,unsigned int rxq)3006 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
3007 {
3008 int rc;
3009
3010 if (rxq < 1 || rxq > dev->num_rx_queues)
3011 return -EINVAL;
3012
3013 if (dev->reg_state == NETREG_REGISTERED) {
3014 ASSERT_RTNL();
3015
3016 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
3017 rxq);
3018 if (rc)
3019 return rc;
3020 }
3021
3022 dev->real_num_rx_queues = rxq;
3023 return 0;
3024 }
3025 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
3026 #endif
3027
3028 /**
3029 * netif_get_num_default_rss_queues - default number of RSS queues
3030 *
3031 * This routine should set an upper limit on the number of RSS queues
3032 * used by default by multiqueue devices.
3033 */
netif_get_num_default_rss_queues(void)3034 int netif_get_num_default_rss_queues(void)
3035 {
3036 return is_kdump_kernel() ?
3037 1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
3038 }
3039 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3040
__netif_reschedule(struct Qdisc * q)3041 static void __netif_reschedule(struct Qdisc *q)
3042 {
3043 struct softnet_data *sd;
3044 unsigned long flags;
3045
3046 local_irq_save(flags);
3047 sd = this_cpu_ptr(&softnet_data);
3048 q->next_sched = NULL;
3049 *sd->output_queue_tailp = q;
3050 sd->output_queue_tailp = &q->next_sched;
3051 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3052 local_irq_restore(flags);
3053 }
3054
__netif_schedule(struct Qdisc * q)3055 void __netif_schedule(struct Qdisc *q)
3056 {
3057 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3058 __netif_reschedule(q);
3059 }
3060 EXPORT_SYMBOL(__netif_schedule);
3061
3062 struct dev_kfree_skb_cb {
3063 enum skb_free_reason reason;
3064 };
3065
get_kfree_skb_cb(const struct sk_buff * skb)3066 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3067 {
3068 return (struct dev_kfree_skb_cb *)skb->cb;
3069 }
3070
netif_schedule_queue(struct netdev_queue * txq)3071 void netif_schedule_queue(struct netdev_queue *txq)
3072 {
3073 rcu_read_lock();
3074 if (!netif_xmit_stopped(txq)) {
3075 struct Qdisc *q = rcu_dereference(txq->qdisc);
3076
3077 __netif_schedule(q);
3078 }
3079 rcu_read_unlock();
3080 }
3081 EXPORT_SYMBOL(netif_schedule_queue);
3082
netif_tx_wake_queue(struct netdev_queue * dev_queue)3083 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3084 {
3085 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3086 struct Qdisc *q;
3087
3088 rcu_read_lock();
3089 q = rcu_dereference(dev_queue->qdisc);
3090 __netif_schedule(q);
3091 rcu_read_unlock();
3092 }
3093 }
3094 EXPORT_SYMBOL(netif_tx_wake_queue);
3095
__dev_kfree_skb_irq(struct sk_buff * skb,enum skb_free_reason reason)3096 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
3097 {
3098 unsigned long flags;
3099
3100 if (unlikely(!skb))
3101 return;
3102
3103 if (likely(refcount_read(&skb->users) == 1)) {
3104 smp_rmb();
3105 refcount_set(&skb->users, 0);
3106 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3107 return;
3108 }
3109 get_kfree_skb_cb(skb)->reason = reason;
3110 local_irq_save(flags);
3111 skb->next = __this_cpu_read(softnet_data.completion_queue);
3112 __this_cpu_write(softnet_data.completion_queue, skb);
3113 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3114 local_irq_restore(flags);
3115 }
3116 EXPORT_SYMBOL(__dev_kfree_skb_irq);
3117
__dev_kfree_skb_any(struct sk_buff * skb,enum skb_free_reason reason)3118 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
3119 {
3120 if (in_irq() || irqs_disabled())
3121 __dev_kfree_skb_irq(skb, reason);
3122 else
3123 dev_kfree_skb(skb);
3124 }
3125 EXPORT_SYMBOL(__dev_kfree_skb_any);
3126
3127
3128 /**
3129 * netif_device_detach - mark device as removed
3130 * @dev: network device
3131 *
3132 * Mark device as removed from system and therefore no longer available.
3133 */
netif_device_detach(struct net_device * dev)3134 void netif_device_detach(struct net_device *dev)
3135 {
3136 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3137 netif_running(dev)) {
3138 netif_tx_stop_all_queues(dev);
3139 }
3140 }
3141 EXPORT_SYMBOL(netif_device_detach);
3142
3143 /**
3144 * netif_device_attach - mark device as attached
3145 * @dev: network device
3146 *
3147 * Mark device as attached from system and restart if needed.
3148 */
netif_device_attach(struct net_device * dev)3149 void netif_device_attach(struct net_device *dev)
3150 {
3151 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3152 netif_running(dev)) {
3153 netif_tx_wake_all_queues(dev);
3154 __netdev_watchdog_up(dev);
3155 }
3156 }
3157 EXPORT_SYMBOL(netif_device_attach);
3158
3159 /*
3160 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3161 * to be used as a distribution range.
3162 */
skb_tx_hash(const struct net_device * dev,const struct net_device * sb_dev,struct sk_buff * skb)3163 static u16 skb_tx_hash(const struct net_device *dev,
3164 const struct net_device *sb_dev,
3165 struct sk_buff *skb)
3166 {
3167 u32 hash;
3168 u16 qoffset = 0;
3169 u16 qcount = dev->real_num_tx_queues;
3170
3171 if (dev->num_tc) {
3172 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3173
3174 qoffset = sb_dev->tc_to_txq[tc].offset;
3175 qcount = sb_dev->tc_to_txq[tc].count;
3176 if (unlikely(!qcount)) {
3177 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3178 sb_dev->name, qoffset, tc);
3179 qoffset = 0;
3180 qcount = dev->real_num_tx_queues;
3181 }
3182 }
3183
3184 if (skb_rx_queue_recorded(skb)) {
3185 hash = skb_get_rx_queue(skb);
3186 if (hash >= qoffset)
3187 hash -= qoffset;
3188 while (unlikely(hash >= qcount))
3189 hash -= qcount;
3190 return hash + qoffset;
3191 }
3192
3193 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3194 }
3195
skb_warn_bad_offload(const struct sk_buff * skb)3196 static void skb_warn_bad_offload(const struct sk_buff *skb)
3197 {
3198 static const netdev_features_t null_features;
3199 struct net_device *dev = skb->dev;
3200 const char *name = "";
3201
3202 if (!net_ratelimit())
3203 return;
3204
3205 if (dev) {
3206 if (dev->dev.parent)
3207 name = dev_driver_string(dev->dev.parent);
3208 else
3209 name = netdev_name(dev);
3210 }
3211 skb_dump(KERN_WARNING, skb, false);
3212 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3213 name, dev ? &dev->features : &null_features,
3214 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3215 }
3216
3217 /*
3218 * Invalidate hardware checksum when packet is to be mangled, and
3219 * complete checksum manually on outgoing path.
3220 */
skb_checksum_help(struct sk_buff * skb)3221 int skb_checksum_help(struct sk_buff *skb)
3222 {
3223 __wsum csum;
3224 int ret = 0, offset;
3225
3226 if (skb->ip_summed == CHECKSUM_COMPLETE)
3227 goto out_set_summed;
3228
3229 if (unlikely(skb_shinfo(skb)->gso_size)) {
3230 skb_warn_bad_offload(skb);
3231 return -EINVAL;
3232 }
3233
3234 /* Before computing a checksum, we should make sure no frag could
3235 * be modified by an external entity : checksum could be wrong.
3236 */
3237 if (skb_has_shared_frag(skb)) {
3238 ret = __skb_linearize(skb);
3239 if (ret)
3240 goto out;
3241 }
3242
3243 offset = skb_checksum_start_offset(skb);
3244 BUG_ON(offset >= skb_headlen(skb));
3245 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3246
3247 offset += skb->csum_offset;
3248 BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
3249
3250 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3251 if (ret)
3252 goto out;
3253
3254 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3255 out_set_summed:
3256 skb->ip_summed = CHECKSUM_NONE;
3257 out:
3258 return ret;
3259 }
3260 EXPORT_SYMBOL(skb_checksum_help);
3261
skb_crc32c_csum_help(struct sk_buff * skb)3262 int skb_crc32c_csum_help(struct sk_buff *skb)
3263 {
3264 __le32 crc32c_csum;
3265 int ret = 0, offset, start;
3266
3267 if (skb->ip_summed != CHECKSUM_PARTIAL)
3268 goto out;
3269
3270 if (unlikely(skb_is_gso(skb)))
3271 goto out;
3272
3273 /* Before computing a checksum, we should make sure no frag could
3274 * be modified by an external entity : checksum could be wrong.
3275 */
3276 if (unlikely(skb_has_shared_frag(skb))) {
3277 ret = __skb_linearize(skb);
3278 if (ret)
3279 goto out;
3280 }
3281 start = skb_checksum_start_offset(skb);
3282 offset = start + offsetof(struct sctphdr, checksum);
3283 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3284 ret = -EINVAL;
3285 goto out;
3286 }
3287
3288 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3289 if (ret)
3290 goto out;
3291
3292 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3293 skb->len - start, ~(__u32)0,
3294 crc32c_csum_stub));
3295 *(__le32 *)(skb->data + offset) = crc32c_csum;
3296 skb->ip_summed = CHECKSUM_NONE;
3297 skb->csum_not_inet = 0;
3298 out:
3299 return ret;
3300 }
3301
skb_network_protocol(struct sk_buff * skb,int * depth)3302 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3303 {
3304 __be16 type = skb->protocol;
3305
3306 /* Tunnel gso handlers can set protocol to ethernet. */
3307 if (type == htons(ETH_P_TEB)) {
3308 struct ethhdr *eth;
3309
3310 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3311 return 0;
3312
3313 eth = (struct ethhdr *)skb->data;
3314 type = eth->h_proto;
3315 }
3316
3317 return __vlan_get_protocol(skb, type, depth);
3318 }
3319
3320 /**
3321 * skb_mac_gso_segment - mac layer segmentation handler.
3322 * @skb: buffer to segment
3323 * @features: features for the output path (see dev->features)
3324 */
skb_mac_gso_segment(struct sk_buff * skb,netdev_features_t features)3325 struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
3326 netdev_features_t features)
3327 {
3328 struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
3329 struct packet_offload *ptype;
3330 int vlan_depth = skb->mac_len;
3331 __be16 type = skb_network_protocol(skb, &vlan_depth);
3332
3333 if (unlikely(!type))
3334 return ERR_PTR(-EINVAL);
3335
3336 __skb_pull(skb, vlan_depth);
3337
3338 rcu_read_lock();
3339 list_for_each_entry_rcu(ptype, &offload_base, list) {
3340 if (ptype->type == type && ptype->callbacks.gso_segment) {
3341 segs = ptype->callbacks.gso_segment(skb, features);
3342 break;
3343 }
3344 }
3345 rcu_read_unlock();
3346
3347 __skb_push(skb, skb->data - skb_mac_header(skb));
3348
3349 return segs;
3350 }
3351 EXPORT_SYMBOL(skb_mac_gso_segment);
3352
3353
3354 /* openvswitch calls this on rx path, so we need a different check.
3355 */
skb_needs_check(struct sk_buff * skb,bool tx_path)3356 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
3357 {
3358 if (tx_path)
3359 return skb->ip_summed != CHECKSUM_PARTIAL &&
3360 skb->ip_summed != CHECKSUM_UNNECESSARY;
3361
3362 return skb->ip_summed == CHECKSUM_NONE;
3363 }
3364
3365 /**
3366 * __skb_gso_segment - Perform segmentation on skb.
3367 * @skb: buffer to segment
3368 * @features: features for the output path (see dev->features)
3369 * @tx_path: whether it is called in TX path
3370 *
3371 * This function segments the given skb and returns a list of segments.
3372 *
3373 * It may return NULL if the skb requires no segmentation. This is
3374 * only possible when GSO is used for verifying header integrity.
3375 *
3376 * Segmentation preserves SKB_GSO_CB_OFFSET bytes of previous skb cb.
3377 */
__skb_gso_segment(struct sk_buff * skb,netdev_features_t features,bool tx_path)3378 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
3379 netdev_features_t features, bool tx_path)
3380 {
3381 struct sk_buff *segs;
3382
3383 if (unlikely(skb_needs_check(skb, tx_path))) {
3384 int err;
3385
3386 /* We're going to init ->check field in TCP or UDP header */
3387 err = skb_cow_head(skb, 0);
3388 if (err < 0)
3389 return ERR_PTR(err);
3390 }
3391
3392 /* Only report GSO partial support if it will enable us to
3393 * support segmentation on this frame without needing additional
3394 * work.
3395 */
3396 if (features & NETIF_F_GSO_PARTIAL) {
3397 netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
3398 struct net_device *dev = skb->dev;
3399
3400 partial_features |= dev->features & dev->gso_partial_features;
3401 if (!skb_gso_ok(skb, features | partial_features))
3402 features &= ~NETIF_F_GSO_PARTIAL;
3403 }
3404
3405 BUILD_BUG_ON(SKB_GSO_CB_OFFSET +
3406 sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
3407
3408 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
3409 SKB_GSO_CB(skb)->encap_level = 0;
3410
3411 skb_reset_mac_header(skb);
3412 skb_reset_mac_len(skb);
3413
3414 segs = skb_mac_gso_segment(skb, features);
3415
3416 if (segs != skb && unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
3417 skb_warn_bad_offload(skb);
3418
3419 return segs;
3420 }
3421 EXPORT_SYMBOL(__skb_gso_segment);
3422
3423 /* Take action when hardware reception checksum errors are detected. */
3424 #ifdef CONFIG_BUG
netdev_rx_csum_fault(struct net_device * dev,struct sk_buff * skb)3425 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3426 {
3427 if (net_ratelimit()) {
3428 pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
3429 skb_dump(KERN_ERR, skb, true);
3430 dump_stack();
3431 }
3432 }
3433 EXPORT_SYMBOL(netdev_rx_csum_fault);
3434 #endif
3435
3436 /* XXX: check that highmem exists at all on the given machine. */
illegal_highdma(struct net_device * dev,struct sk_buff * skb)3437 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3438 {
3439 #ifdef CONFIG_HIGHMEM
3440 int i;
3441
3442 if (!(dev->features & NETIF_F_HIGHDMA)) {
3443 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3444 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3445
3446 if (PageHighMem(skb_frag_page(frag)))
3447 return 1;
3448 }
3449 }
3450 #endif
3451 return 0;
3452 }
3453
3454 /* If MPLS offload request, verify we are testing hardware MPLS features
3455 * instead of standard features for the netdev.
3456 */
3457 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
net_mpls_features(struct sk_buff * skb,netdev_features_t features,__be16 type)3458 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3459 netdev_features_t features,
3460 __be16 type)
3461 {
3462 if (eth_p_mpls(type))
3463 features &= skb->dev->mpls_features;
3464
3465 return features;
3466 }
3467 #else
net_mpls_features(struct sk_buff * skb,netdev_features_t features,__be16 type)3468 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3469 netdev_features_t features,
3470 __be16 type)
3471 {
3472 return features;
3473 }
3474 #endif
3475
harmonize_features(struct sk_buff * skb,netdev_features_t features)3476 static netdev_features_t harmonize_features(struct sk_buff *skb,
3477 netdev_features_t features)
3478 {
3479 __be16 type;
3480
3481 type = skb_network_protocol(skb, NULL);
3482 features = net_mpls_features(skb, features, type);
3483
3484 if (skb->ip_summed != CHECKSUM_NONE &&
3485 !can_checksum_protocol(features, type)) {
3486 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3487 }
3488 if (illegal_highdma(skb->dev, skb))
3489 features &= ~NETIF_F_SG;
3490
3491 return features;
3492 }
3493
passthru_features_check(struct sk_buff * skb,struct net_device * dev,netdev_features_t features)3494 netdev_features_t passthru_features_check(struct sk_buff *skb,
3495 struct net_device *dev,
3496 netdev_features_t features)
3497 {
3498 return features;
3499 }
3500 EXPORT_SYMBOL(passthru_features_check);
3501
dflt_features_check(struct sk_buff * skb,struct net_device * dev,netdev_features_t features)3502 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3503 struct net_device *dev,
3504 netdev_features_t features)
3505 {
3506 return vlan_features_check(skb, features);
3507 }
3508
gso_features_check(const struct sk_buff * skb,struct net_device * dev,netdev_features_t features)3509 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3510 struct net_device *dev,
3511 netdev_features_t features)
3512 {
3513 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3514
3515 if (gso_segs > dev->gso_max_segs)
3516 return features & ~NETIF_F_GSO_MASK;
3517
3518 /* Support for GSO partial features requires software
3519 * intervention before we can actually process the packets
3520 * so we need to strip support for any partial features now
3521 * and we can pull them back in after we have partially
3522 * segmented the frame.
3523 */
3524 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3525 features &= ~dev->gso_partial_features;
3526
3527 /* Make sure to clear the IPv4 ID mangling feature if the
3528 * IPv4 header has the potential to be fragmented.
3529 */
3530 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3531 struct iphdr *iph = skb->encapsulation ?
3532 inner_ip_hdr(skb) : ip_hdr(skb);
3533
3534 if (!(iph->frag_off & htons(IP_DF)))
3535 features &= ~NETIF_F_TSO_MANGLEID;
3536 }
3537
3538 return features;
3539 }
3540
netif_skb_features(struct sk_buff * skb)3541 netdev_features_t netif_skb_features(struct sk_buff *skb)
3542 {
3543 struct net_device *dev = skb->dev;
3544 netdev_features_t features = dev->features;
3545
3546 if (skb_is_gso(skb))
3547 features = gso_features_check(skb, dev, features);
3548
3549 /* If encapsulation offload request, verify we are testing
3550 * hardware encapsulation features instead of standard
3551 * features for the netdev
3552 */
3553 if (skb->encapsulation)
3554 features &= dev->hw_enc_features;
3555
3556 if (skb_vlan_tagged(skb))
3557 features = netdev_intersect_features(features,
3558 dev->vlan_features |
3559 NETIF_F_HW_VLAN_CTAG_TX |
3560 NETIF_F_HW_VLAN_STAG_TX);
3561
3562 if (dev->netdev_ops->ndo_features_check)
3563 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3564 features);
3565 else
3566 features &= dflt_features_check(skb, dev, features);
3567
3568 return harmonize_features(skb, features);
3569 }
3570 EXPORT_SYMBOL(netif_skb_features);
3571
xmit_one(struct sk_buff * skb,struct net_device * dev,struct netdev_queue * txq,bool more)3572 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3573 struct netdev_queue *txq, bool more)
3574 {
3575 unsigned int len;
3576 int rc;
3577
3578 if (dev_nit_active(dev))
3579 dev_queue_xmit_nit(skb, dev);
3580
3581 len = skb->len;
3582 PRANDOM_ADD_NOISE(skb, dev, txq, len + jiffies);
3583 trace_net_dev_start_xmit(skb, dev);
3584 rc = netdev_start_xmit(skb, dev, txq, more);
3585 trace_net_dev_xmit(skb, rc, dev, len);
3586
3587 return rc;
3588 }
3589
dev_hard_start_xmit(struct sk_buff * first,struct net_device * dev,struct netdev_queue * txq,int * ret)3590 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3591 struct netdev_queue *txq, int *ret)
3592 {
3593 struct sk_buff *skb = first;
3594 int rc = NETDEV_TX_OK;
3595
3596 while (skb) {
3597 struct sk_buff *next = skb->next;
3598
3599 skb_mark_not_on_list(skb);
3600 rc = xmit_one(skb, dev, txq, next != NULL);
3601 if (unlikely(!dev_xmit_complete(rc))) {
3602 skb->next = next;
3603 goto out;
3604 }
3605
3606 skb = next;
3607 if (netif_tx_queue_stopped(txq) && skb) {
3608 rc = NETDEV_TX_BUSY;
3609 break;
3610 }
3611 }
3612
3613 out:
3614 *ret = rc;
3615 return skb;
3616 }
3617
validate_xmit_vlan(struct sk_buff * skb,netdev_features_t features)3618 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3619 netdev_features_t features)
3620 {
3621 if (skb_vlan_tag_present(skb) &&
3622 !vlan_hw_offload_capable(features, skb->vlan_proto))
3623 skb = __vlan_hwaccel_push_inside(skb);
3624 return skb;
3625 }
3626
skb_csum_hwoffload_help(struct sk_buff * skb,const netdev_features_t features)3627 int skb_csum_hwoffload_help(struct sk_buff *skb,
3628 const netdev_features_t features)
3629 {
3630 if (unlikely(skb->csum_not_inet))
3631 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3632 skb_crc32c_csum_help(skb);
3633
3634 return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
3635 }
3636 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3637
validate_xmit_skb(struct sk_buff * skb,struct net_device * dev,bool * again)3638 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3639 {
3640 netdev_features_t features;
3641
3642 features = netif_skb_features(skb);
3643 skb = validate_xmit_vlan(skb, features);
3644 if (unlikely(!skb))
3645 goto out_null;
3646
3647 skb = sk_validate_xmit_skb(skb, dev);
3648 if (unlikely(!skb))
3649 goto out_null;
3650
3651 if (netif_needs_gso(skb, features)) {
3652 struct sk_buff *segs;
3653
3654 segs = skb_gso_segment(skb, features);
3655 if (IS_ERR(segs)) {
3656 goto out_kfree_skb;
3657 } else if (segs) {
3658 consume_skb(skb);
3659 skb = segs;
3660 }
3661 } else {
3662 if (skb_needs_linearize(skb, features) &&
3663 __skb_linearize(skb))
3664 goto out_kfree_skb;
3665
3666 /* If packet is not checksummed and device does not
3667 * support checksumming for this protocol, complete
3668 * checksumming here.
3669 */
3670 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3671 if (skb->encapsulation)
3672 skb_set_inner_transport_header(skb,
3673 skb_checksum_start_offset(skb));
3674 else
3675 skb_set_transport_header(skb,
3676 skb_checksum_start_offset(skb));
3677 if (skb_csum_hwoffload_help(skb, features))
3678 goto out_kfree_skb;
3679 }
3680 }
3681
3682 skb = validate_xmit_xfrm(skb, features, again);
3683
3684 return skb;
3685
3686 out_kfree_skb:
3687 kfree_skb(skb);
3688 out_null:
3689 atomic_long_inc(&dev->tx_dropped);
3690 return NULL;
3691 }
3692
validate_xmit_skb_list(struct sk_buff * skb,struct net_device * dev,bool * again)3693 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3694 {
3695 struct sk_buff *next, *head = NULL, *tail;
3696
3697 for (; skb != NULL; skb = next) {
3698 next = skb->next;
3699 skb_mark_not_on_list(skb);
3700
3701 /* in case skb wont be segmented, point to itself */
3702 skb->prev = skb;
3703
3704 skb = validate_xmit_skb(skb, dev, again);
3705 if (!skb)
3706 continue;
3707
3708 if (!head)
3709 head = skb;
3710 else
3711 tail->next = skb;
3712 /* If skb was segmented, skb->prev points to
3713 * the last segment. If not, it still contains skb.
3714 */
3715 tail = skb->prev;
3716 }
3717 return head;
3718 }
3719 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3720
qdisc_pkt_len_init(struct sk_buff * skb)3721 static void qdisc_pkt_len_init(struct sk_buff *skb)
3722 {
3723 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3724
3725 qdisc_skb_cb(skb)->pkt_len = skb->len;
3726
3727 /* To get more precise estimation of bytes sent on wire,
3728 * we add to pkt_len the headers size of all segments
3729 */
3730 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3731 unsigned int hdr_len;
3732 u16 gso_segs = shinfo->gso_segs;
3733
3734 /* mac layer + network layer */
3735 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3736
3737 /* + transport layer */
3738 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3739 const struct tcphdr *th;
3740 struct tcphdr _tcphdr;
3741
3742 th = skb_header_pointer(skb, skb_transport_offset(skb),
3743 sizeof(_tcphdr), &_tcphdr);
3744 if (likely(th))
3745 hdr_len += __tcp_hdrlen(th);
3746 } else {
3747 struct udphdr _udphdr;
3748
3749 if (skb_header_pointer(skb, skb_transport_offset(skb),
3750 sizeof(_udphdr), &_udphdr))
3751 hdr_len += sizeof(struct udphdr);
3752 }
3753
3754 if (shinfo->gso_type & SKB_GSO_DODGY)
3755 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3756 shinfo->gso_size);
3757
3758 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3759 }
3760 }
3761
__dev_xmit_skb(struct sk_buff * skb,struct Qdisc * q,struct net_device * dev,struct netdev_queue * txq)3762 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3763 struct net_device *dev,
3764 struct netdev_queue *txq)
3765 {
3766 spinlock_t *root_lock = qdisc_lock(q);
3767 struct sk_buff *to_free = NULL;
3768 bool contended;
3769 int rc;
3770
3771 qdisc_calculate_pkt_len(skb, q);
3772
3773 if (q->flags & TCQ_F_NOLOCK) {
3774 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3775 if (likely(!netif_xmit_frozen_or_stopped(txq)))
3776 qdisc_run(q);
3777
3778 if (unlikely(to_free))
3779 kfree_skb_list(to_free);
3780 return rc;
3781 }
3782
3783 /*
3784 * Heuristic to force contended enqueues to serialize on a
3785 * separate lock before trying to get qdisc main lock.
3786 * This permits qdisc->running owner to get the lock more
3787 * often and dequeue packets faster.
3788 */
3789 contended = qdisc_is_running(q);
3790 if (unlikely(contended))
3791 spin_lock(&q->busylock);
3792
3793 spin_lock(root_lock);
3794 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3795 __qdisc_drop(skb, &to_free);
3796 rc = NET_XMIT_DROP;
3797 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3798 qdisc_run_begin(q)) {
3799 /*
3800 * This is a work-conserving queue; there are no old skbs
3801 * waiting to be sent out; and the qdisc is not running -
3802 * xmit the skb directly.
3803 */
3804
3805 qdisc_bstats_update(q, skb);
3806
3807 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3808 if (unlikely(contended)) {
3809 spin_unlock(&q->busylock);
3810 contended = false;
3811 }
3812 __qdisc_run(q);
3813 }
3814
3815 qdisc_run_end(q);
3816 rc = NET_XMIT_SUCCESS;
3817 } else {
3818 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3819 if (qdisc_run_begin(q)) {
3820 if (unlikely(contended)) {
3821 spin_unlock(&q->busylock);
3822 contended = false;
3823 }
3824 __qdisc_run(q);
3825 qdisc_run_end(q);
3826 }
3827 }
3828 spin_unlock(root_lock);
3829 if (unlikely(to_free))
3830 kfree_skb_list(to_free);
3831 if (unlikely(contended))
3832 spin_unlock(&q->busylock);
3833 return rc;
3834 }
3835
3836 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
skb_update_prio(struct sk_buff * skb)3837 static void skb_update_prio(struct sk_buff *skb)
3838 {
3839 const struct netprio_map *map;
3840 const struct sock *sk;
3841 unsigned int prioidx;
3842
3843 if (skb->priority)
3844 return;
3845 map = rcu_dereference_bh(skb->dev->priomap);
3846 if (!map)
3847 return;
3848 sk = skb_to_full_sk(skb);
3849 if (!sk)
3850 return;
3851
3852 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3853
3854 if (prioidx < map->priomap_len)
3855 skb->priority = map->priomap[prioidx];
3856 }
3857 #else
3858 #define skb_update_prio(skb)
3859 #endif
3860
3861 /**
3862 * dev_loopback_xmit - loop back @skb
3863 * @net: network namespace this loopback is happening in
3864 * @sk: sk needed to be a netfilter okfn
3865 * @skb: buffer to transmit
3866 */
dev_loopback_xmit(struct net * net,struct sock * sk,struct sk_buff * skb)3867 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3868 {
3869 skb_reset_mac_header(skb);
3870 __skb_pull(skb, skb_network_offset(skb));
3871 skb->pkt_type = PACKET_LOOPBACK;
3872 if (skb->ip_summed == CHECKSUM_NONE)
3873 skb->ip_summed = CHECKSUM_UNNECESSARY;
3874 WARN_ON(!skb_dst(skb));
3875 skb_dst_force(skb);
3876 netif_rx_ni(skb);
3877 return 0;
3878 }
3879 EXPORT_SYMBOL(dev_loopback_xmit);
3880
3881 #ifdef CONFIG_NET_EGRESS
3882 static struct sk_buff *
sch_handle_egress(struct sk_buff * skb,int * ret,struct net_device * dev)3883 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3884 {
3885 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3886 struct tcf_result cl_res;
3887
3888 if (!miniq)
3889 return skb;
3890
3891 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3892 qdisc_skb_cb(skb)->mru = 0;
3893 mini_qdisc_bstats_cpu_update(miniq, skb);
3894
3895 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
3896 case TC_ACT_OK:
3897 case TC_ACT_RECLASSIFY:
3898 skb->tc_index = TC_H_MIN(cl_res.classid);
3899 break;
3900 case TC_ACT_SHOT:
3901 mini_qdisc_qstats_cpu_drop(miniq);
3902 *ret = NET_XMIT_DROP;
3903 kfree_skb(skb);
3904 return NULL;
3905 case TC_ACT_STOLEN:
3906 case TC_ACT_QUEUED:
3907 case TC_ACT_TRAP:
3908 *ret = NET_XMIT_SUCCESS;
3909 consume_skb(skb);
3910 return NULL;
3911 case TC_ACT_REDIRECT:
3912 /* No need to push/pop skb's mac_header here on egress! */
3913 skb_do_redirect(skb);
3914 *ret = NET_XMIT_SUCCESS;
3915 return NULL;
3916 default:
3917 break;
3918 }
3919
3920 return skb;
3921 }
3922 #endif /* CONFIG_NET_EGRESS */
3923
3924 #ifdef CONFIG_XPS
__get_xps_queue_idx(struct net_device * dev,struct sk_buff * skb,struct xps_dev_maps * dev_maps,unsigned int tci)3925 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3926 struct xps_dev_maps *dev_maps, unsigned int tci)
3927 {
3928 struct xps_map *map;
3929 int queue_index = -1;
3930
3931 if (dev->num_tc) {
3932 tci *= dev->num_tc;
3933 tci += netdev_get_prio_tc_map(dev, skb->priority);
3934 }
3935
3936 map = rcu_dereference(dev_maps->attr_map[tci]);
3937 if (map) {
3938 if (map->len == 1)
3939 queue_index = map->queues[0];
3940 else
3941 queue_index = map->queues[reciprocal_scale(
3942 skb_get_hash(skb), map->len)];
3943 if (unlikely(queue_index >= dev->real_num_tx_queues))
3944 queue_index = -1;
3945 }
3946 return queue_index;
3947 }
3948 #endif
3949
get_xps_queue(struct net_device * dev,struct net_device * sb_dev,struct sk_buff * skb)3950 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3951 struct sk_buff *skb)
3952 {
3953 #ifdef CONFIG_XPS
3954 struct xps_dev_maps *dev_maps;
3955 struct sock *sk = skb->sk;
3956 int queue_index = -1;
3957
3958 if (!static_key_false(&xps_needed))
3959 return -1;
3960
3961 rcu_read_lock();
3962 if (!static_key_false(&xps_rxqs_needed))
3963 goto get_cpus_map;
3964
3965 dev_maps = rcu_dereference(sb_dev->xps_rxqs_map);
3966 if (dev_maps) {
3967 int tci = sk_rx_queue_get(sk);
3968
3969 if (tci >= 0 && tci < dev->num_rx_queues)
3970 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3971 tci);
3972 }
3973
3974 get_cpus_map:
3975 if (queue_index < 0) {
3976 dev_maps = rcu_dereference(sb_dev->xps_cpus_map);
3977 if (dev_maps) {
3978 unsigned int tci = skb->sender_cpu - 1;
3979
3980 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3981 tci);
3982 }
3983 }
3984 rcu_read_unlock();
3985
3986 return queue_index;
3987 #else
3988 return -1;
3989 #endif
3990 }
3991
dev_pick_tx_zero(struct net_device * dev,struct sk_buff * skb,struct net_device * sb_dev)3992 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3993 struct net_device *sb_dev)
3994 {
3995 return 0;
3996 }
3997 EXPORT_SYMBOL(dev_pick_tx_zero);
3998
dev_pick_tx_cpu_id(struct net_device * dev,struct sk_buff * skb,struct net_device * sb_dev)3999 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
4000 struct net_device *sb_dev)
4001 {
4002 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
4003 }
4004 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
4005
netdev_pick_tx(struct net_device * dev,struct sk_buff * skb,struct net_device * sb_dev)4006 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4007 struct net_device *sb_dev)
4008 {
4009 struct sock *sk = skb->sk;
4010 int queue_index = sk_tx_queue_get(sk);
4011
4012 sb_dev = sb_dev ? : dev;
4013
4014 if (queue_index < 0 || skb->ooo_okay ||
4015 queue_index >= dev->real_num_tx_queues) {
4016 int new_index = get_xps_queue(dev, sb_dev, skb);
4017
4018 if (new_index < 0)
4019 new_index = skb_tx_hash(dev, sb_dev, skb);
4020
4021 if (queue_index != new_index && sk &&
4022 sk_fullsock(sk) &&
4023 rcu_access_pointer(sk->sk_dst_cache))
4024 sk_tx_queue_set(sk, new_index);
4025
4026 queue_index = new_index;
4027 }
4028
4029 return queue_index;
4030 }
4031 EXPORT_SYMBOL(netdev_pick_tx);
4032
netdev_core_pick_tx(struct net_device * dev,struct sk_buff * skb,struct net_device * sb_dev)4033 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4034 struct sk_buff *skb,
4035 struct net_device *sb_dev)
4036 {
4037 int queue_index = 0;
4038
4039 #ifdef CONFIG_XPS
4040 u32 sender_cpu = skb->sender_cpu - 1;
4041
4042 if (sender_cpu >= (u32)NR_CPUS)
4043 skb->sender_cpu = raw_smp_processor_id() + 1;
4044 #endif
4045
4046 if (dev->real_num_tx_queues != 1) {
4047 const struct net_device_ops *ops = dev->netdev_ops;
4048
4049 if (ops->ndo_select_queue)
4050 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4051 else
4052 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4053
4054 queue_index = netdev_cap_txqueue(dev, queue_index);
4055 }
4056
4057 skb_set_queue_mapping(skb, queue_index);
4058 return netdev_get_tx_queue(dev, queue_index);
4059 }
4060
4061 /**
4062 * __dev_queue_xmit - transmit a buffer
4063 * @skb: buffer to transmit
4064 * @sb_dev: suboordinate device used for L2 forwarding offload
4065 *
4066 * Queue a buffer for transmission to a network device. The caller must
4067 * have set the device and priority and built the buffer before calling
4068 * this function. The function can be called from an interrupt.
4069 *
4070 * A negative errno code is returned on a failure. A success does not
4071 * guarantee the frame will be transmitted as it may be dropped due
4072 * to congestion or traffic shaping.
4073 *
4074 * -----------------------------------------------------------------------------------
4075 * I notice this method can also return errors from the queue disciplines,
4076 * including NET_XMIT_DROP, which is a positive value. So, errors can also
4077 * be positive.
4078 *
4079 * Regardless of the return value, the skb is consumed, so it is currently
4080 * difficult to retry a send to this method. (You can bump the ref count
4081 * before sending to hold a reference for retry if you are careful.)
4082 *
4083 * When calling this method, interrupts MUST be enabled. This is because
4084 * the BH enable code must have IRQs enabled so that it will not deadlock.
4085 * --BLG
4086 */
__dev_queue_xmit(struct sk_buff * skb,struct net_device * sb_dev)4087 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4088 {
4089 struct net_device *dev = skb->dev;
4090 struct netdev_queue *txq;
4091 struct Qdisc *q;
4092 int rc = -ENOMEM;
4093 bool again = false;
4094
4095 skb_reset_mac_header(skb);
4096
4097 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4098 __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
4099
4100 /* Disable soft irqs for various locks below. Also
4101 * stops preemption for RCU.
4102 */
4103 rcu_read_lock_bh();
4104
4105 skb_update_prio(skb);
4106
4107 qdisc_pkt_len_init(skb);
4108 #ifdef CONFIG_NET_CLS_ACT
4109 skb->tc_at_ingress = 0;
4110 # ifdef CONFIG_NET_EGRESS
4111 if (static_branch_unlikely(&egress_needed_key)) {
4112 skb = sch_handle_egress(skb, &rc, dev);
4113 if (!skb)
4114 goto out;
4115 }
4116 # endif
4117 #endif
4118 /* If device/qdisc don't need skb->dst, release it right now while
4119 * its hot in this cpu cache.
4120 */
4121 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4122 skb_dst_drop(skb);
4123 else
4124 skb_dst_force(skb);
4125
4126 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4127 q = rcu_dereference_bh(txq->qdisc);
4128
4129 trace_net_dev_queue(skb);
4130 if (q->enqueue) {
4131 rc = __dev_xmit_skb(skb, q, dev, txq);
4132 goto out;
4133 }
4134
4135 /* The device has no queue. Common case for software devices:
4136 * loopback, all the sorts of tunnels...
4137
4138 * Really, it is unlikely that netif_tx_lock protection is necessary
4139 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4140 * counters.)
4141 * However, it is possible, that they rely on protection
4142 * made by us here.
4143
4144 * Check this and shot the lock. It is not prone from deadlocks.
4145 *Either shot noqueue qdisc, it is even simpler 8)
4146 */
4147 if (dev->flags & IFF_UP) {
4148 int cpu = smp_processor_id(); /* ok because BHs are off */
4149
4150 /* Other cpus might concurrently change txq->xmit_lock_owner
4151 * to -1 or to their cpu id, but not to our id.
4152 */
4153 if (READ_ONCE(txq->xmit_lock_owner) != cpu) {
4154 if (dev_xmit_recursion())
4155 goto recursion_alert;
4156
4157 skb = validate_xmit_skb(skb, dev, &again);
4158 if (!skb)
4159 goto out;
4160
4161 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4162 HARD_TX_LOCK(dev, txq, cpu);
4163
4164 if (!netif_xmit_stopped(txq)) {
4165 dev_xmit_recursion_inc();
4166 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4167 dev_xmit_recursion_dec();
4168 if (dev_xmit_complete(rc)) {
4169 HARD_TX_UNLOCK(dev, txq);
4170 goto out;
4171 }
4172 }
4173 HARD_TX_UNLOCK(dev, txq);
4174 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4175 dev->name);
4176 } else {
4177 /* Recursion is detected! It is possible,
4178 * unfortunately
4179 */
4180 recursion_alert:
4181 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4182 dev->name);
4183 }
4184 }
4185
4186 rc = -ENETDOWN;
4187 rcu_read_unlock_bh();
4188
4189 atomic_long_inc(&dev->tx_dropped);
4190 kfree_skb_list(skb);
4191 return rc;
4192 out:
4193 rcu_read_unlock_bh();
4194 return rc;
4195 }
4196
dev_queue_xmit(struct sk_buff * skb)4197 int dev_queue_xmit(struct sk_buff *skb)
4198 {
4199 return __dev_queue_xmit(skb, NULL);
4200 }
4201 EXPORT_SYMBOL(dev_queue_xmit);
4202
dev_queue_xmit_accel(struct sk_buff * skb,struct net_device * sb_dev)4203 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
4204 {
4205 return __dev_queue_xmit(skb, sb_dev);
4206 }
4207 EXPORT_SYMBOL(dev_queue_xmit_accel);
4208
__dev_direct_xmit(struct sk_buff * skb,u16 queue_id)4209 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4210 {
4211 struct net_device *dev = skb->dev;
4212 struct sk_buff *orig_skb = skb;
4213 struct netdev_queue *txq;
4214 int ret = NETDEV_TX_BUSY;
4215 bool again = false;
4216
4217 if (unlikely(!netif_running(dev) ||
4218 !netif_carrier_ok(dev)))
4219 goto drop;
4220
4221 skb = validate_xmit_skb_list(skb, dev, &again);
4222 if (skb != orig_skb)
4223 goto drop;
4224
4225 skb_set_queue_mapping(skb, queue_id);
4226 txq = skb_get_tx_queue(dev, skb);
4227 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4228
4229 local_bh_disable();
4230
4231 dev_xmit_recursion_inc();
4232 HARD_TX_LOCK(dev, txq, smp_processor_id());
4233 if (!netif_xmit_frozen_or_drv_stopped(txq))
4234 ret = netdev_start_xmit(skb, dev, txq, false);
4235 HARD_TX_UNLOCK(dev, txq);
4236 dev_xmit_recursion_dec();
4237
4238 local_bh_enable();
4239 return ret;
4240 drop:
4241 atomic_long_inc(&dev->tx_dropped);
4242 kfree_skb_list(skb);
4243 return NET_XMIT_DROP;
4244 }
4245 EXPORT_SYMBOL(__dev_direct_xmit);
4246
4247 /*************************************************************************
4248 * Receiver routines
4249 *************************************************************************/
4250
4251 int netdev_max_backlog __read_mostly = 1000;
4252 EXPORT_SYMBOL(netdev_max_backlog);
4253
4254 int netdev_tstamp_prequeue __read_mostly = 1;
4255 int netdev_budget __read_mostly = 300;
4256 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4257 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4258 int weight_p __read_mostly = 64; /* old backlog weight */
4259 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4260 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4261 int dev_rx_weight __read_mostly = 64;
4262 int dev_tx_weight __read_mostly = 64;
4263 /* Maximum number of GRO_NORMAL skbs to batch up for list-RX */
4264 int gro_normal_batch __read_mostly = 8;
4265
4266 /* Called with irq disabled */
____napi_schedule(struct softnet_data * sd,struct napi_struct * napi)4267 static inline void ____napi_schedule(struct softnet_data *sd,
4268 struct napi_struct *napi)
4269 {
4270 list_add_tail(&napi->poll_list, &sd->poll_list);
4271 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4272 }
4273
4274 #ifdef CONFIG_RPS
4275
4276 /* One global table that all flow-based protocols share. */
4277 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4278 EXPORT_SYMBOL(rps_sock_flow_table);
4279 u32 rps_cpu_mask __read_mostly;
4280 EXPORT_SYMBOL(rps_cpu_mask);
4281
4282 struct static_key_false rps_needed __read_mostly;
4283 EXPORT_SYMBOL(rps_needed);
4284 struct static_key_false rfs_needed __read_mostly;
4285 EXPORT_SYMBOL(rfs_needed);
4286
4287 static struct rps_dev_flow *
set_rps_cpu(struct net_device * dev,struct sk_buff * skb,struct rps_dev_flow * rflow,u16 next_cpu)4288 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4289 struct rps_dev_flow *rflow, u16 next_cpu)
4290 {
4291 if (next_cpu < nr_cpu_ids) {
4292 #ifdef CONFIG_RFS_ACCEL
4293 struct netdev_rx_queue *rxqueue;
4294 struct rps_dev_flow_table *flow_table;
4295 struct rps_dev_flow *old_rflow;
4296 u32 flow_id;
4297 u16 rxq_index;
4298 int rc;
4299
4300 /* Should we steer this flow to a different hardware queue? */
4301 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4302 !(dev->features & NETIF_F_NTUPLE))
4303 goto out;
4304 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4305 if (rxq_index == skb_get_rx_queue(skb))
4306 goto out;
4307
4308 rxqueue = dev->_rx + rxq_index;
4309 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4310 if (!flow_table)
4311 goto out;
4312 flow_id = skb_get_hash(skb) & flow_table->mask;
4313 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4314 rxq_index, flow_id);
4315 if (rc < 0)
4316 goto out;
4317 old_rflow = rflow;
4318 rflow = &flow_table->flows[flow_id];
4319 rflow->filter = rc;
4320 if (old_rflow->filter == rflow->filter)
4321 old_rflow->filter = RPS_NO_FILTER;
4322 out:
4323 #endif
4324 rflow->last_qtail =
4325 per_cpu(softnet_data, next_cpu).input_queue_head;
4326 }
4327
4328 rflow->cpu = next_cpu;
4329 return rflow;
4330 }
4331
4332 /*
4333 * get_rps_cpu is called from netif_receive_skb and returns the target
4334 * CPU from the RPS map of the receiving queue for a given skb.
4335 * rcu_read_lock must be held on entry.
4336 */
get_rps_cpu(struct net_device * dev,struct sk_buff * skb,struct rps_dev_flow ** rflowp)4337 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4338 struct rps_dev_flow **rflowp)
4339 {
4340 const struct rps_sock_flow_table *sock_flow_table;
4341 struct netdev_rx_queue *rxqueue = dev->_rx;
4342 struct rps_dev_flow_table *flow_table;
4343 struct rps_map *map;
4344 int cpu = -1;
4345 u32 tcpu;
4346 u32 hash;
4347
4348 if (skb_rx_queue_recorded(skb)) {
4349 u16 index = skb_get_rx_queue(skb);
4350
4351 if (unlikely(index >= dev->real_num_rx_queues)) {
4352 WARN_ONCE(dev->real_num_rx_queues > 1,
4353 "%s received packet on queue %u, but number "
4354 "of RX queues is %u\n",
4355 dev->name, index, dev->real_num_rx_queues);
4356 goto done;
4357 }
4358 rxqueue += index;
4359 }
4360
4361 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4362
4363 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4364 map = rcu_dereference(rxqueue->rps_map);
4365 if (!flow_table && !map)
4366 goto done;
4367
4368 skb_reset_network_header(skb);
4369 hash = skb_get_hash(skb);
4370 if (!hash)
4371 goto done;
4372
4373 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4374 if (flow_table && sock_flow_table) {
4375 struct rps_dev_flow *rflow;
4376 u32 next_cpu;
4377 u32 ident;
4378
4379 /* First check into global flow table if there is a match */
4380 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4381 if ((ident ^ hash) & ~rps_cpu_mask)
4382 goto try_rps;
4383
4384 next_cpu = ident & rps_cpu_mask;
4385
4386 /* OK, now we know there is a match,
4387 * we can look at the local (per receive queue) flow table
4388 */
4389 rflow = &flow_table->flows[hash & flow_table->mask];
4390 tcpu = rflow->cpu;
4391
4392 /*
4393 * If the desired CPU (where last recvmsg was done) is
4394 * different from current CPU (one in the rx-queue flow
4395 * table entry), switch if one of the following holds:
4396 * - Current CPU is unset (>= nr_cpu_ids).
4397 * - Current CPU is offline.
4398 * - The current CPU's queue tail has advanced beyond the
4399 * last packet that was enqueued using this table entry.
4400 * This guarantees that all previous packets for the flow
4401 * have been dequeued, thus preserving in order delivery.
4402 */
4403 if (unlikely(tcpu != next_cpu) &&
4404 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4405 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4406 rflow->last_qtail)) >= 0)) {
4407 tcpu = next_cpu;
4408 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4409 }
4410
4411 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4412 *rflowp = rflow;
4413 cpu = tcpu;
4414 goto done;
4415 }
4416 }
4417
4418 try_rps:
4419
4420 if (map) {
4421 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4422 if (cpu_online(tcpu)) {
4423 cpu = tcpu;
4424 goto done;
4425 }
4426 }
4427
4428 done:
4429 return cpu;
4430 }
4431
4432 #ifdef CONFIG_RFS_ACCEL
4433
4434 /**
4435 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4436 * @dev: Device on which the filter was set
4437 * @rxq_index: RX queue index
4438 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4439 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4440 *
4441 * Drivers that implement ndo_rx_flow_steer() should periodically call
4442 * this function for each installed filter and remove the filters for
4443 * which it returns %true.
4444 */
rps_may_expire_flow(struct net_device * dev,u16 rxq_index,u32 flow_id,u16 filter_id)4445 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4446 u32 flow_id, u16 filter_id)
4447 {
4448 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4449 struct rps_dev_flow_table *flow_table;
4450 struct rps_dev_flow *rflow;
4451 bool expire = true;
4452 unsigned int cpu;
4453
4454 rcu_read_lock();
4455 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4456 if (flow_table && flow_id <= flow_table->mask) {
4457 rflow = &flow_table->flows[flow_id];
4458 cpu = READ_ONCE(rflow->cpu);
4459 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4460 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4461 rflow->last_qtail) <
4462 (int)(10 * flow_table->mask)))
4463 expire = false;
4464 }
4465 rcu_read_unlock();
4466 return expire;
4467 }
4468 EXPORT_SYMBOL(rps_may_expire_flow);
4469
4470 #endif /* CONFIG_RFS_ACCEL */
4471
4472 /* Called from hardirq (IPI) context */
rps_trigger_softirq(void * data)4473 static void rps_trigger_softirq(void *data)
4474 {
4475 struct softnet_data *sd = data;
4476
4477 ____napi_schedule(sd, &sd->backlog);
4478 sd->received_rps++;
4479 }
4480
4481 #endif /* CONFIG_RPS */
4482
4483 /*
4484 * Check if this softnet_data structure is another cpu one
4485 * If yes, queue it to our IPI list and return 1
4486 * If no, return 0
4487 */
rps_ipi_queued(struct softnet_data * sd)4488 static int rps_ipi_queued(struct softnet_data *sd)
4489 {
4490 #ifdef CONFIG_RPS
4491 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4492
4493 if (sd != mysd) {
4494 sd->rps_ipi_next = mysd->rps_ipi_list;
4495 mysd->rps_ipi_list = sd;
4496
4497 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4498 return 1;
4499 }
4500 #endif /* CONFIG_RPS */
4501 return 0;
4502 }
4503
4504 #ifdef CONFIG_NET_FLOW_LIMIT
4505 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4506 #endif
4507
skb_flow_limit(struct sk_buff * skb,unsigned int qlen)4508 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4509 {
4510 #ifdef CONFIG_NET_FLOW_LIMIT
4511 struct sd_flow_limit *fl;
4512 struct softnet_data *sd;
4513 unsigned int old_flow, new_flow;
4514
4515 if (qlen < (netdev_max_backlog >> 1))
4516 return false;
4517
4518 sd = this_cpu_ptr(&softnet_data);
4519
4520 rcu_read_lock();
4521 fl = rcu_dereference(sd->flow_limit);
4522 if (fl) {
4523 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4524 old_flow = fl->history[fl->history_head];
4525 fl->history[fl->history_head] = new_flow;
4526
4527 fl->history_head++;
4528 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4529
4530 if (likely(fl->buckets[old_flow]))
4531 fl->buckets[old_flow]--;
4532
4533 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4534 fl->count++;
4535 rcu_read_unlock();
4536 return true;
4537 }
4538 }
4539 rcu_read_unlock();
4540 #endif
4541 return false;
4542 }
4543
4544 /*
4545 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4546 * queue (may be a remote CPU queue).
4547 */
enqueue_to_backlog(struct sk_buff * skb,int cpu,unsigned int * qtail)4548 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4549 unsigned int *qtail)
4550 {
4551 struct softnet_data *sd;
4552 unsigned long flags;
4553 unsigned int qlen;
4554
4555 sd = &per_cpu(softnet_data, cpu);
4556
4557 local_irq_save(flags);
4558
4559 rps_lock(sd);
4560 if (!netif_running(skb->dev))
4561 goto drop;
4562 qlen = skb_queue_len(&sd->input_pkt_queue);
4563 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
4564 if (qlen) {
4565 enqueue:
4566 __skb_queue_tail(&sd->input_pkt_queue, skb);
4567 input_queue_tail_incr_save(sd, qtail);
4568 rps_unlock(sd);
4569 local_irq_restore(flags);
4570 return NET_RX_SUCCESS;
4571 }
4572
4573 /* Schedule NAPI for backlog device
4574 * We can use non atomic operation since we own the queue lock
4575 */
4576 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
4577 if (!rps_ipi_queued(sd))
4578 ____napi_schedule(sd, &sd->backlog);
4579 }
4580 goto enqueue;
4581 }
4582
4583 drop:
4584 sd->dropped++;
4585 rps_unlock(sd);
4586
4587 local_irq_restore(flags);
4588
4589 atomic_long_inc(&skb->dev->rx_dropped);
4590 kfree_skb(skb);
4591 return NET_RX_DROP;
4592 }
4593
netif_get_rxqueue(struct sk_buff * skb)4594 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4595 {
4596 struct net_device *dev = skb->dev;
4597 struct netdev_rx_queue *rxqueue;
4598
4599 rxqueue = dev->_rx;
4600
4601 if (skb_rx_queue_recorded(skb)) {
4602 u16 index = skb_get_rx_queue(skb);
4603
4604 if (unlikely(index >= dev->real_num_rx_queues)) {
4605 WARN_ONCE(dev->real_num_rx_queues > 1,
4606 "%s received packet on queue %u, but number "
4607 "of RX queues is %u\n",
4608 dev->name, index, dev->real_num_rx_queues);
4609
4610 return rxqueue; /* Return first rxqueue */
4611 }
4612 rxqueue += index;
4613 }
4614 return rxqueue;
4615 }
4616
netif_receive_generic_xdp(struct sk_buff * skb,struct xdp_buff * xdp,struct bpf_prog * xdp_prog)4617 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4618 struct xdp_buff *xdp,
4619 struct bpf_prog *xdp_prog)
4620 {
4621 struct netdev_rx_queue *rxqueue;
4622 void *orig_data, *orig_data_end;
4623 u32 metalen, act = XDP_DROP;
4624 __be16 orig_eth_type;
4625 struct ethhdr *eth;
4626 bool orig_bcast;
4627 int hlen, off;
4628 u32 mac_len;
4629
4630 /* Reinjected packets coming from act_mirred or similar should
4631 * not get XDP generic processing.
4632 */
4633 if (skb_is_redirected(skb))
4634 return XDP_PASS;
4635
4636 /* XDP packets must be linear and must have sufficient headroom
4637 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4638 * native XDP provides, thus we need to do it here as well.
4639 */
4640 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4641 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4642 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4643 int troom = skb->tail + skb->data_len - skb->end;
4644
4645 /* In case we have to go down the path and also linearize,
4646 * then lets do the pskb_expand_head() work just once here.
4647 */
4648 if (pskb_expand_head(skb,
4649 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4650 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4651 goto do_drop;
4652 if (skb_linearize(skb))
4653 goto do_drop;
4654 }
4655
4656 /* The XDP program wants to see the packet starting at the MAC
4657 * header.
4658 */
4659 mac_len = skb->data - skb_mac_header(skb);
4660 hlen = skb_headlen(skb) + mac_len;
4661 xdp->data = skb->data - mac_len;
4662 xdp->data_meta = xdp->data;
4663 xdp->data_end = xdp->data + hlen;
4664 xdp->data_hard_start = skb->data - skb_headroom(skb);
4665
4666 /* SKB "head" area always have tailroom for skb_shared_info */
4667 xdp->frame_sz = (void *)skb_end_pointer(skb) - xdp->data_hard_start;
4668 xdp->frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4669
4670 orig_data_end = xdp->data_end;
4671 orig_data = xdp->data;
4672 eth = (struct ethhdr *)xdp->data;
4673 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4674 orig_eth_type = eth->h_proto;
4675
4676 rxqueue = netif_get_rxqueue(skb);
4677 xdp->rxq = &rxqueue->xdp_rxq;
4678
4679 act = bpf_prog_run_xdp(xdp_prog, xdp);
4680
4681 /* check if bpf_xdp_adjust_head was used */
4682 off = xdp->data - orig_data;
4683 if (off) {
4684 if (off > 0)
4685 __skb_pull(skb, off);
4686 else if (off < 0)
4687 __skb_push(skb, -off);
4688
4689 skb->mac_header += off;
4690 skb_reset_network_header(skb);
4691 }
4692
4693 /* check if bpf_xdp_adjust_tail was used */
4694 off = xdp->data_end - orig_data_end;
4695 if (off != 0) {
4696 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4697 skb->len += off; /* positive on grow, negative on shrink */
4698 }
4699
4700 /* check if XDP changed eth hdr such SKB needs update */
4701 eth = (struct ethhdr *)xdp->data;
4702 if ((orig_eth_type != eth->h_proto) ||
4703 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4704 __skb_push(skb, ETH_HLEN);
4705 skb->protocol = eth_type_trans(skb, skb->dev);
4706 }
4707
4708 switch (act) {
4709 case XDP_REDIRECT:
4710 case XDP_TX:
4711 __skb_push(skb, mac_len);
4712 break;
4713 case XDP_PASS:
4714 metalen = xdp->data - xdp->data_meta;
4715 if (metalen)
4716 skb_metadata_set(skb, metalen);
4717 break;
4718 default:
4719 bpf_warn_invalid_xdp_action(act);
4720 fallthrough;
4721 case XDP_ABORTED:
4722 trace_xdp_exception(skb->dev, xdp_prog, act);
4723 fallthrough;
4724 case XDP_DROP:
4725 do_drop:
4726 kfree_skb(skb);
4727 break;
4728 }
4729
4730 return act;
4731 }
4732
4733 /* When doing generic XDP we have to bypass the qdisc layer and the
4734 * network taps in order to match in-driver-XDP behavior.
4735 */
generic_xdp_tx(struct sk_buff * skb,struct bpf_prog * xdp_prog)4736 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4737 {
4738 struct net_device *dev = skb->dev;
4739 struct netdev_queue *txq;
4740 bool free_skb = true;
4741 int cpu, rc;
4742
4743 txq = netdev_core_pick_tx(dev, skb, NULL);
4744 cpu = smp_processor_id();
4745 HARD_TX_LOCK(dev, txq, cpu);
4746 if (!netif_xmit_stopped(txq)) {
4747 rc = netdev_start_xmit(skb, dev, txq, 0);
4748 if (dev_xmit_complete(rc))
4749 free_skb = false;
4750 }
4751 HARD_TX_UNLOCK(dev, txq);
4752 if (free_skb) {
4753 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4754 kfree_skb(skb);
4755 }
4756 }
4757
4758 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4759
do_xdp_generic(struct bpf_prog * xdp_prog,struct sk_buff * skb)4760 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4761 {
4762 if (xdp_prog) {
4763 struct xdp_buff xdp;
4764 u32 act;
4765 int err;
4766
4767 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4768 if (act != XDP_PASS) {
4769 switch (act) {
4770 case XDP_REDIRECT:
4771 err = xdp_do_generic_redirect(skb->dev, skb,
4772 &xdp, xdp_prog);
4773 if (err)
4774 goto out_redir;
4775 break;
4776 case XDP_TX:
4777 generic_xdp_tx(skb, xdp_prog);
4778 break;
4779 }
4780 return XDP_DROP;
4781 }
4782 }
4783 return XDP_PASS;
4784 out_redir:
4785 kfree_skb(skb);
4786 return XDP_DROP;
4787 }
4788 EXPORT_SYMBOL_GPL(do_xdp_generic);
4789
netif_rx_internal(struct sk_buff * skb)4790 static int netif_rx_internal(struct sk_buff *skb)
4791 {
4792 int ret;
4793
4794 net_timestamp_check(netdev_tstamp_prequeue, skb);
4795
4796 trace_netif_rx(skb);
4797
4798 #ifdef CONFIG_RPS
4799 if (static_branch_unlikely(&rps_needed)) {
4800 struct rps_dev_flow voidflow, *rflow = &voidflow;
4801 int cpu;
4802
4803 preempt_disable();
4804 rcu_read_lock();
4805
4806 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4807 if (cpu < 0)
4808 cpu = smp_processor_id();
4809
4810 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4811
4812 rcu_read_unlock();
4813 preempt_enable();
4814 } else
4815 #endif
4816 {
4817 unsigned int qtail;
4818
4819 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
4820 put_cpu();
4821 }
4822 return ret;
4823 }
4824
4825 /**
4826 * netif_rx - post buffer to the network code
4827 * @skb: buffer to post
4828 *
4829 * This function receives a packet from a device driver and queues it for
4830 * the upper (protocol) levels to process. It always succeeds. The buffer
4831 * may be dropped during processing for congestion control or by the
4832 * protocol layers.
4833 *
4834 * return values:
4835 * NET_RX_SUCCESS (no congestion)
4836 * NET_RX_DROP (packet was dropped)
4837 *
4838 */
4839
netif_rx(struct sk_buff * skb)4840 int netif_rx(struct sk_buff *skb)
4841 {
4842 int ret;
4843
4844 trace_netif_rx_entry(skb);
4845
4846 ret = netif_rx_internal(skb);
4847 trace_netif_rx_exit(ret);
4848
4849 return ret;
4850 }
4851 EXPORT_SYMBOL(netif_rx);
4852
netif_rx_ni(struct sk_buff * skb)4853 int netif_rx_ni(struct sk_buff *skb)
4854 {
4855 int err;
4856
4857 trace_netif_rx_ni_entry(skb);
4858
4859 preempt_disable();
4860 err = netif_rx_internal(skb);
4861 if (local_softirq_pending())
4862 do_softirq();
4863 preempt_enable();
4864 trace_netif_rx_ni_exit(err);
4865
4866 return err;
4867 }
4868 EXPORT_SYMBOL(netif_rx_ni);
4869
netif_rx_any_context(struct sk_buff * skb)4870 int netif_rx_any_context(struct sk_buff *skb)
4871 {
4872 /*
4873 * If invoked from contexts which do not invoke bottom half
4874 * processing either at return from interrupt or when softrqs are
4875 * reenabled, use netif_rx_ni() which invokes bottomhalf processing
4876 * directly.
4877 */
4878 if (in_interrupt())
4879 return netif_rx(skb);
4880 else
4881 return netif_rx_ni(skb);
4882 }
4883 EXPORT_SYMBOL(netif_rx_any_context);
4884
net_tx_action(struct softirq_action * h)4885 static __latent_entropy void net_tx_action(struct softirq_action *h)
4886 {
4887 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4888
4889 if (sd->completion_queue) {
4890 struct sk_buff *clist;
4891
4892 local_irq_disable();
4893 clist = sd->completion_queue;
4894 sd->completion_queue = NULL;
4895 local_irq_enable();
4896
4897 while (clist) {
4898 struct sk_buff *skb = clist;
4899
4900 clist = clist->next;
4901
4902 WARN_ON(refcount_read(&skb->users));
4903 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4904 trace_consume_skb(skb);
4905 else
4906 trace_kfree_skb(skb, net_tx_action);
4907
4908 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4909 __kfree_skb(skb);
4910 else
4911 __kfree_skb_defer(skb);
4912 }
4913
4914 __kfree_skb_flush();
4915 }
4916
4917 if (sd->output_queue) {
4918 struct Qdisc *head;
4919
4920 local_irq_disable();
4921 head = sd->output_queue;
4922 sd->output_queue = NULL;
4923 sd->output_queue_tailp = &sd->output_queue;
4924 local_irq_enable();
4925
4926 rcu_read_lock();
4927
4928 while (head) {
4929 struct Qdisc *q = head;
4930 spinlock_t *root_lock = NULL;
4931
4932 head = head->next_sched;
4933
4934 /* We need to make sure head->next_sched is read
4935 * before clearing __QDISC_STATE_SCHED
4936 */
4937 smp_mb__before_atomic();
4938
4939 if (!(q->flags & TCQ_F_NOLOCK)) {
4940 root_lock = qdisc_lock(q);
4941 spin_lock(root_lock);
4942 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
4943 &q->state))) {
4944 /* There is a synchronize_net() between
4945 * STATE_DEACTIVATED flag being set and
4946 * qdisc_reset()/some_qdisc_is_busy() in
4947 * dev_deactivate(), so we can safely bail out
4948 * early here to avoid data race between
4949 * qdisc_deactivate() and some_qdisc_is_busy()
4950 * for lockless qdisc.
4951 */
4952 clear_bit(__QDISC_STATE_SCHED, &q->state);
4953 continue;
4954 }
4955
4956 clear_bit(__QDISC_STATE_SCHED, &q->state);
4957 qdisc_run(q);
4958 if (root_lock)
4959 spin_unlock(root_lock);
4960 }
4961
4962 rcu_read_unlock();
4963 }
4964
4965 xfrm_dev_backlog(sd);
4966 }
4967
4968 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
4969 /* This hook is defined here for ATM LANE */
4970 int (*br_fdb_test_addr_hook)(struct net_device *dev,
4971 unsigned char *addr) __read_mostly;
4972 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
4973 #endif
4974
4975 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)4976 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4977 struct net_device *orig_dev, bool *another)
4978 {
4979 #ifdef CONFIG_NET_CLS_ACT
4980 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
4981 struct tcf_result cl_res;
4982
4983 /* If there's at least one ingress present somewhere (so
4984 * we get here via enabled static key), remaining devices
4985 * that are not configured with an ingress qdisc will bail
4986 * out here.
4987 */
4988 if (!miniq)
4989 return skb;
4990
4991 if (*pt_prev) {
4992 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4993 *pt_prev = NULL;
4994 }
4995
4996 qdisc_skb_cb(skb)->pkt_len = skb->len;
4997 qdisc_skb_cb(skb)->mru = 0;
4998 skb->tc_at_ingress = 1;
4999 mini_qdisc_bstats_cpu_update(miniq, skb);
5000
5001 switch (tcf_classify_ingress(skb, miniq->block, miniq->filter_list,
5002 &cl_res, false)) {
5003 case TC_ACT_OK:
5004 case TC_ACT_RECLASSIFY:
5005 skb->tc_index = TC_H_MIN(cl_res.classid);
5006 break;
5007 case TC_ACT_SHOT:
5008 mini_qdisc_qstats_cpu_drop(miniq);
5009 kfree_skb(skb);
5010 return NULL;
5011 case TC_ACT_STOLEN:
5012 case TC_ACT_QUEUED:
5013 case TC_ACT_TRAP:
5014 consume_skb(skb);
5015 return NULL;
5016 case TC_ACT_REDIRECT:
5017 /* skb_mac_header check was done by cls/act_bpf, so
5018 * we can safely push the L2 header back before
5019 * redirecting to another netdev
5020 */
5021 __skb_push(skb, skb->mac_len);
5022 if (skb_do_redirect(skb) == -EAGAIN) {
5023 __skb_pull(skb, skb->mac_len);
5024 *another = true;
5025 break;
5026 }
5027 return NULL;
5028 case TC_ACT_CONSUMED:
5029 return NULL;
5030 default:
5031 break;
5032 }
5033 #endif /* CONFIG_NET_CLS_ACT */
5034 return skb;
5035 }
5036
5037 /**
5038 * netdev_is_rx_handler_busy - check if receive handler is registered
5039 * @dev: device to check
5040 *
5041 * Check if a receive handler is already registered for a given device.
5042 * Return true if there one.
5043 *
5044 * The caller must hold the rtnl_mutex.
5045 */
netdev_is_rx_handler_busy(struct net_device * dev)5046 bool netdev_is_rx_handler_busy(struct net_device *dev)
5047 {
5048 ASSERT_RTNL();
5049 return dev && rtnl_dereference(dev->rx_handler);
5050 }
5051 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5052
5053 /**
5054 * netdev_rx_handler_register - register receive handler
5055 * @dev: device to register a handler for
5056 * @rx_handler: receive handler to register
5057 * @rx_handler_data: data pointer that is used by rx handler
5058 *
5059 * Register a receive handler for a device. This handler will then be
5060 * called from __netif_receive_skb. A negative errno code is returned
5061 * on a failure.
5062 *
5063 * The caller must hold the rtnl_mutex.
5064 *
5065 * For a general description of rx_handler, see enum rx_handler_result.
5066 */
netdev_rx_handler_register(struct net_device * dev,rx_handler_func_t * rx_handler,void * rx_handler_data)5067 int netdev_rx_handler_register(struct net_device *dev,
5068 rx_handler_func_t *rx_handler,
5069 void *rx_handler_data)
5070 {
5071 if (netdev_is_rx_handler_busy(dev))
5072 return -EBUSY;
5073
5074 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5075 return -EINVAL;
5076
5077 /* Note: rx_handler_data must be set before rx_handler */
5078 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5079 rcu_assign_pointer(dev->rx_handler, rx_handler);
5080
5081 return 0;
5082 }
5083 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5084
5085 /**
5086 * netdev_rx_handler_unregister - unregister receive handler
5087 * @dev: device to unregister a handler from
5088 *
5089 * Unregister a receive handler from a device.
5090 *
5091 * The caller must hold the rtnl_mutex.
5092 */
netdev_rx_handler_unregister(struct net_device * dev)5093 void netdev_rx_handler_unregister(struct net_device *dev)
5094 {
5095
5096 ASSERT_RTNL();
5097 RCU_INIT_POINTER(dev->rx_handler, NULL);
5098 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5099 * section has a guarantee to see a non NULL rx_handler_data
5100 * as well.
5101 */
5102 synchronize_net();
5103 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5104 }
5105 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5106
5107 /*
5108 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5109 * the special handling of PFMEMALLOC skbs.
5110 */
skb_pfmemalloc_protocol(struct sk_buff * skb)5111 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5112 {
5113 switch (skb->protocol) {
5114 case htons(ETH_P_ARP):
5115 case htons(ETH_P_IP):
5116 case htons(ETH_P_IPV6):
5117 case htons(ETH_P_8021Q):
5118 case htons(ETH_P_8021AD):
5119 return true;
5120 default:
5121 return false;
5122 }
5123 }
5124
nf_ingress(struct sk_buff * skb,struct packet_type ** pt_prev,int * ret,struct net_device * orig_dev)5125 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5126 int *ret, struct net_device *orig_dev)
5127 {
5128 if (nf_hook_ingress_active(skb)) {
5129 int ingress_retval;
5130
5131 if (*pt_prev) {
5132 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5133 *pt_prev = NULL;
5134 }
5135
5136 rcu_read_lock();
5137 ingress_retval = nf_hook_ingress(skb);
5138 rcu_read_unlock();
5139 return ingress_retval;
5140 }
5141 return 0;
5142 }
5143
__netif_receive_skb_core(struct sk_buff ** pskb,bool pfmemalloc,struct packet_type ** ppt_prev)5144 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5145 struct packet_type **ppt_prev)
5146 {
5147 struct packet_type *ptype, *pt_prev;
5148 rx_handler_func_t *rx_handler;
5149 struct sk_buff *skb = *pskb;
5150 struct net_device *orig_dev;
5151 bool deliver_exact = false;
5152 int ret = NET_RX_DROP;
5153 __be16 type;
5154
5155 net_timestamp_check(!netdev_tstamp_prequeue, skb);
5156
5157 trace_netif_receive_skb(skb);
5158
5159 orig_dev = skb->dev;
5160
5161 skb_reset_network_header(skb);
5162 if (!skb_transport_header_was_set(skb))
5163 skb_reset_transport_header(skb);
5164 skb_reset_mac_len(skb);
5165
5166 pt_prev = NULL;
5167
5168 another_round:
5169 skb->skb_iif = skb->dev->ifindex;
5170
5171 __this_cpu_inc(softnet_data.processed);
5172
5173 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5174 int ret2;
5175
5176 preempt_disable();
5177 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5178 preempt_enable();
5179
5180 if (ret2 != XDP_PASS) {
5181 ret = NET_RX_DROP;
5182 goto out;
5183 }
5184 skb_reset_mac_len(skb);
5185 }
5186
5187 if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5188 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5189 skb = skb_vlan_untag(skb);
5190 if (unlikely(!skb))
5191 goto out;
5192 }
5193
5194 if (skb_skip_tc_classify(skb))
5195 goto skip_classify;
5196
5197 if (pfmemalloc)
5198 goto skip_taps;
5199
5200 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5201 if (pt_prev)
5202 ret = deliver_skb(skb, pt_prev, orig_dev);
5203 pt_prev = ptype;
5204 }
5205
5206 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5207 if (pt_prev)
5208 ret = deliver_skb(skb, pt_prev, orig_dev);
5209 pt_prev = ptype;
5210 }
5211
5212 skip_taps:
5213 #ifdef CONFIG_NET_INGRESS
5214 if (static_branch_unlikely(&ingress_needed_key)) {
5215 bool another = false;
5216
5217 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5218 &another);
5219 if (another)
5220 goto another_round;
5221 if (!skb)
5222 goto out;
5223
5224 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5225 goto out;
5226 }
5227 #endif
5228 skb_reset_redirect(skb);
5229 skip_classify:
5230 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5231 goto drop;
5232
5233 if (skb_vlan_tag_present(skb)) {
5234 if (pt_prev) {
5235 ret = deliver_skb(skb, pt_prev, orig_dev);
5236 pt_prev = NULL;
5237 }
5238 if (vlan_do_receive(&skb))
5239 goto another_round;
5240 else if (unlikely(!skb))
5241 goto out;
5242 }
5243
5244 rx_handler = rcu_dereference(skb->dev->rx_handler);
5245 if (rx_handler) {
5246 if (pt_prev) {
5247 ret = deliver_skb(skb, pt_prev, orig_dev);
5248 pt_prev = NULL;
5249 }
5250 switch (rx_handler(&skb)) {
5251 case RX_HANDLER_CONSUMED:
5252 ret = NET_RX_SUCCESS;
5253 goto out;
5254 case RX_HANDLER_ANOTHER:
5255 goto another_round;
5256 case RX_HANDLER_EXACT:
5257 deliver_exact = true;
5258 case RX_HANDLER_PASS:
5259 break;
5260 default:
5261 BUG();
5262 }
5263 }
5264
5265 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5266 check_vlan_id:
5267 if (skb_vlan_tag_get_id(skb)) {
5268 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5269 * find vlan device.
5270 */
5271 skb->pkt_type = PACKET_OTHERHOST;
5272 } else if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5273 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5274 /* Outer header is 802.1P with vlan 0, inner header is
5275 * 802.1Q or 802.1AD and vlan_do_receive() above could
5276 * not find vlan dev for vlan id 0.
5277 */
5278 __vlan_hwaccel_clear_tag(skb);
5279 skb = skb_vlan_untag(skb);
5280 if (unlikely(!skb))
5281 goto out;
5282 if (vlan_do_receive(&skb))
5283 /* After stripping off 802.1P header with vlan 0
5284 * vlan dev is found for inner header.
5285 */
5286 goto another_round;
5287 else if (unlikely(!skb))
5288 goto out;
5289 else
5290 /* We have stripped outer 802.1P vlan 0 header.
5291 * But could not find vlan dev.
5292 * check again for vlan id to set OTHERHOST.
5293 */
5294 goto check_vlan_id;
5295 }
5296 /* Note: we might in the future use prio bits
5297 * and set skb->priority like in vlan_do_receive()
5298 * For the time being, just ignore Priority Code Point
5299 */
5300 __vlan_hwaccel_clear_tag(skb);
5301 }
5302
5303 type = skb->protocol;
5304
5305 /* deliver only exact match when indicated */
5306 if (likely(!deliver_exact)) {
5307 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5308 &ptype_base[ntohs(type) &
5309 PTYPE_HASH_MASK]);
5310 }
5311
5312 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5313 &orig_dev->ptype_specific);
5314
5315 if (unlikely(skb->dev != orig_dev)) {
5316 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5317 &skb->dev->ptype_specific);
5318 }
5319
5320 if (pt_prev) {
5321 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5322 goto drop;
5323 *ppt_prev = pt_prev;
5324 } else {
5325 drop:
5326 if (!deliver_exact)
5327 atomic_long_inc(&skb->dev->rx_dropped);
5328 else
5329 atomic_long_inc(&skb->dev->rx_nohandler);
5330 kfree_skb(skb);
5331 /* Jamal, now you will not able to escape explaining
5332 * me how you were going to use this. :-)
5333 */
5334 ret = NET_RX_DROP;
5335 }
5336
5337 out:
5338 /* The invariant here is that if *ppt_prev is not NULL
5339 * then skb should also be non-NULL.
5340 *
5341 * Apparently *ppt_prev assignment above holds this invariant due to
5342 * skb dereferencing near it.
5343 */
5344 *pskb = skb;
5345 return ret;
5346 }
5347
__netif_receive_skb_one_core(struct sk_buff * skb,bool pfmemalloc)5348 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5349 {
5350 struct net_device *orig_dev = skb->dev;
5351 struct packet_type *pt_prev = NULL;
5352 int ret;
5353
5354 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5355 if (pt_prev)
5356 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5357 skb->dev, pt_prev, orig_dev);
5358 return ret;
5359 }
5360
5361 /**
5362 * netif_receive_skb_core - special purpose version of netif_receive_skb
5363 * @skb: buffer to process
5364 *
5365 * More direct receive version of netif_receive_skb(). It should
5366 * only be used by callers that have a need to skip RPS and Generic XDP.
5367 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5368 *
5369 * This function may only be called from softirq context and interrupts
5370 * should be enabled.
5371 *
5372 * Return values (usually ignored):
5373 * NET_RX_SUCCESS: no congestion
5374 * NET_RX_DROP: packet was dropped
5375 */
netif_receive_skb_core(struct sk_buff * skb)5376 int netif_receive_skb_core(struct sk_buff *skb)
5377 {
5378 int ret;
5379
5380 rcu_read_lock();
5381 ret = __netif_receive_skb_one_core(skb, false);
5382 rcu_read_unlock();
5383
5384 return ret;
5385 }
5386 EXPORT_SYMBOL(netif_receive_skb_core);
5387
__netif_receive_skb_list_ptype(struct list_head * head,struct packet_type * pt_prev,struct net_device * orig_dev)5388 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5389 struct packet_type *pt_prev,
5390 struct net_device *orig_dev)
5391 {
5392 struct sk_buff *skb, *next;
5393
5394 if (!pt_prev)
5395 return;
5396 if (list_empty(head))
5397 return;
5398 if (pt_prev->list_func != NULL)
5399 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5400 ip_list_rcv, head, pt_prev, orig_dev);
5401 else
5402 list_for_each_entry_safe(skb, next, head, list) {
5403 skb_list_del_init(skb);
5404 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5405 }
5406 }
5407
__netif_receive_skb_list_core(struct list_head * head,bool pfmemalloc)5408 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5409 {
5410 /* Fast-path assumptions:
5411 * - There is no RX handler.
5412 * - Only one packet_type matches.
5413 * If either of these fails, we will end up doing some per-packet
5414 * processing in-line, then handling the 'last ptype' for the whole
5415 * sublist. This can't cause out-of-order delivery to any single ptype,
5416 * because the 'last ptype' must be constant across the sublist, and all
5417 * other ptypes are handled per-packet.
5418 */
5419 /* Current (common) ptype of sublist */
5420 struct packet_type *pt_curr = NULL;
5421 /* Current (common) orig_dev of sublist */
5422 struct net_device *od_curr = NULL;
5423 struct list_head sublist;
5424 struct sk_buff *skb, *next;
5425
5426 INIT_LIST_HEAD(&sublist);
5427 list_for_each_entry_safe(skb, next, head, list) {
5428 struct net_device *orig_dev = skb->dev;
5429 struct packet_type *pt_prev = NULL;
5430
5431 skb_list_del_init(skb);
5432 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5433 if (!pt_prev)
5434 continue;
5435 if (pt_curr != pt_prev || od_curr != orig_dev) {
5436 /* dispatch old sublist */
5437 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5438 /* start new sublist */
5439 INIT_LIST_HEAD(&sublist);
5440 pt_curr = pt_prev;
5441 od_curr = orig_dev;
5442 }
5443 list_add_tail(&skb->list, &sublist);
5444 }
5445
5446 /* dispatch final sublist */
5447 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5448 }
5449
__netif_receive_skb(struct sk_buff * skb)5450 static int __netif_receive_skb(struct sk_buff *skb)
5451 {
5452 int ret;
5453
5454 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5455 unsigned int noreclaim_flag;
5456
5457 /*
5458 * PFMEMALLOC skbs are special, they should
5459 * - be delivered to SOCK_MEMALLOC sockets only
5460 * - stay away from userspace
5461 * - have bounded memory usage
5462 *
5463 * Use PF_MEMALLOC as this saves us from propagating the allocation
5464 * context down to all allocation sites.
5465 */
5466 noreclaim_flag = memalloc_noreclaim_save();
5467 ret = __netif_receive_skb_one_core(skb, true);
5468 memalloc_noreclaim_restore(noreclaim_flag);
5469 } else
5470 ret = __netif_receive_skb_one_core(skb, false);
5471
5472 return ret;
5473 }
5474
__netif_receive_skb_list(struct list_head * head)5475 static void __netif_receive_skb_list(struct list_head *head)
5476 {
5477 unsigned long noreclaim_flag = 0;
5478 struct sk_buff *skb, *next;
5479 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5480
5481 list_for_each_entry_safe(skb, next, head, list) {
5482 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5483 struct list_head sublist;
5484
5485 /* Handle the previous sublist */
5486 list_cut_before(&sublist, head, &skb->list);
5487 if (!list_empty(&sublist))
5488 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5489 pfmemalloc = !pfmemalloc;
5490 /* See comments in __netif_receive_skb */
5491 if (pfmemalloc)
5492 noreclaim_flag = memalloc_noreclaim_save();
5493 else
5494 memalloc_noreclaim_restore(noreclaim_flag);
5495 }
5496 }
5497 /* Handle the remaining sublist */
5498 if (!list_empty(head))
5499 __netif_receive_skb_list_core(head, pfmemalloc);
5500 /* Restore pflags */
5501 if (pfmemalloc)
5502 memalloc_noreclaim_restore(noreclaim_flag);
5503 }
5504
generic_xdp_install(struct net_device * dev,struct netdev_bpf * xdp)5505 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5506 {
5507 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5508 struct bpf_prog *new = xdp->prog;
5509 int ret = 0;
5510
5511 if (new) {
5512 u32 i;
5513
5514 mutex_lock(&new->aux->used_maps_mutex);
5515
5516 /* generic XDP does not work with DEVMAPs that can
5517 * have a bpf_prog installed on an entry
5518 */
5519 for (i = 0; i < new->aux->used_map_cnt; i++) {
5520 if (dev_map_can_have_prog(new->aux->used_maps[i]) ||
5521 cpu_map_prog_allowed(new->aux->used_maps[i])) {
5522 mutex_unlock(&new->aux->used_maps_mutex);
5523 return -EINVAL;
5524 }
5525 }
5526
5527 mutex_unlock(&new->aux->used_maps_mutex);
5528 }
5529
5530 switch (xdp->command) {
5531 case XDP_SETUP_PROG:
5532 rcu_assign_pointer(dev->xdp_prog, new);
5533 if (old)
5534 bpf_prog_put(old);
5535
5536 if (old && !new) {
5537 static_branch_dec(&generic_xdp_needed_key);
5538 } else if (new && !old) {
5539 static_branch_inc(&generic_xdp_needed_key);
5540 dev_disable_lro(dev);
5541 dev_disable_gro_hw(dev);
5542 }
5543 break;
5544
5545 default:
5546 ret = -EINVAL;
5547 break;
5548 }
5549
5550 return ret;
5551 }
5552
netif_receive_skb_internal(struct sk_buff * skb)5553 static int netif_receive_skb_internal(struct sk_buff *skb)
5554 {
5555 int ret;
5556
5557 net_timestamp_check(netdev_tstamp_prequeue, skb);
5558
5559 if (skb_defer_rx_timestamp(skb))
5560 return NET_RX_SUCCESS;
5561
5562 rcu_read_lock();
5563 #ifdef CONFIG_RPS
5564 if (static_branch_unlikely(&rps_needed)) {
5565 struct rps_dev_flow voidflow, *rflow = &voidflow;
5566 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5567
5568 if (cpu >= 0) {
5569 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5570 rcu_read_unlock();
5571 return ret;
5572 }
5573 }
5574 #endif
5575 ret = __netif_receive_skb(skb);
5576 rcu_read_unlock();
5577 return ret;
5578 }
5579
netif_receive_skb_list_internal(struct list_head * head)5580 static void netif_receive_skb_list_internal(struct list_head *head)
5581 {
5582 struct sk_buff *skb, *next;
5583 struct list_head sublist;
5584
5585 INIT_LIST_HEAD(&sublist);
5586 list_for_each_entry_safe(skb, next, head, list) {
5587 net_timestamp_check(netdev_tstamp_prequeue, skb);
5588 skb_list_del_init(skb);
5589 if (!skb_defer_rx_timestamp(skb))
5590 list_add_tail(&skb->list, &sublist);
5591 }
5592 list_splice_init(&sublist, head);
5593
5594 rcu_read_lock();
5595 #ifdef CONFIG_RPS
5596 if (static_branch_unlikely(&rps_needed)) {
5597 list_for_each_entry_safe(skb, next, head, list) {
5598 struct rps_dev_flow voidflow, *rflow = &voidflow;
5599 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5600
5601 if (cpu >= 0) {
5602 /* Will be handled, remove from list */
5603 skb_list_del_init(skb);
5604 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5605 }
5606 }
5607 }
5608 #endif
5609 __netif_receive_skb_list(head);
5610 rcu_read_unlock();
5611 }
5612
5613 /**
5614 * netif_receive_skb - process receive buffer from network
5615 * @skb: buffer to process
5616 *
5617 * netif_receive_skb() is the main receive data processing function.
5618 * It always succeeds. The buffer may be dropped during processing
5619 * for congestion control or by the protocol layers.
5620 *
5621 * This function may only be called from softirq context and interrupts
5622 * should be enabled.
5623 *
5624 * Return values (usually ignored):
5625 * NET_RX_SUCCESS: no congestion
5626 * NET_RX_DROP: packet was dropped
5627 */
netif_receive_skb(struct sk_buff * skb)5628 int netif_receive_skb(struct sk_buff *skb)
5629 {
5630 int ret;
5631
5632 trace_netif_receive_skb_entry(skb);
5633
5634 ret = netif_receive_skb_internal(skb);
5635 trace_netif_receive_skb_exit(ret);
5636
5637 return ret;
5638 }
5639 EXPORT_SYMBOL(netif_receive_skb);
5640
5641 /**
5642 * netif_receive_skb_list - process many receive buffers from network
5643 * @head: list of skbs to process.
5644 *
5645 * Since return value of netif_receive_skb() is normally ignored, and
5646 * wouldn't be meaningful for a list, this function returns void.
5647 *
5648 * This function may only be called from softirq context and interrupts
5649 * should be enabled.
5650 */
netif_receive_skb_list(struct list_head * head)5651 void netif_receive_skb_list(struct list_head *head)
5652 {
5653 struct sk_buff *skb;
5654
5655 if (list_empty(head))
5656 return;
5657 if (trace_netif_receive_skb_list_entry_enabled()) {
5658 list_for_each_entry(skb, head, list)
5659 trace_netif_receive_skb_list_entry(skb);
5660 }
5661 netif_receive_skb_list_internal(head);
5662 trace_netif_receive_skb_list_exit(0);
5663 }
5664 EXPORT_SYMBOL(netif_receive_skb_list);
5665
5666 static DEFINE_PER_CPU(struct work_struct, flush_works);
5667
5668 /* Network device is going away, flush any packets still pending */
flush_backlog(struct work_struct * work)5669 static void flush_backlog(struct work_struct *work)
5670 {
5671 struct sk_buff *skb, *tmp;
5672 struct softnet_data *sd;
5673
5674 local_bh_disable();
5675 sd = this_cpu_ptr(&softnet_data);
5676
5677 local_irq_disable();
5678 rps_lock(sd);
5679 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5680 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5681 __skb_unlink(skb, &sd->input_pkt_queue);
5682 dev_kfree_skb_irq(skb);
5683 input_queue_head_incr(sd);
5684 }
5685 }
5686 rps_unlock(sd);
5687 local_irq_enable();
5688
5689 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5690 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5691 __skb_unlink(skb, &sd->process_queue);
5692 kfree_skb(skb);
5693 input_queue_head_incr(sd);
5694 }
5695 }
5696 local_bh_enable();
5697 }
5698
flush_required(int cpu)5699 static bool flush_required(int cpu)
5700 {
5701 #if IS_ENABLED(CONFIG_RPS)
5702 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5703 bool do_flush;
5704
5705 local_irq_disable();
5706 rps_lock(sd);
5707
5708 /* as insertion into process_queue happens with the rps lock held,
5709 * process_queue access may race only with dequeue
5710 */
5711 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5712 !skb_queue_empty_lockless(&sd->process_queue);
5713 rps_unlock(sd);
5714 local_irq_enable();
5715
5716 return do_flush;
5717 #endif
5718 /* without RPS we can't safely check input_pkt_queue: during a
5719 * concurrent remote skb_queue_splice() we can detect as empty both
5720 * input_pkt_queue and process_queue even if the latter could end-up
5721 * containing a lot of packets.
5722 */
5723 return true;
5724 }
5725
flush_all_backlogs(void)5726 static void flush_all_backlogs(void)
5727 {
5728 static cpumask_t flush_cpus;
5729 unsigned int cpu;
5730
5731 /* since we are under rtnl lock protection we can use static data
5732 * for the cpumask and avoid allocating on stack the possibly
5733 * large mask
5734 */
5735 ASSERT_RTNL();
5736
5737 get_online_cpus();
5738
5739 cpumask_clear(&flush_cpus);
5740 for_each_online_cpu(cpu) {
5741 if (flush_required(cpu)) {
5742 queue_work_on(cpu, system_highpri_wq,
5743 per_cpu_ptr(&flush_works, cpu));
5744 cpumask_set_cpu(cpu, &flush_cpus);
5745 }
5746 }
5747
5748 /* we can have in flight packet[s] on the cpus we are not flushing,
5749 * synchronize_net() in rollback_registered_many() will take care of
5750 * them
5751 */
5752 for_each_cpu(cpu, &flush_cpus)
5753 flush_work(per_cpu_ptr(&flush_works, cpu));
5754
5755 put_online_cpus();
5756 }
5757
5758 /* Pass the currently batched GRO_NORMAL SKBs up to the stack. */
gro_normal_list(struct napi_struct * napi)5759 static void gro_normal_list(struct napi_struct *napi)
5760 {
5761 if (!napi->rx_count)
5762 return;
5763 netif_receive_skb_list_internal(&napi->rx_list);
5764 INIT_LIST_HEAD(&napi->rx_list);
5765 napi->rx_count = 0;
5766 }
5767
5768 /* Queue one GRO_NORMAL SKB up for list processing. If batch size exceeded,
5769 * pass the whole batch up to the stack.
5770 */
gro_normal_one(struct napi_struct * napi,struct sk_buff * skb,int segs)5771 static void gro_normal_one(struct napi_struct *napi, struct sk_buff *skb, int segs)
5772 {
5773 list_add_tail(&skb->list, &napi->rx_list);
5774 napi->rx_count += segs;
5775 if (napi->rx_count >= gro_normal_batch)
5776 gro_normal_list(napi);
5777 }
5778
5779 INDIRECT_CALLABLE_DECLARE(int inet_gro_complete(struct sk_buff *, int));
5780 INDIRECT_CALLABLE_DECLARE(int ipv6_gro_complete(struct sk_buff *, int));
napi_gro_complete(struct napi_struct * napi,struct sk_buff * skb)5781 static int napi_gro_complete(struct napi_struct *napi, struct sk_buff *skb)
5782 {
5783 struct packet_offload *ptype;
5784 __be16 type = skb->protocol;
5785 struct list_head *head = &offload_base;
5786 int err = -ENOENT;
5787
5788 BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
5789
5790 if (NAPI_GRO_CB(skb)->count == 1) {
5791 skb_shinfo(skb)->gso_size = 0;
5792 goto out;
5793 }
5794
5795 rcu_read_lock();
5796 list_for_each_entry_rcu(ptype, head, list) {
5797 if (ptype->type != type || !ptype->callbacks.gro_complete)
5798 continue;
5799
5800 err = INDIRECT_CALL_INET(ptype->callbacks.gro_complete,
5801 ipv6_gro_complete, inet_gro_complete,
5802 skb, 0);
5803 break;
5804 }
5805 rcu_read_unlock();
5806
5807 if (err) {
5808 WARN_ON(&ptype->list == head);
5809 kfree_skb(skb);
5810 return NET_RX_SUCCESS;
5811 }
5812
5813 out:
5814 gro_normal_one(napi, skb, NAPI_GRO_CB(skb)->count);
5815 return NET_RX_SUCCESS;
5816 }
5817
__napi_gro_flush_chain(struct napi_struct * napi,u32 index,bool flush_old)5818 static void __napi_gro_flush_chain(struct napi_struct *napi, u32 index,
5819 bool flush_old)
5820 {
5821 struct list_head *head = &napi->gro_hash[index].list;
5822 struct sk_buff *skb, *p;
5823
5824 list_for_each_entry_safe_reverse(skb, p, head, list) {
5825 if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
5826 return;
5827 skb_list_del_init(skb);
5828 napi_gro_complete(napi, skb);
5829 napi->gro_hash[index].count--;
5830 }
5831
5832 if (!napi->gro_hash[index].count)
5833 __clear_bit(index, &napi->gro_bitmask);
5834 }
5835
5836 /* napi->gro_hash[].list contains packets ordered by age.
5837 * youngest packets at the head of it.
5838 * Complete skbs in reverse order to reduce latencies.
5839 */
napi_gro_flush(struct napi_struct * napi,bool flush_old)5840 void napi_gro_flush(struct napi_struct *napi, bool flush_old)
5841 {
5842 unsigned long bitmask = napi->gro_bitmask;
5843 unsigned int i, base = ~0U;
5844
5845 while ((i = ffs(bitmask)) != 0) {
5846 bitmask >>= i;
5847 base += i;
5848 __napi_gro_flush_chain(napi, base, flush_old);
5849 }
5850 }
5851 EXPORT_SYMBOL(napi_gro_flush);
5852
gro_list_prepare(struct napi_struct * napi,struct sk_buff * skb)5853 static struct list_head *gro_list_prepare(struct napi_struct *napi,
5854 struct sk_buff *skb)
5855 {
5856 unsigned int maclen = skb->dev->hard_header_len;
5857 u32 hash = skb_get_hash_raw(skb);
5858 struct list_head *head;
5859 struct sk_buff *p;
5860
5861 head = &napi->gro_hash[hash & (GRO_HASH_BUCKETS - 1)].list;
5862 list_for_each_entry(p, head, list) {
5863 unsigned long diffs;
5864
5865 NAPI_GRO_CB(p)->flush = 0;
5866
5867 if (hash != skb_get_hash_raw(p)) {
5868 NAPI_GRO_CB(p)->same_flow = 0;
5869 continue;
5870 }
5871
5872 diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
5873 diffs |= skb_vlan_tag_present(p) ^ skb_vlan_tag_present(skb);
5874 if (skb_vlan_tag_present(p))
5875 diffs |= skb_vlan_tag_get(p) ^ skb_vlan_tag_get(skb);
5876 diffs |= skb_metadata_dst_cmp(p, skb);
5877 diffs |= skb_metadata_differs(p, skb);
5878 if (maclen == ETH_HLEN)
5879 diffs |= compare_ether_header(skb_mac_header(p),
5880 skb_mac_header(skb));
5881 else if (!diffs)
5882 diffs = memcmp(skb_mac_header(p),
5883 skb_mac_header(skb),
5884 maclen);
5885
5886 diffs |= skb_get_nfct(p) ^ skb_get_nfct(skb);
5887 #if IS_ENABLED(CONFIG_SKB_EXTENSIONS) && IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
5888 if (!diffs) {
5889 struct tc_skb_ext *skb_ext = skb_ext_find(skb, TC_SKB_EXT);
5890 struct tc_skb_ext *p_ext = skb_ext_find(p, TC_SKB_EXT);
5891
5892 diffs |= (!!p_ext) ^ (!!skb_ext);
5893 if (!diffs && unlikely(skb_ext))
5894 diffs |= p_ext->chain ^ skb_ext->chain;
5895 }
5896 #endif
5897
5898 NAPI_GRO_CB(p)->same_flow = !diffs;
5899 }
5900
5901 return head;
5902 }
5903
skb_gro_reset_offset(struct sk_buff * skb,u32 nhoff)5904 static inline void skb_gro_reset_offset(struct sk_buff *skb, u32 nhoff)
5905 {
5906 const struct skb_shared_info *pinfo = skb_shinfo(skb);
5907 const skb_frag_t *frag0 = &pinfo->frags[0];
5908
5909 NAPI_GRO_CB(skb)->data_offset = 0;
5910 NAPI_GRO_CB(skb)->frag0 = NULL;
5911 NAPI_GRO_CB(skb)->frag0_len = 0;
5912
5913 if (!skb_headlen(skb) && pinfo->nr_frags &&
5914 !PageHighMem(skb_frag_page(frag0)) &&
5915 (!NET_IP_ALIGN || !((skb_frag_off(frag0) + nhoff) & 3))) {
5916 NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
5917 NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
5918 skb_frag_size(frag0),
5919 skb->end - skb->tail);
5920 }
5921 }
5922
gro_pull_from_frag0(struct sk_buff * skb,int grow)5923 static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
5924 {
5925 struct skb_shared_info *pinfo = skb_shinfo(skb);
5926
5927 BUG_ON(skb->end - skb->tail < grow);
5928
5929 memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
5930
5931 skb->data_len -= grow;
5932 skb->tail += grow;
5933
5934 skb_frag_off_add(&pinfo->frags[0], grow);
5935 skb_frag_size_sub(&pinfo->frags[0], grow);
5936
5937 if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
5938 skb_frag_unref(skb, 0);
5939 memmove(pinfo->frags, pinfo->frags + 1,
5940 --pinfo->nr_frags * sizeof(pinfo->frags[0]));
5941 }
5942 }
5943
gro_flush_oldest(struct napi_struct * napi,struct list_head * head)5944 static void gro_flush_oldest(struct napi_struct *napi, struct list_head *head)
5945 {
5946 struct sk_buff *oldest;
5947
5948 oldest = list_last_entry(head, struct sk_buff, list);
5949
5950 /* We are called with head length >= MAX_GRO_SKBS, so this is
5951 * impossible.
5952 */
5953 if (WARN_ON_ONCE(!oldest))
5954 return;
5955
5956 /* Do not adjust napi->gro_hash[].count, caller is adding a new
5957 * SKB to the chain.
5958 */
5959 skb_list_del_init(oldest);
5960 napi_gro_complete(napi, oldest);
5961 }
5962
5963 INDIRECT_CALLABLE_DECLARE(struct sk_buff *inet_gro_receive(struct list_head *,
5964 struct sk_buff *));
5965 INDIRECT_CALLABLE_DECLARE(struct sk_buff *ipv6_gro_receive(struct list_head *,
5966 struct sk_buff *));
dev_gro_receive(struct napi_struct * napi,struct sk_buff * skb)5967 static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5968 {
5969 u32 hash = skb_get_hash_raw(skb) & (GRO_HASH_BUCKETS - 1);
5970 struct list_head *head = &offload_base;
5971 struct packet_offload *ptype;
5972 __be16 type = skb->protocol;
5973 struct list_head *gro_head;
5974 struct sk_buff *pp = NULL;
5975 enum gro_result ret;
5976 int same_flow;
5977 int grow;
5978
5979 if (netif_elide_gro(skb->dev))
5980 goto normal;
5981
5982 gro_head = gro_list_prepare(napi, skb);
5983
5984 rcu_read_lock();
5985 list_for_each_entry_rcu(ptype, head, list) {
5986 if (ptype->type != type || !ptype->callbacks.gro_receive)
5987 continue;
5988
5989 skb_set_network_header(skb, skb_gro_offset(skb));
5990 skb_reset_mac_len(skb);
5991 NAPI_GRO_CB(skb)->same_flow = 0;
5992 NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
5993 NAPI_GRO_CB(skb)->free = 0;
5994 NAPI_GRO_CB(skb)->encap_mark = 0;
5995 NAPI_GRO_CB(skb)->recursion_counter = 0;
5996 NAPI_GRO_CB(skb)->is_fou = 0;
5997 NAPI_GRO_CB(skb)->is_atomic = 1;
5998 NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
5999
6000 /* Setup for GRO checksum validation */
6001 switch (skb->ip_summed) {
6002 case CHECKSUM_COMPLETE:
6003 NAPI_GRO_CB(skb)->csum = skb->csum;
6004 NAPI_GRO_CB(skb)->csum_valid = 1;
6005 NAPI_GRO_CB(skb)->csum_cnt = 0;
6006 break;
6007 case CHECKSUM_UNNECESSARY:
6008 NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
6009 NAPI_GRO_CB(skb)->csum_valid = 0;
6010 break;
6011 default:
6012 NAPI_GRO_CB(skb)->csum_cnt = 0;
6013 NAPI_GRO_CB(skb)->csum_valid = 0;
6014 }
6015
6016 pp = INDIRECT_CALL_INET(ptype->callbacks.gro_receive,
6017 ipv6_gro_receive, inet_gro_receive,
6018 gro_head, skb);
6019 break;
6020 }
6021 rcu_read_unlock();
6022
6023 if (&ptype->list == head)
6024 goto normal;
6025
6026 if (PTR_ERR(pp) == -EINPROGRESS) {
6027 ret = GRO_CONSUMED;
6028 goto ok;
6029 }
6030
6031 same_flow = NAPI_GRO_CB(skb)->same_flow;
6032 ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
6033
6034 if (pp) {
6035 skb_list_del_init(pp);
6036 napi_gro_complete(napi, pp);
6037 napi->gro_hash[hash].count--;
6038 }
6039
6040 if (same_flow)
6041 goto ok;
6042
6043 if (NAPI_GRO_CB(skb)->flush)
6044 goto normal;
6045
6046 if (unlikely(napi->gro_hash[hash].count >= MAX_GRO_SKBS)) {
6047 gro_flush_oldest(napi, gro_head);
6048 } else {
6049 napi->gro_hash[hash].count++;
6050 }
6051 NAPI_GRO_CB(skb)->count = 1;
6052 NAPI_GRO_CB(skb)->age = jiffies;
6053 NAPI_GRO_CB(skb)->last = skb;
6054 skb_shinfo(skb)->gso_size = skb_gro_len(skb);
6055 list_add(&skb->list, gro_head);
6056 ret = GRO_HELD;
6057
6058 pull:
6059 grow = skb_gro_offset(skb) - skb_headlen(skb);
6060 if (grow > 0)
6061 gro_pull_from_frag0(skb, grow);
6062 ok:
6063 if (napi->gro_hash[hash].count) {
6064 if (!test_bit(hash, &napi->gro_bitmask))
6065 __set_bit(hash, &napi->gro_bitmask);
6066 } else if (test_bit(hash, &napi->gro_bitmask)) {
6067 __clear_bit(hash, &napi->gro_bitmask);
6068 }
6069
6070 return ret;
6071
6072 normal:
6073 ret = GRO_NORMAL;
6074 goto pull;
6075 }
6076
gro_find_receive_by_type(__be16 type)6077 struct packet_offload *gro_find_receive_by_type(__be16 type)
6078 {
6079 struct list_head *offload_head = &offload_base;
6080 struct packet_offload *ptype;
6081
6082 list_for_each_entry_rcu(ptype, offload_head, list) {
6083 if (ptype->type != type || !ptype->callbacks.gro_receive)
6084 continue;
6085 return ptype;
6086 }
6087 return NULL;
6088 }
6089 EXPORT_SYMBOL(gro_find_receive_by_type);
6090
gro_find_complete_by_type(__be16 type)6091 struct packet_offload *gro_find_complete_by_type(__be16 type)
6092 {
6093 struct list_head *offload_head = &offload_base;
6094 struct packet_offload *ptype;
6095
6096 list_for_each_entry_rcu(ptype, offload_head, list) {
6097 if (ptype->type != type || !ptype->callbacks.gro_complete)
6098 continue;
6099 return ptype;
6100 }
6101 return NULL;
6102 }
6103 EXPORT_SYMBOL(gro_find_complete_by_type);
6104
napi_skb_free_stolen_head(struct sk_buff * skb)6105 static void napi_skb_free_stolen_head(struct sk_buff *skb)
6106 {
6107 skb_dst_drop(skb);
6108 skb_ext_put(skb);
6109 kmem_cache_free(skbuff_head_cache, skb);
6110 }
6111
napi_skb_finish(struct napi_struct * napi,struct sk_buff * skb,gro_result_t ret)6112 static gro_result_t napi_skb_finish(struct napi_struct *napi,
6113 struct sk_buff *skb,
6114 gro_result_t ret)
6115 {
6116 switch (ret) {
6117 case GRO_NORMAL:
6118 gro_normal_one(napi, skb, 1);
6119 break;
6120
6121 case GRO_DROP:
6122 kfree_skb(skb);
6123 break;
6124
6125 case GRO_MERGED_FREE:
6126 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
6127 napi_skb_free_stolen_head(skb);
6128 else
6129 __kfree_skb(skb);
6130 break;
6131
6132 case GRO_HELD:
6133 case GRO_MERGED:
6134 case GRO_CONSUMED:
6135 break;
6136 }
6137
6138 return ret;
6139 }
6140
napi_gro_receive(struct napi_struct * napi,struct sk_buff * skb)6141 gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
6142 {
6143 gro_result_t ret;
6144
6145 skb_mark_napi_id(skb, napi);
6146 trace_napi_gro_receive_entry(skb);
6147
6148 skb_gro_reset_offset(skb, 0);
6149
6150 ret = napi_skb_finish(napi, skb, dev_gro_receive(napi, skb));
6151 trace_napi_gro_receive_exit(ret);
6152
6153 return ret;
6154 }
6155 EXPORT_SYMBOL(napi_gro_receive);
6156
napi_reuse_skb(struct napi_struct * napi,struct sk_buff * skb)6157 static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
6158 {
6159 if (unlikely(skb->pfmemalloc)) {
6160 consume_skb(skb);
6161 return;
6162 }
6163 __skb_pull(skb, skb_headlen(skb));
6164 /* restore the reserve we had after netdev_alloc_skb_ip_align() */
6165 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
6166 __vlan_hwaccel_clear_tag(skb);
6167 skb->dev = napi->dev;
6168 skb->skb_iif = 0;
6169
6170 /* eth_type_trans() assumes pkt_type is PACKET_HOST */
6171 skb->pkt_type = PACKET_HOST;
6172
6173 skb->encapsulation = 0;
6174 skb_shinfo(skb)->gso_type = 0;
6175 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6176 skb_ext_reset(skb);
6177 nf_reset_ct(skb);
6178
6179 napi->skb = skb;
6180 }
6181
napi_get_frags(struct napi_struct * napi)6182 struct sk_buff *napi_get_frags(struct napi_struct *napi)
6183 {
6184 struct sk_buff *skb = napi->skb;
6185
6186 if (!skb) {
6187 skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
6188 if (skb) {
6189 napi->skb = skb;
6190 skb_mark_napi_id(skb, napi);
6191 }
6192 }
6193 return skb;
6194 }
6195 EXPORT_SYMBOL(napi_get_frags);
6196
napi_frags_finish(struct napi_struct * napi,struct sk_buff * skb,gro_result_t ret)6197 static gro_result_t napi_frags_finish(struct napi_struct *napi,
6198 struct sk_buff *skb,
6199 gro_result_t ret)
6200 {
6201 switch (ret) {
6202 case GRO_NORMAL:
6203 case GRO_HELD:
6204 __skb_push(skb, ETH_HLEN);
6205 skb->protocol = eth_type_trans(skb, skb->dev);
6206 if (ret == GRO_NORMAL)
6207 gro_normal_one(napi, skb, 1);
6208 break;
6209
6210 case GRO_DROP:
6211 napi_reuse_skb(napi, skb);
6212 break;
6213
6214 case GRO_MERGED_FREE:
6215 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
6216 napi_skb_free_stolen_head(skb);
6217 else
6218 napi_reuse_skb(napi, skb);
6219 break;
6220
6221 case GRO_MERGED:
6222 case GRO_CONSUMED:
6223 break;
6224 }
6225
6226 return ret;
6227 }
6228
6229 /* Upper GRO stack assumes network header starts at gro_offset=0
6230 * Drivers could call both napi_gro_frags() and napi_gro_receive()
6231 * We copy ethernet header into skb->data to have a common layout.
6232 */
napi_frags_skb(struct napi_struct * napi)6233 static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
6234 {
6235 struct sk_buff *skb = napi->skb;
6236 const struct ethhdr *eth;
6237 unsigned int hlen = sizeof(*eth);
6238
6239 napi->skb = NULL;
6240
6241 skb_reset_mac_header(skb);
6242 skb_gro_reset_offset(skb, hlen);
6243
6244 if (unlikely(skb_gro_header_hard(skb, hlen))) {
6245 eth = skb_gro_header_slow(skb, hlen, 0);
6246 if (unlikely(!eth)) {
6247 net_warn_ratelimited("%s: dropping impossible skb from %s\n",
6248 __func__, napi->dev->name);
6249 napi_reuse_skb(napi, skb);
6250 return NULL;
6251 }
6252 } else {
6253 eth = (const struct ethhdr *)skb->data;
6254 gro_pull_from_frag0(skb, hlen);
6255 NAPI_GRO_CB(skb)->frag0 += hlen;
6256 NAPI_GRO_CB(skb)->frag0_len -= hlen;
6257 }
6258 __skb_pull(skb, hlen);
6259
6260 /*
6261 * This works because the only protocols we care about don't require
6262 * special handling.
6263 * We'll fix it up properly in napi_frags_finish()
6264 */
6265 skb->protocol = eth->h_proto;
6266
6267 return skb;
6268 }
6269
napi_gro_frags(struct napi_struct * napi)6270 gro_result_t napi_gro_frags(struct napi_struct *napi)
6271 {
6272 gro_result_t ret;
6273 struct sk_buff *skb = napi_frags_skb(napi);
6274
6275 if (!skb)
6276 return GRO_DROP;
6277
6278 trace_napi_gro_frags_entry(skb);
6279
6280 ret = napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
6281 trace_napi_gro_frags_exit(ret);
6282
6283 return ret;
6284 }
6285 EXPORT_SYMBOL(napi_gro_frags);
6286
6287 /* Compute the checksum from gro_offset and return the folded value
6288 * after adding in any pseudo checksum.
6289 */
__skb_gro_checksum_complete(struct sk_buff * skb)6290 __sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
6291 {
6292 __wsum wsum;
6293 __sum16 sum;
6294
6295 wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
6296
6297 /* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
6298 sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
6299 /* See comments in __skb_checksum_complete(). */
6300 if (likely(!sum)) {
6301 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
6302 !skb->csum_complete_sw)
6303 netdev_rx_csum_fault(skb->dev, skb);
6304 }
6305
6306 NAPI_GRO_CB(skb)->csum = wsum;
6307 NAPI_GRO_CB(skb)->csum_valid = 1;
6308
6309 return sum;
6310 }
6311 EXPORT_SYMBOL(__skb_gro_checksum_complete);
6312
net_rps_send_ipi(struct softnet_data * remsd)6313 static void net_rps_send_ipi(struct softnet_data *remsd)
6314 {
6315 #ifdef CONFIG_RPS
6316 while (remsd) {
6317 struct softnet_data *next = remsd->rps_ipi_next;
6318
6319 if (cpu_online(remsd->cpu))
6320 smp_call_function_single_async(remsd->cpu, &remsd->csd);
6321 remsd = next;
6322 }
6323 #endif
6324 }
6325
6326 /*
6327 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
6328 * Note: called with local irq disabled, but exits with local irq enabled.
6329 */
net_rps_action_and_irq_enable(struct softnet_data * sd)6330 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
6331 {
6332 #ifdef CONFIG_RPS
6333 struct softnet_data *remsd = sd->rps_ipi_list;
6334
6335 if (remsd) {
6336 sd->rps_ipi_list = NULL;
6337
6338 local_irq_enable();
6339
6340 /* Send pending IPI's to kick RPS processing on remote cpus. */
6341 net_rps_send_ipi(remsd);
6342 } else
6343 #endif
6344 local_irq_enable();
6345 }
6346
sd_has_rps_ipi_waiting(struct softnet_data * sd)6347 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
6348 {
6349 #ifdef CONFIG_RPS
6350 return sd->rps_ipi_list != NULL;
6351 #else
6352 return false;
6353 #endif
6354 }
6355
process_backlog(struct napi_struct * napi,int quota)6356 static int process_backlog(struct napi_struct *napi, int quota)
6357 {
6358 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
6359 bool again = true;
6360 int work = 0;
6361
6362 /* Check if we have pending ipi, its better to send them now,
6363 * not waiting net_rx_action() end.
6364 */
6365 if (sd_has_rps_ipi_waiting(sd)) {
6366 local_irq_disable();
6367 net_rps_action_and_irq_enable(sd);
6368 }
6369
6370 napi->weight = dev_rx_weight;
6371 while (again) {
6372 struct sk_buff *skb;
6373
6374 while ((skb = __skb_dequeue(&sd->process_queue))) {
6375 rcu_read_lock();
6376 __netif_receive_skb(skb);
6377 rcu_read_unlock();
6378 input_queue_head_incr(sd);
6379 if (++work >= quota)
6380 return work;
6381
6382 }
6383
6384 local_irq_disable();
6385 rps_lock(sd);
6386 if (skb_queue_empty(&sd->input_pkt_queue)) {
6387 /*
6388 * Inline a custom version of __napi_complete().
6389 * only current cpu owns and manipulates this napi,
6390 * and NAPI_STATE_SCHED is the only possible flag set
6391 * on backlog.
6392 * We can use a plain write instead of clear_bit(),
6393 * and we dont need an smp_mb() memory barrier.
6394 */
6395 napi->state = 0;
6396 again = false;
6397 } else {
6398 skb_queue_splice_tail_init(&sd->input_pkt_queue,
6399 &sd->process_queue);
6400 }
6401 rps_unlock(sd);
6402 local_irq_enable();
6403 }
6404
6405 return work;
6406 }
6407
6408 /**
6409 * __napi_schedule - schedule for receive
6410 * @n: entry to schedule
6411 *
6412 * The entry's receive function will be scheduled to run.
6413 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6414 */
__napi_schedule(struct napi_struct * n)6415 void __napi_schedule(struct napi_struct *n)
6416 {
6417 unsigned long flags;
6418
6419 local_irq_save(flags);
6420 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6421 local_irq_restore(flags);
6422 }
6423 EXPORT_SYMBOL(__napi_schedule);
6424
6425 /**
6426 * napi_schedule_prep - check if napi can be scheduled
6427 * @n: napi context
6428 *
6429 * Test if NAPI routine is already running, and if not mark
6430 * it as running. This is used as a condition variable to
6431 * insure only one NAPI poll instance runs. We also make
6432 * sure there is no pending NAPI disable.
6433 */
napi_schedule_prep(struct napi_struct * n)6434 bool napi_schedule_prep(struct napi_struct *n)
6435 {
6436 unsigned long val, new;
6437
6438 do {
6439 val = READ_ONCE(n->state);
6440 if (unlikely(val & NAPIF_STATE_DISABLE))
6441 return false;
6442 new = val | NAPIF_STATE_SCHED;
6443
6444 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6445 * This was suggested by Alexander Duyck, as compiler
6446 * emits better code than :
6447 * if (val & NAPIF_STATE_SCHED)
6448 * new |= NAPIF_STATE_MISSED;
6449 */
6450 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6451 NAPIF_STATE_MISSED;
6452 } while (cmpxchg(&n->state, val, new) != val);
6453
6454 return !(val & NAPIF_STATE_SCHED);
6455 }
6456 EXPORT_SYMBOL(napi_schedule_prep);
6457
6458 /**
6459 * __napi_schedule_irqoff - schedule for receive
6460 * @n: entry to schedule
6461 *
6462 * Variant of __napi_schedule() assuming hard irqs are masked.
6463 *
6464 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
6465 * because the interrupt disabled assumption might not be true
6466 * due to force-threaded interrupts and spinlock substitution.
6467 */
__napi_schedule_irqoff(struct napi_struct * n)6468 void __napi_schedule_irqoff(struct napi_struct *n)
6469 {
6470 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6471 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6472 else
6473 __napi_schedule(n);
6474 }
6475 EXPORT_SYMBOL(__napi_schedule_irqoff);
6476
napi_complete_done(struct napi_struct * n,int work_done)6477 bool napi_complete_done(struct napi_struct *n, int work_done)
6478 {
6479 unsigned long flags, val, new, timeout = 0;
6480 bool ret = true;
6481
6482 /*
6483 * 1) Don't let napi dequeue from the cpu poll list
6484 * just in case its running on a different cpu.
6485 * 2) If we are busy polling, do nothing here, we have
6486 * the guarantee we will be called later.
6487 */
6488 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6489 NAPIF_STATE_IN_BUSY_POLL)))
6490 return false;
6491
6492 if (work_done) {
6493 if (n->gro_bitmask)
6494 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6495 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
6496 }
6497 if (n->defer_hard_irqs_count > 0) {
6498 n->defer_hard_irqs_count--;
6499 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6500 if (timeout)
6501 ret = false;
6502 }
6503 if (n->gro_bitmask) {
6504 /* When the NAPI instance uses a timeout and keeps postponing
6505 * it, we need to bound somehow the time packets are kept in
6506 * the GRO layer
6507 */
6508 napi_gro_flush(n, !!timeout);
6509 }
6510
6511 gro_normal_list(n);
6512
6513 if (unlikely(!list_empty(&n->poll_list))) {
6514 /* If n->poll_list is not empty, we need to mask irqs */
6515 local_irq_save(flags);
6516 list_del_init(&n->poll_list);
6517 local_irq_restore(flags);
6518 }
6519
6520 do {
6521 val = READ_ONCE(n->state);
6522
6523 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6524
6525 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED);
6526
6527 /* If STATE_MISSED was set, leave STATE_SCHED set,
6528 * because we will call napi->poll() one more time.
6529 * This C code was suggested by Alexander Duyck to help gcc.
6530 */
6531 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6532 NAPIF_STATE_SCHED;
6533 } while (cmpxchg(&n->state, val, new) != val);
6534
6535 if (unlikely(val & NAPIF_STATE_MISSED)) {
6536 __napi_schedule(n);
6537 return false;
6538 }
6539
6540 if (timeout)
6541 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6542 HRTIMER_MODE_REL_PINNED);
6543 return ret;
6544 }
6545 EXPORT_SYMBOL(napi_complete_done);
6546
6547 /* must be called under rcu_read_lock(), as we dont take a reference */
napi_by_id(unsigned int napi_id)6548 static struct napi_struct *napi_by_id(unsigned int napi_id)
6549 {
6550 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6551 struct napi_struct *napi;
6552
6553 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6554 if (napi->napi_id == napi_id)
6555 return napi;
6556
6557 return NULL;
6558 }
6559
6560 #if defined(CONFIG_NET_RX_BUSY_POLL)
6561
6562 #define BUSY_POLL_BUDGET 8
6563
busy_poll_stop(struct napi_struct * napi,void * have_poll_lock)6564 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock)
6565 {
6566 int rc;
6567
6568 /* Busy polling means there is a high chance device driver hard irq
6569 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6570 * set in napi_schedule_prep().
6571 * Since we are about to call napi->poll() once more, we can safely
6572 * clear NAPI_STATE_MISSED.
6573 *
6574 * Note: x86 could use a single "lock and ..." instruction
6575 * to perform these two clear_bit()
6576 */
6577 clear_bit(NAPI_STATE_MISSED, &napi->state);
6578 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6579
6580 local_bh_disable();
6581
6582 /* All we really want here is to re-enable device interrupts.
6583 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6584 */
6585 rc = napi->poll(napi, BUSY_POLL_BUDGET);
6586 /* We can't gro_normal_list() here, because napi->poll() might have
6587 * rearmed the napi (napi_complete_done()) in which case it could
6588 * already be running on another CPU.
6589 */
6590 trace_napi_poll(napi, rc, BUSY_POLL_BUDGET);
6591 netpoll_poll_unlock(have_poll_lock);
6592 if (rc == BUSY_POLL_BUDGET) {
6593 /* As the whole budget was spent, we still own the napi so can
6594 * safely handle the rx_list.
6595 */
6596 gro_normal_list(napi);
6597 __napi_schedule(napi);
6598 }
6599 local_bh_enable();
6600 }
6601
napi_busy_loop(unsigned int napi_id,bool (* loop_end)(void *,unsigned long),void * loop_end_arg)6602 void napi_busy_loop(unsigned int napi_id,
6603 bool (*loop_end)(void *, unsigned long),
6604 void *loop_end_arg)
6605 {
6606 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6607 int (*napi_poll)(struct napi_struct *napi, int budget);
6608 void *have_poll_lock = NULL;
6609 struct napi_struct *napi;
6610
6611 restart:
6612 napi_poll = NULL;
6613
6614 rcu_read_lock();
6615
6616 napi = napi_by_id(napi_id);
6617 if (!napi)
6618 goto out;
6619
6620 preempt_disable();
6621 for (;;) {
6622 int work = 0;
6623
6624 local_bh_disable();
6625 if (!napi_poll) {
6626 unsigned long val = READ_ONCE(napi->state);
6627
6628 /* If multiple threads are competing for this napi,
6629 * we avoid dirtying napi->state as much as we can.
6630 */
6631 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6632 NAPIF_STATE_IN_BUSY_POLL))
6633 goto count;
6634 if (cmpxchg(&napi->state, val,
6635 val | NAPIF_STATE_IN_BUSY_POLL |
6636 NAPIF_STATE_SCHED) != val)
6637 goto count;
6638 have_poll_lock = netpoll_poll_lock(napi);
6639 napi_poll = napi->poll;
6640 }
6641 work = napi_poll(napi, BUSY_POLL_BUDGET);
6642 trace_napi_poll(napi, work, BUSY_POLL_BUDGET);
6643 gro_normal_list(napi);
6644 count:
6645 if (work > 0)
6646 __NET_ADD_STATS(dev_net(napi->dev),
6647 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6648 local_bh_enable();
6649
6650 if (!loop_end || loop_end(loop_end_arg, start_time))
6651 break;
6652
6653 if (unlikely(need_resched())) {
6654 if (napi_poll)
6655 busy_poll_stop(napi, have_poll_lock);
6656 preempt_enable();
6657 rcu_read_unlock();
6658 cond_resched();
6659 if (loop_end(loop_end_arg, start_time))
6660 return;
6661 goto restart;
6662 }
6663 cpu_relax();
6664 }
6665 if (napi_poll)
6666 busy_poll_stop(napi, have_poll_lock);
6667 preempt_enable();
6668 out:
6669 rcu_read_unlock();
6670 }
6671 EXPORT_SYMBOL(napi_busy_loop);
6672
6673 #endif /* CONFIG_NET_RX_BUSY_POLL */
6674
napi_hash_add(struct napi_struct * napi)6675 static void napi_hash_add(struct napi_struct *napi)
6676 {
6677 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6678 return;
6679
6680 spin_lock(&napi_hash_lock);
6681
6682 /* 0..NR_CPUS range is reserved for sender_cpu use */
6683 do {
6684 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6685 napi_gen_id = MIN_NAPI_ID;
6686 } while (napi_by_id(napi_gen_id));
6687 napi->napi_id = napi_gen_id;
6688
6689 hlist_add_head_rcu(&napi->napi_hash_node,
6690 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6691
6692 spin_unlock(&napi_hash_lock);
6693 }
6694
6695 /* Warning : caller is responsible to make sure rcu grace period
6696 * is respected before freeing memory containing @napi
6697 */
napi_hash_del(struct napi_struct * napi)6698 static void napi_hash_del(struct napi_struct *napi)
6699 {
6700 spin_lock(&napi_hash_lock);
6701
6702 hlist_del_init_rcu(&napi->napi_hash_node);
6703
6704 spin_unlock(&napi_hash_lock);
6705 }
6706
napi_watchdog(struct hrtimer * timer)6707 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6708 {
6709 struct napi_struct *napi;
6710
6711 napi = container_of(timer, struct napi_struct, timer);
6712
6713 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6714 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6715 */
6716 if (!napi_disable_pending(napi) &&
6717 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state))
6718 __napi_schedule_irqoff(napi);
6719
6720 return HRTIMER_NORESTART;
6721 }
6722
init_gro_hash(struct napi_struct * napi)6723 static void init_gro_hash(struct napi_struct *napi)
6724 {
6725 int i;
6726
6727 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6728 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6729 napi->gro_hash[i].count = 0;
6730 }
6731 napi->gro_bitmask = 0;
6732 }
6733
netif_napi_add(struct net_device * dev,struct napi_struct * napi,int (* poll)(struct napi_struct *,int),int weight)6734 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
6735 int (*poll)(struct napi_struct *, int), int weight)
6736 {
6737 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6738 return;
6739
6740 INIT_LIST_HEAD(&napi->poll_list);
6741 INIT_HLIST_NODE(&napi->napi_hash_node);
6742 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6743 napi->timer.function = napi_watchdog;
6744 init_gro_hash(napi);
6745 napi->skb = NULL;
6746 INIT_LIST_HEAD(&napi->rx_list);
6747 napi->rx_count = 0;
6748 napi->poll = poll;
6749 if (weight > NAPI_POLL_WEIGHT)
6750 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6751 weight);
6752 napi->weight = weight;
6753 napi->dev = dev;
6754 #ifdef CONFIG_NETPOLL
6755 napi->poll_owner = -1;
6756 #endif
6757 set_bit(NAPI_STATE_SCHED, &napi->state);
6758 set_bit(NAPI_STATE_NPSVC, &napi->state);
6759 list_add_rcu(&napi->dev_list, &dev->napi_list);
6760 napi_hash_add(napi);
6761 }
6762 EXPORT_SYMBOL(netif_napi_add);
6763
napi_disable(struct napi_struct * n)6764 void napi_disable(struct napi_struct *n)
6765 {
6766 might_sleep();
6767 set_bit(NAPI_STATE_DISABLE, &n->state);
6768
6769 while (test_and_set_bit(NAPI_STATE_SCHED, &n->state))
6770 msleep(1);
6771 while (test_and_set_bit(NAPI_STATE_NPSVC, &n->state))
6772 msleep(1);
6773
6774 hrtimer_cancel(&n->timer);
6775
6776 clear_bit(NAPI_STATE_DISABLE, &n->state);
6777 }
6778 EXPORT_SYMBOL(napi_disable);
6779
flush_gro_hash(struct napi_struct * napi)6780 static void flush_gro_hash(struct napi_struct *napi)
6781 {
6782 int i;
6783
6784 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6785 struct sk_buff *skb, *n;
6786
6787 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6788 kfree_skb(skb);
6789 napi->gro_hash[i].count = 0;
6790 }
6791 }
6792
6793 /* Must be called in process context */
__netif_napi_del(struct napi_struct * napi)6794 void __netif_napi_del(struct napi_struct *napi)
6795 {
6796 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6797 return;
6798
6799 napi_hash_del(napi);
6800 list_del_rcu(&napi->dev_list);
6801 napi_free_frags(napi);
6802
6803 flush_gro_hash(napi);
6804 napi->gro_bitmask = 0;
6805 }
6806 EXPORT_SYMBOL(__netif_napi_del);
6807
napi_poll(struct napi_struct * n,struct list_head * repoll)6808 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6809 {
6810 void *have;
6811 int work, weight;
6812
6813 list_del_init(&n->poll_list);
6814
6815 have = netpoll_poll_lock(n);
6816
6817 weight = n->weight;
6818
6819 /* This NAPI_STATE_SCHED test is for avoiding a race
6820 * with netpoll's poll_napi(). Only the entity which
6821 * obtains the lock and sees NAPI_STATE_SCHED set will
6822 * actually make the ->poll() call. Therefore we avoid
6823 * accidentally calling ->poll() when NAPI is not scheduled.
6824 */
6825 work = 0;
6826 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6827 work = n->poll(n, weight);
6828 trace_napi_poll(n, work, weight);
6829 }
6830
6831 if (unlikely(work > weight))
6832 pr_err_once("NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6833 n->poll, work, weight);
6834
6835 if (likely(work < weight))
6836 goto out_unlock;
6837
6838 /* Drivers must not modify the NAPI state if they
6839 * consume the entire weight. In such cases this code
6840 * still "owns" the NAPI instance and therefore can
6841 * move the instance around on the list at-will.
6842 */
6843 if (unlikely(napi_disable_pending(n))) {
6844 napi_complete(n);
6845 goto out_unlock;
6846 }
6847
6848 if (n->gro_bitmask) {
6849 /* flush too old packets
6850 * If HZ < 1000, flush all packets.
6851 */
6852 napi_gro_flush(n, HZ >= 1000);
6853 }
6854
6855 gro_normal_list(n);
6856
6857 /* Some drivers may have called napi_schedule
6858 * prior to exhausting their budget.
6859 */
6860 if (unlikely(!list_empty(&n->poll_list))) {
6861 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6862 n->dev ? n->dev->name : "backlog");
6863 goto out_unlock;
6864 }
6865
6866 list_add_tail(&n->poll_list, repoll);
6867
6868 out_unlock:
6869 netpoll_poll_unlock(have);
6870
6871 return work;
6872 }
6873
net_rx_action(struct softirq_action * h)6874 static __latent_entropy void net_rx_action(struct softirq_action *h)
6875 {
6876 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6877 unsigned long time_limit = jiffies +
6878 usecs_to_jiffies(netdev_budget_usecs);
6879 int budget = netdev_budget;
6880 LIST_HEAD(list);
6881 LIST_HEAD(repoll);
6882
6883 local_irq_disable();
6884 list_splice_init(&sd->poll_list, &list);
6885 local_irq_enable();
6886
6887 for (;;) {
6888 struct napi_struct *n;
6889
6890 if (list_empty(&list)) {
6891 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
6892 goto out;
6893 break;
6894 }
6895
6896 n = list_first_entry(&list, struct napi_struct, poll_list);
6897 budget -= napi_poll(n, &repoll);
6898
6899 /* If softirq window is exhausted then punt.
6900 * Allow this to run for 2 jiffies since which will allow
6901 * an average latency of 1.5/HZ.
6902 */
6903 if (unlikely(budget <= 0 ||
6904 time_after_eq(jiffies, time_limit))) {
6905 sd->time_squeeze++;
6906 break;
6907 }
6908 }
6909
6910 local_irq_disable();
6911
6912 list_splice_tail_init(&sd->poll_list, &list);
6913 list_splice_tail(&repoll, &list);
6914 list_splice(&list, &sd->poll_list);
6915 if (!list_empty(&sd->poll_list))
6916 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6917
6918 net_rps_action_and_irq_enable(sd);
6919 out:
6920 __kfree_skb_flush();
6921 }
6922
6923 struct netdev_adjacent {
6924 struct net_device *dev;
6925
6926 /* upper master flag, there can only be one master device per list */
6927 bool master;
6928
6929 /* lookup ignore flag */
6930 bool ignore;
6931
6932 /* counter for the number of times this device was added to us */
6933 u16 ref_nr;
6934
6935 /* private field for the users */
6936 void *private;
6937
6938 struct list_head list;
6939 struct rcu_head rcu;
6940 };
6941
__netdev_find_adj(struct net_device * adj_dev,struct list_head * adj_list)6942 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6943 struct list_head *adj_list)
6944 {
6945 struct netdev_adjacent *adj;
6946
6947 list_for_each_entry(adj, adj_list, list) {
6948 if (adj->dev == adj_dev)
6949 return adj;
6950 }
6951 return NULL;
6952 }
6953
____netdev_has_upper_dev(struct net_device * upper_dev,struct netdev_nested_priv * priv)6954 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6955 struct netdev_nested_priv *priv)
6956 {
6957 struct net_device *dev = (struct net_device *)priv->data;
6958
6959 return upper_dev == dev;
6960 }
6961
6962 /**
6963 * netdev_has_upper_dev - Check if device is linked to an upper device
6964 * @dev: device
6965 * @upper_dev: upper device to check
6966 *
6967 * Find out if a device is linked to specified upper device and return true
6968 * in case it is. Note that this checks only immediate upper device,
6969 * not through a complete stack of devices. The caller must hold the RTNL lock.
6970 */
netdev_has_upper_dev(struct net_device * dev,struct net_device * upper_dev)6971 bool netdev_has_upper_dev(struct net_device *dev,
6972 struct net_device *upper_dev)
6973 {
6974 struct netdev_nested_priv priv = {
6975 .data = (void *)upper_dev,
6976 };
6977
6978 ASSERT_RTNL();
6979
6980 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6981 &priv);
6982 }
6983 EXPORT_SYMBOL(netdev_has_upper_dev);
6984
6985 /**
6986 * netdev_has_upper_dev_all - Check if device is linked to an upper device
6987 * @dev: device
6988 * @upper_dev: upper device to check
6989 *
6990 * Find out if a device is linked to specified upper device and return true
6991 * in case it is. Note that this checks the entire upper device chain.
6992 * The caller must hold rcu lock.
6993 */
6994
netdev_has_upper_dev_all_rcu(struct net_device * dev,struct net_device * upper_dev)6995 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6996 struct net_device *upper_dev)
6997 {
6998 struct netdev_nested_priv priv = {
6999 .data = (void *)upper_dev,
7000 };
7001
7002 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
7003 &priv);
7004 }
7005 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
7006
7007 /**
7008 * netdev_has_any_upper_dev - Check if device is linked to some device
7009 * @dev: device
7010 *
7011 * Find out if a device is linked to an upper device and return true in case
7012 * it is. The caller must hold the RTNL lock.
7013 */
netdev_has_any_upper_dev(struct net_device * dev)7014 bool netdev_has_any_upper_dev(struct net_device *dev)
7015 {
7016 ASSERT_RTNL();
7017
7018 return !list_empty(&dev->adj_list.upper);
7019 }
7020 EXPORT_SYMBOL(netdev_has_any_upper_dev);
7021
7022 /**
7023 * netdev_master_upper_dev_get - Get master upper device
7024 * @dev: device
7025 *
7026 * Find a master upper device and return pointer to it or NULL in case
7027 * it's not there. The caller must hold the RTNL lock.
7028 */
netdev_master_upper_dev_get(struct net_device * dev)7029 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
7030 {
7031 struct netdev_adjacent *upper;
7032
7033 ASSERT_RTNL();
7034
7035 if (list_empty(&dev->adj_list.upper))
7036 return NULL;
7037
7038 upper = list_first_entry(&dev->adj_list.upper,
7039 struct netdev_adjacent, list);
7040 if (likely(upper->master))
7041 return upper->dev;
7042 return NULL;
7043 }
7044 EXPORT_SYMBOL(netdev_master_upper_dev_get);
7045
__netdev_master_upper_dev_get(struct net_device * dev)7046 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
7047 {
7048 struct netdev_adjacent *upper;
7049
7050 ASSERT_RTNL();
7051
7052 if (list_empty(&dev->adj_list.upper))
7053 return NULL;
7054
7055 upper = list_first_entry(&dev->adj_list.upper,
7056 struct netdev_adjacent, list);
7057 if (likely(upper->master) && !upper->ignore)
7058 return upper->dev;
7059 return NULL;
7060 }
7061
7062 /**
7063 * netdev_has_any_lower_dev - Check if device is linked to some device
7064 * @dev: device
7065 *
7066 * Find out if a device is linked to a lower device and return true in case
7067 * it is. The caller must hold the RTNL lock.
7068 */
netdev_has_any_lower_dev(struct net_device * dev)7069 static bool netdev_has_any_lower_dev(struct net_device *dev)
7070 {
7071 ASSERT_RTNL();
7072
7073 return !list_empty(&dev->adj_list.lower);
7074 }
7075
netdev_adjacent_get_private(struct list_head * adj_list)7076 void *netdev_adjacent_get_private(struct list_head *adj_list)
7077 {
7078 struct netdev_adjacent *adj;
7079
7080 adj = list_entry(adj_list, struct netdev_adjacent, list);
7081
7082 return adj->private;
7083 }
7084 EXPORT_SYMBOL(netdev_adjacent_get_private);
7085
7086 /**
7087 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
7088 * @dev: device
7089 * @iter: list_head ** of the current position
7090 *
7091 * Gets the next device from the dev's upper list, starting from iter
7092 * position. The caller must hold RCU read lock.
7093 */
netdev_upper_get_next_dev_rcu(struct net_device * dev,struct list_head ** iter)7094 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
7095 struct list_head **iter)
7096 {
7097 struct netdev_adjacent *upper;
7098
7099 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7100
7101 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7102
7103 if (&upper->list == &dev->adj_list.upper)
7104 return NULL;
7105
7106 *iter = &upper->list;
7107
7108 return upper->dev;
7109 }
7110 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
7111
__netdev_next_upper_dev(struct net_device * dev,struct list_head ** iter,bool * ignore)7112 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
7113 struct list_head **iter,
7114 bool *ignore)
7115 {
7116 struct netdev_adjacent *upper;
7117
7118 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
7119
7120 if (&upper->list == &dev->adj_list.upper)
7121 return NULL;
7122
7123 *iter = &upper->list;
7124 *ignore = upper->ignore;
7125
7126 return upper->dev;
7127 }
7128
netdev_next_upper_dev_rcu(struct net_device * dev,struct list_head ** iter)7129 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
7130 struct list_head **iter)
7131 {
7132 struct netdev_adjacent *upper;
7133
7134 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7135
7136 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7137
7138 if (&upper->list == &dev->adj_list.upper)
7139 return NULL;
7140
7141 *iter = &upper->list;
7142
7143 return upper->dev;
7144 }
7145
__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)7146 static int __netdev_walk_all_upper_dev(struct net_device *dev,
7147 int (*fn)(struct net_device *dev,
7148 struct netdev_nested_priv *priv),
7149 struct netdev_nested_priv *priv)
7150 {
7151 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7152 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7153 int ret, cur = 0;
7154 bool ignore;
7155
7156 now = dev;
7157 iter = &dev->adj_list.upper;
7158
7159 while (1) {
7160 if (now != dev) {
7161 ret = fn(now, priv);
7162 if (ret)
7163 return ret;
7164 }
7165
7166 next = NULL;
7167 while (1) {
7168 udev = __netdev_next_upper_dev(now, &iter, &ignore);
7169 if (!udev)
7170 break;
7171 if (ignore)
7172 continue;
7173
7174 next = udev;
7175 niter = &udev->adj_list.upper;
7176 dev_stack[cur] = now;
7177 iter_stack[cur++] = iter;
7178 break;
7179 }
7180
7181 if (!next) {
7182 if (!cur)
7183 return 0;
7184 next = dev_stack[--cur];
7185 niter = iter_stack[cur];
7186 }
7187
7188 now = next;
7189 iter = niter;
7190 }
7191
7192 return 0;
7193 }
7194
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)7195 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
7196 int (*fn)(struct net_device *dev,
7197 struct netdev_nested_priv *priv),
7198 struct netdev_nested_priv *priv)
7199 {
7200 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7201 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7202 int ret, cur = 0;
7203
7204 now = dev;
7205 iter = &dev->adj_list.upper;
7206
7207 while (1) {
7208 if (now != dev) {
7209 ret = fn(now, priv);
7210 if (ret)
7211 return ret;
7212 }
7213
7214 next = NULL;
7215 while (1) {
7216 udev = netdev_next_upper_dev_rcu(now, &iter);
7217 if (!udev)
7218 break;
7219
7220 next = udev;
7221 niter = &udev->adj_list.upper;
7222 dev_stack[cur] = now;
7223 iter_stack[cur++] = iter;
7224 break;
7225 }
7226
7227 if (!next) {
7228 if (!cur)
7229 return 0;
7230 next = dev_stack[--cur];
7231 niter = iter_stack[cur];
7232 }
7233
7234 now = next;
7235 iter = niter;
7236 }
7237
7238 return 0;
7239 }
7240 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7241
__netdev_has_upper_dev(struct net_device * dev,struct net_device * upper_dev)7242 static bool __netdev_has_upper_dev(struct net_device *dev,
7243 struct net_device *upper_dev)
7244 {
7245 struct netdev_nested_priv priv = {
7246 .flags = 0,
7247 .data = (void *)upper_dev,
7248 };
7249
7250 ASSERT_RTNL();
7251
7252 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7253 &priv);
7254 }
7255
7256 /**
7257 * netdev_lower_get_next_private - Get the next ->private from the
7258 * lower neighbour list
7259 * @dev: device
7260 * @iter: list_head ** of the current position
7261 *
7262 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7263 * list, starting from iter position. The caller must hold either hold the
7264 * RTNL lock or its own locking that guarantees that the neighbour lower
7265 * list will remain unchanged.
7266 */
netdev_lower_get_next_private(struct net_device * dev,struct list_head ** iter)7267 void *netdev_lower_get_next_private(struct net_device *dev,
7268 struct list_head **iter)
7269 {
7270 struct netdev_adjacent *lower;
7271
7272 lower = list_entry(*iter, struct netdev_adjacent, list);
7273
7274 if (&lower->list == &dev->adj_list.lower)
7275 return NULL;
7276
7277 *iter = lower->list.next;
7278
7279 return lower->private;
7280 }
7281 EXPORT_SYMBOL(netdev_lower_get_next_private);
7282
7283 /**
7284 * netdev_lower_get_next_private_rcu - Get the next ->private from the
7285 * lower neighbour list, RCU
7286 * variant
7287 * @dev: device
7288 * @iter: list_head ** of the current position
7289 *
7290 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7291 * list, starting from iter position. The caller must hold RCU read lock.
7292 */
netdev_lower_get_next_private_rcu(struct net_device * dev,struct list_head ** iter)7293 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
7294 struct list_head **iter)
7295 {
7296 struct netdev_adjacent *lower;
7297
7298 WARN_ON_ONCE(!rcu_read_lock_held());
7299
7300 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7301
7302 if (&lower->list == &dev->adj_list.lower)
7303 return NULL;
7304
7305 *iter = &lower->list;
7306
7307 return lower->private;
7308 }
7309 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7310
7311 /**
7312 * netdev_lower_get_next - Get the next device from the lower neighbour
7313 * list
7314 * @dev: device
7315 * @iter: list_head ** of the current position
7316 *
7317 * Gets the next netdev_adjacent from the dev's lower neighbour
7318 * list, starting from iter position. The caller must hold RTNL lock or
7319 * its own locking that guarantees that the neighbour lower
7320 * list will remain unchanged.
7321 */
netdev_lower_get_next(struct net_device * dev,struct list_head ** iter)7322 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7323 {
7324 struct netdev_adjacent *lower;
7325
7326 lower = list_entry(*iter, struct netdev_adjacent, list);
7327
7328 if (&lower->list == &dev->adj_list.lower)
7329 return NULL;
7330
7331 *iter = lower->list.next;
7332
7333 return lower->dev;
7334 }
7335 EXPORT_SYMBOL(netdev_lower_get_next);
7336
netdev_next_lower_dev(struct net_device * dev,struct list_head ** iter)7337 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7338 struct list_head **iter)
7339 {
7340 struct netdev_adjacent *lower;
7341
7342 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7343
7344 if (&lower->list == &dev->adj_list.lower)
7345 return NULL;
7346
7347 *iter = &lower->list;
7348
7349 return lower->dev;
7350 }
7351
__netdev_next_lower_dev(struct net_device * dev,struct list_head ** iter,bool * ignore)7352 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7353 struct list_head **iter,
7354 bool *ignore)
7355 {
7356 struct netdev_adjacent *lower;
7357
7358 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7359
7360 if (&lower->list == &dev->adj_list.lower)
7361 return NULL;
7362
7363 *iter = &lower->list;
7364 *ignore = lower->ignore;
7365
7366 return lower->dev;
7367 }
7368
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)7369 int netdev_walk_all_lower_dev(struct net_device *dev,
7370 int (*fn)(struct net_device *dev,
7371 struct netdev_nested_priv *priv),
7372 struct netdev_nested_priv *priv)
7373 {
7374 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7375 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7376 int ret, cur = 0;
7377
7378 now = dev;
7379 iter = &dev->adj_list.lower;
7380
7381 while (1) {
7382 if (now != dev) {
7383 ret = fn(now, priv);
7384 if (ret)
7385 return ret;
7386 }
7387
7388 next = NULL;
7389 while (1) {
7390 ldev = netdev_next_lower_dev(now, &iter);
7391 if (!ldev)
7392 break;
7393
7394 next = ldev;
7395 niter = &ldev->adj_list.lower;
7396 dev_stack[cur] = now;
7397 iter_stack[cur++] = iter;
7398 break;
7399 }
7400
7401 if (!next) {
7402 if (!cur)
7403 return 0;
7404 next = dev_stack[--cur];
7405 niter = iter_stack[cur];
7406 }
7407
7408 now = next;
7409 iter = niter;
7410 }
7411
7412 return 0;
7413 }
7414 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7415
__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)7416 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7417 int (*fn)(struct net_device *dev,
7418 struct netdev_nested_priv *priv),
7419 struct netdev_nested_priv *priv)
7420 {
7421 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7422 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7423 int ret, cur = 0;
7424 bool ignore;
7425
7426 now = dev;
7427 iter = &dev->adj_list.lower;
7428
7429 while (1) {
7430 if (now != dev) {
7431 ret = fn(now, priv);
7432 if (ret)
7433 return ret;
7434 }
7435
7436 next = NULL;
7437 while (1) {
7438 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7439 if (!ldev)
7440 break;
7441 if (ignore)
7442 continue;
7443
7444 next = ldev;
7445 niter = &ldev->adj_list.lower;
7446 dev_stack[cur] = now;
7447 iter_stack[cur++] = iter;
7448 break;
7449 }
7450
7451 if (!next) {
7452 if (!cur)
7453 return 0;
7454 next = dev_stack[--cur];
7455 niter = iter_stack[cur];
7456 }
7457
7458 now = next;
7459 iter = niter;
7460 }
7461
7462 return 0;
7463 }
7464
netdev_next_lower_dev_rcu(struct net_device * dev,struct list_head ** iter)7465 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7466 struct list_head **iter)
7467 {
7468 struct netdev_adjacent *lower;
7469
7470 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7471 if (&lower->list == &dev->adj_list.lower)
7472 return NULL;
7473
7474 *iter = &lower->list;
7475
7476 return lower->dev;
7477 }
7478 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7479
__netdev_upper_depth(struct net_device * dev)7480 static u8 __netdev_upper_depth(struct net_device *dev)
7481 {
7482 struct net_device *udev;
7483 struct list_head *iter;
7484 u8 max_depth = 0;
7485 bool ignore;
7486
7487 for (iter = &dev->adj_list.upper,
7488 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7489 udev;
7490 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7491 if (ignore)
7492 continue;
7493 if (max_depth < udev->upper_level)
7494 max_depth = udev->upper_level;
7495 }
7496
7497 return max_depth;
7498 }
7499
__netdev_lower_depth(struct net_device * dev)7500 static u8 __netdev_lower_depth(struct net_device *dev)
7501 {
7502 struct net_device *ldev;
7503 struct list_head *iter;
7504 u8 max_depth = 0;
7505 bool ignore;
7506
7507 for (iter = &dev->adj_list.lower,
7508 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7509 ldev;
7510 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7511 if (ignore)
7512 continue;
7513 if (max_depth < ldev->lower_level)
7514 max_depth = ldev->lower_level;
7515 }
7516
7517 return max_depth;
7518 }
7519
__netdev_update_upper_level(struct net_device * dev,struct netdev_nested_priv * __unused)7520 static int __netdev_update_upper_level(struct net_device *dev,
7521 struct netdev_nested_priv *__unused)
7522 {
7523 dev->upper_level = __netdev_upper_depth(dev) + 1;
7524 return 0;
7525 }
7526
__netdev_update_lower_level(struct net_device * dev,struct netdev_nested_priv * priv)7527 static int __netdev_update_lower_level(struct net_device *dev,
7528 struct netdev_nested_priv *priv)
7529 {
7530 dev->lower_level = __netdev_lower_depth(dev) + 1;
7531
7532 #ifdef CONFIG_LOCKDEP
7533 if (!priv)
7534 return 0;
7535
7536 if (priv->flags & NESTED_SYNC_IMM)
7537 dev->nested_level = dev->lower_level - 1;
7538 if (priv->flags & NESTED_SYNC_TODO)
7539 net_unlink_todo(dev);
7540 #endif
7541 return 0;
7542 }
7543
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)7544 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7545 int (*fn)(struct net_device *dev,
7546 struct netdev_nested_priv *priv),
7547 struct netdev_nested_priv *priv)
7548 {
7549 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7550 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7551 int ret, cur = 0;
7552
7553 now = dev;
7554 iter = &dev->adj_list.lower;
7555
7556 while (1) {
7557 if (now != dev) {
7558 ret = fn(now, priv);
7559 if (ret)
7560 return ret;
7561 }
7562
7563 next = NULL;
7564 while (1) {
7565 ldev = netdev_next_lower_dev_rcu(now, &iter);
7566 if (!ldev)
7567 break;
7568
7569 next = ldev;
7570 niter = &ldev->adj_list.lower;
7571 dev_stack[cur] = now;
7572 iter_stack[cur++] = iter;
7573 break;
7574 }
7575
7576 if (!next) {
7577 if (!cur)
7578 return 0;
7579 next = dev_stack[--cur];
7580 niter = iter_stack[cur];
7581 }
7582
7583 now = next;
7584 iter = niter;
7585 }
7586
7587 return 0;
7588 }
7589 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7590
7591 /**
7592 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7593 * lower neighbour list, RCU
7594 * variant
7595 * @dev: device
7596 *
7597 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7598 * list. The caller must hold RCU read lock.
7599 */
netdev_lower_get_first_private_rcu(struct net_device * dev)7600 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7601 {
7602 struct netdev_adjacent *lower;
7603
7604 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7605 struct netdev_adjacent, list);
7606 if (lower)
7607 return lower->private;
7608 return NULL;
7609 }
7610 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7611
7612 /**
7613 * netdev_master_upper_dev_get_rcu - Get master upper device
7614 * @dev: device
7615 *
7616 * Find a master upper device and return pointer to it or NULL in case
7617 * it's not there. The caller must hold the RCU read lock.
7618 */
netdev_master_upper_dev_get_rcu(struct net_device * dev)7619 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7620 {
7621 struct netdev_adjacent *upper;
7622
7623 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7624 struct netdev_adjacent, list);
7625 if (upper && likely(upper->master))
7626 return upper->dev;
7627 return NULL;
7628 }
7629 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7630
netdev_adjacent_sysfs_add(struct net_device * dev,struct net_device * adj_dev,struct list_head * dev_list)7631 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7632 struct net_device *adj_dev,
7633 struct list_head *dev_list)
7634 {
7635 char linkname[IFNAMSIZ+7];
7636
7637 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7638 "upper_%s" : "lower_%s", adj_dev->name);
7639 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7640 linkname);
7641 }
netdev_adjacent_sysfs_del(struct net_device * dev,char * name,struct list_head * dev_list)7642 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7643 char *name,
7644 struct list_head *dev_list)
7645 {
7646 char linkname[IFNAMSIZ+7];
7647
7648 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7649 "upper_%s" : "lower_%s", name);
7650 sysfs_remove_link(&(dev->dev.kobj), linkname);
7651 }
7652
netdev_adjacent_is_neigh_list(struct net_device * dev,struct net_device * adj_dev,struct list_head * dev_list)7653 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7654 struct net_device *adj_dev,
7655 struct list_head *dev_list)
7656 {
7657 return (dev_list == &dev->adj_list.upper ||
7658 dev_list == &dev->adj_list.lower) &&
7659 net_eq(dev_net(dev), dev_net(adj_dev));
7660 }
7661
__netdev_adjacent_dev_insert(struct net_device * dev,struct net_device * adj_dev,struct list_head * dev_list,void * private,bool master)7662 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7663 struct net_device *adj_dev,
7664 struct list_head *dev_list,
7665 void *private, bool master)
7666 {
7667 struct netdev_adjacent *adj;
7668 int ret;
7669
7670 adj = __netdev_find_adj(adj_dev, dev_list);
7671
7672 if (adj) {
7673 adj->ref_nr += 1;
7674 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7675 dev->name, adj_dev->name, adj->ref_nr);
7676
7677 return 0;
7678 }
7679
7680 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7681 if (!adj)
7682 return -ENOMEM;
7683
7684 adj->dev = adj_dev;
7685 adj->master = master;
7686 adj->ref_nr = 1;
7687 adj->private = private;
7688 adj->ignore = false;
7689 dev_hold(adj_dev);
7690
7691 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7692 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7693
7694 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7695 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7696 if (ret)
7697 goto free_adj;
7698 }
7699
7700 /* Ensure that master link is always the first item in list. */
7701 if (master) {
7702 ret = sysfs_create_link(&(dev->dev.kobj),
7703 &(adj_dev->dev.kobj), "master");
7704 if (ret)
7705 goto remove_symlinks;
7706
7707 list_add_rcu(&adj->list, dev_list);
7708 } else {
7709 list_add_tail_rcu(&adj->list, dev_list);
7710 }
7711
7712 return 0;
7713
7714 remove_symlinks:
7715 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7716 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7717 free_adj:
7718 kfree(adj);
7719 dev_put(adj_dev);
7720
7721 return ret;
7722 }
7723
__netdev_adjacent_dev_remove(struct net_device * dev,struct net_device * adj_dev,u16 ref_nr,struct list_head * dev_list)7724 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7725 struct net_device *adj_dev,
7726 u16 ref_nr,
7727 struct list_head *dev_list)
7728 {
7729 struct netdev_adjacent *adj;
7730
7731 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7732 dev->name, adj_dev->name, ref_nr);
7733
7734 adj = __netdev_find_adj(adj_dev, dev_list);
7735
7736 if (!adj) {
7737 pr_err("Adjacency does not exist for device %s from %s\n",
7738 dev->name, adj_dev->name);
7739 WARN_ON(1);
7740 return;
7741 }
7742
7743 if (adj->ref_nr > ref_nr) {
7744 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7745 dev->name, adj_dev->name, ref_nr,
7746 adj->ref_nr - ref_nr);
7747 adj->ref_nr -= ref_nr;
7748 return;
7749 }
7750
7751 if (adj->master)
7752 sysfs_remove_link(&(dev->dev.kobj), "master");
7753
7754 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7755 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7756
7757 list_del_rcu(&adj->list);
7758 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7759 adj_dev->name, dev->name, adj_dev->name);
7760 dev_put(adj_dev);
7761 kfree_rcu(adj, rcu);
7762 }
7763
__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)7764 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7765 struct net_device *upper_dev,
7766 struct list_head *up_list,
7767 struct list_head *down_list,
7768 void *private, bool master)
7769 {
7770 int ret;
7771
7772 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7773 private, master);
7774 if (ret)
7775 return ret;
7776
7777 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7778 private, false);
7779 if (ret) {
7780 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7781 return ret;
7782 }
7783
7784 return 0;
7785 }
7786
__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)7787 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7788 struct net_device *upper_dev,
7789 u16 ref_nr,
7790 struct list_head *up_list,
7791 struct list_head *down_list)
7792 {
7793 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7794 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7795 }
7796
__netdev_adjacent_dev_link_neighbour(struct net_device * dev,struct net_device * upper_dev,void * private,bool master)7797 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7798 struct net_device *upper_dev,
7799 void *private, bool master)
7800 {
7801 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7802 &dev->adj_list.upper,
7803 &upper_dev->adj_list.lower,
7804 private, master);
7805 }
7806
__netdev_adjacent_dev_unlink_neighbour(struct net_device * dev,struct net_device * upper_dev)7807 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7808 struct net_device *upper_dev)
7809 {
7810 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7811 &dev->adj_list.upper,
7812 &upper_dev->adj_list.lower);
7813 }
7814
__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)7815 static int __netdev_upper_dev_link(struct net_device *dev,
7816 struct net_device *upper_dev, bool master,
7817 void *upper_priv, void *upper_info,
7818 struct netdev_nested_priv *priv,
7819 struct netlink_ext_ack *extack)
7820 {
7821 struct netdev_notifier_changeupper_info changeupper_info = {
7822 .info = {
7823 .dev = dev,
7824 .extack = extack,
7825 },
7826 .upper_dev = upper_dev,
7827 .master = master,
7828 .linking = true,
7829 .upper_info = upper_info,
7830 };
7831 struct net_device *master_dev;
7832 int ret = 0;
7833
7834 ASSERT_RTNL();
7835
7836 if (dev == upper_dev)
7837 return -EBUSY;
7838
7839 /* To prevent loops, check if dev is not upper device to upper_dev. */
7840 if (__netdev_has_upper_dev(upper_dev, dev))
7841 return -EBUSY;
7842
7843 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7844 return -EMLINK;
7845
7846 if (!master) {
7847 if (__netdev_has_upper_dev(dev, upper_dev))
7848 return -EEXIST;
7849 } else {
7850 master_dev = __netdev_master_upper_dev_get(dev);
7851 if (master_dev)
7852 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7853 }
7854
7855 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7856 &changeupper_info.info);
7857 ret = notifier_to_errno(ret);
7858 if (ret)
7859 return ret;
7860
7861 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7862 master);
7863 if (ret)
7864 return ret;
7865
7866 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7867 &changeupper_info.info);
7868 ret = notifier_to_errno(ret);
7869 if (ret)
7870 goto rollback;
7871
7872 __netdev_update_upper_level(dev, NULL);
7873 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7874
7875 __netdev_update_lower_level(upper_dev, priv);
7876 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7877 priv);
7878
7879 return 0;
7880
7881 rollback:
7882 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7883
7884 return ret;
7885 }
7886
7887 /**
7888 * netdev_upper_dev_link - Add a link to the upper device
7889 * @dev: device
7890 * @upper_dev: new upper device
7891 * @extack: netlink extended ack
7892 *
7893 * Adds a link to device which is upper to this one. The caller must hold
7894 * the RTNL lock. On a failure a negative errno code is returned.
7895 * On success the reference counts are adjusted and the function
7896 * returns zero.
7897 */
netdev_upper_dev_link(struct net_device * dev,struct net_device * upper_dev,struct netlink_ext_ack * extack)7898 int netdev_upper_dev_link(struct net_device *dev,
7899 struct net_device *upper_dev,
7900 struct netlink_ext_ack *extack)
7901 {
7902 struct netdev_nested_priv priv = {
7903 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7904 .data = NULL,
7905 };
7906
7907 return __netdev_upper_dev_link(dev, upper_dev, false,
7908 NULL, NULL, &priv, extack);
7909 }
7910 EXPORT_SYMBOL(netdev_upper_dev_link);
7911
7912 /**
7913 * netdev_master_upper_dev_link - Add a master link to the upper device
7914 * @dev: device
7915 * @upper_dev: new upper device
7916 * @upper_priv: upper device private
7917 * @upper_info: upper info to be passed down via notifier
7918 * @extack: netlink extended ack
7919 *
7920 * Adds a link to device which is upper to this one. In this case, only
7921 * one master upper device can be linked, although other non-master devices
7922 * might be linked as well. The caller must hold the RTNL lock.
7923 * On a failure a negative errno code is returned. On success the reference
7924 * counts are adjusted and the function returns zero.
7925 */
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)7926 int netdev_master_upper_dev_link(struct net_device *dev,
7927 struct net_device *upper_dev,
7928 void *upper_priv, void *upper_info,
7929 struct netlink_ext_ack *extack)
7930 {
7931 struct netdev_nested_priv priv = {
7932 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7933 .data = NULL,
7934 };
7935
7936 return __netdev_upper_dev_link(dev, upper_dev, true,
7937 upper_priv, upper_info, &priv, extack);
7938 }
7939 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7940
__netdev_upper_dev_unlink(struct net_device * dev,struct net_device * upper_dev,struct netdev_nested_priv * priv)7941 static void __netdev_upper_dev_unlink(struct net_device *dev,
7942 struct net_device *upper_dev,
7943 struct netdev_nested_priv *priv)
7944 {
7945 struct netdev_notifier_changeupper_info changeupper_info = {
7946 .info = {
7947 .dev = dev,
7948 },
7949 .upper_dev = upper_dev,
7950 .linking = false,
7951 };
7952
7953 ASSERT_RTNL();
7954
7955 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7956
7957 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7958 &changeupper_info.info);
7959
7960 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7961
7962 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7963 &changeupper_info.info);
7964
7965 __netdev_update_upper_level(dev, NULL);
7966 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7967
7968 __netdev_update_lower_level(upper_dev, priv);
7969 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7970 priv);
7971 }
7972
7973 /**
7974 * netdev_upper_dev_unlink - Removes a link to upper device
7975 * @dev: device
7976 * @upper_dev: new upper device
7977 *
7978 * Removes a link to device which is upper to this one. The caller must hold
7979 * the RTNL lock.
7980 */
netdev_upper_dev_unlink(struct net_device * dev,struct net_device * upper_dev)7981 void netdev_upper_dev_unlink(struct net_device *dev,
7982 struct net_device *upper_dev)
7983 {
7984 struct netdev_nested_priv priv = {
7985 .flags = NESTED_SYNC_TODO,
7986 .data = NULL,
7987 };
7988
7989 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
7990 }
7991 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7992
__netdev_adjacent_dev_set(struct net_device * upper_dev,struct net_device * lower_dev,bool val)7993 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7994 struct net_device *lower_dev,
7995 bool val)
7996 {
7997 struct netdev_adjacent *adj;
7998
7999 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
8000 if (adj)
8001 adj->ignore = val;
8002
8003 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
8004 if (adj)
8005 adj->ignore = val;
8006 }
8007
netdev_adjacent_dev_disable(struct net_device * upper_dev,struct net_device * lower_dev)8008 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
8009 struct net_device *lower_dev)
8010 {
8011 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
8012 }
8013
netdev_adjacent_dev_enable(struct net_device * upper_dev,struct net_device * lower_dev)8014 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
8015 struct net_device *lower_dev)
8016 {
8017 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
8018 }
8019
netdev_adjacent_change_prepare(struct net_device * old_dev,struct net_device * new_dev,struct net_device * dev,struct netlink_ext_ack * extack)8020 int netdev_adjacent_change_prepare(struct net_device *old_dev,
8021 struct net_device *new_dev,
8022 struct net_device *dev,
8023 struct netlink_ext_ack *extack)
8024 {
8025 struct netdev_nested_priv priv = {
8026 .flags = 0,
8027 .data = NULL,
8028 };
8029 int err;
8030
8031 if (!new_dev)
8032 return 0;
8033
8034 if (old_dev && new_dev != old_dev)
8035 netdev_adjacent_dev_disable(dev, old_dev);
8036 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
8037 extack);
8038 if (err) {
8039 if (old_dev && new_dev != old_dev)
8040 netdev_adjacent_dev_enable(dev, old_dev);
8041 return err;
8042 }
8043
8044 return 0;
8045 }
8046 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
8047
netdev_adjacent_change_commit(struct net_device * old_dev,struct net_device * new_dev,struct net_device * dev)8048 void netdev_adjacent_change_commit(struct net_device *old_dev,
8049 struct net_device *new_dev,
8050 struct net_device *dev)
8051 {
8052 struct netdev_nested_priv priv = {
8053 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
8054 .data = NULL,
8055 };
8056
8057 if (!new_dev || !old_dev)
8058 return;
8059
8060 if (new_dev == old_dev)
8061 return;
8062
8063 netdev_adjacent_dev_enable(dev, old_dev);
8064 __netdev_upper_dev_unlink(old_dev, dev, &priv);
8065 }
8066 EXPORT_SYMBOL(netdev_adjacent_change_commit);
8067
netdev_adjacent_change_abort(struct net_device * old_dev,struct net_device * new_dev,struct net_device * dev)8068 void netdev_adjacent_change_abort(struct net_device *old_dev,
8069 struct net_device *new_dev,
8070 struct net_device *dev)
8071 {
8072 struct netdev_nested_priv priv = {
8073 .flags = 0,
8074 .data = NULL,
8075 };
8076
8077 if (!new_dev)
8078 return;
8079
8080 if (old_dev && new_dev != old_dev)
8081 netdev_adjacent_dev_enable(dev, old_dev);
8082
8083 __netdev_upper_dev_unlink(new_dev, dev, &priv);
8084 }
8085 EXPORT_SYMBOL(netdev_adjacent_change_abort);
8086
8087 /**
8088 * netdev_bonding_info_change - Dispatch event about slave change
8089 * @dev: device
8090 * @bonding_info: info to dispatch
8091 *
8092 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
8093 * The caller must hold the RTNL lock.
8094 */
netdev_bonding_info_change(struct net_device * dev,struct netdev_bonding_info * bonding_info)8095 void netdev_bonding_info_change(struct net_device *dev,
8096 struct netdev_bonding_info *bonding_info)
8097 {
8098 struct netdev_notifier_bonding_info info = {
8099 .info.dev = dev,
8100 };
8101
8102 memcpy(&info.bonding_info, bonding_info,
8103 sizeof(struct netdev_bonding_info));
8104 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
8105 &info.info);
8106 }
8107 EXPORT_SYMBOL(netdev_bonding_info_change);
8108
8109 /**
8110 * netdev_get_xmit_slave - Get the xmit slave of master device
8111 * @dev: device
8112 * @skb: The packet
8113 * @all_slaves: assume all the slaves are active
8114 *
8115 * The reference counters are not incremented so the caller must be
8116 * careful with locks. The caller must hold RCU lock.
8117 * %NULL is returned if no slave is found.
8118 */
8119
netdev_get_xmit_slave(struct net_device * dev,struct sk_buff * skb,bool all_slaves)8120 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8121 struct sk_buff *skb,
8122 bool all_slaves)
8123 {
8124 const struct net_device_ops *ops = dev->netdev_ops;
8125
8126 if (!ops->ndo_get_xmit_slave)
8127 return NULL;
8128 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8129 }
8130 EXPORT_SYMBOL(netdev_get_xmit_slave);
8131
netdev_adjacent_add_links(struct net_device * dev)8132 static void netdev_adjacent_add_links(struct net_device *dev)
8133 {
8134 struct netdev_adjacent *iter;
8135
8136 struct net *net = dev_net(dev);
8137
8138 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8139 if (!net_eq(net, dev_net(iter->dev)))
8140 continue;
8141 netdev_adjacent_sysfs_add(iter->dev, dev,
8142 &iter->dev->adj_list.lower);
8143 netdev_adjacent_sysfs_add(dev, iter->dev,
8144 &dev->adj_list.upper);
8145 }
8146
8147 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8148 if (!net_eq(net, dev_net(iter->dev)))
8149 continue;
8150 netdev_adjacent_sysfs_add(iter->dev, dev,
8151 &iter->dev->adj_list.upper);
8152 netdev_adjacent_sysfs_add(dev, iter->dev,
8153 &dev->adj_list.lower);
8154 }
8155 }
8156
netdev_adjacent_del_links(struct net_device * dev)8157 static void netdev_adjacent_del_links(struct net_device *dev)
8158 {
8159 struct netdev_adjacent *iter;
8160
8161 struct net *net = dev_net(dev);
8162
8163 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8164 if (!net_eq(net, dev_net(iter->dev)))
8165 continue;
8166 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8167 &iter->dev->adj_list.lower);
8168 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8169 &dev->adj_list.upper);
8170 }
8171
8172 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8173 if (!net_eq(net, dev_net(iter->dev)))
8174 continue;
8175 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8176 &iter->dev->adj_list.upper);
8177 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8178 &dev->adj_list.lower);
8179 }
8180 }
8181
netdev_adjacent_rename_links(struct net_device * dev,char * oldname)8182 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8183 {
8184 struct netdev_adjacent *iter;
8185
8186 struct net *net = dev_net(dev);
8187
8188 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8189 if (!net_eq(net, dev_net(iter->dev)))
8190 continue;
8191 netdev_adjacent_sysfs_del(iter->dev, oldname,
8192 &iter->dev->adj_list.lower);
8193 netdev_adjacent_sysfs_add(iter->dev, dev,
8194 &iter->dev->adj_list.lower);
8195 }
8196
8197 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8198 if (!net_eq(net, dev_net(iter->dev)))
8199 continue;
8200 netdev_adjacent_sysfs_del(iter->dev, oldname,
8201 &iter->dev->adj_list.upper);
8202 netdev_adjacent_sysfs_add(iter->dev, dev,
8203 &iter->dev->adj_list.upper);
8204 }
8205 }
8206
netdev_lower_dev_get_private(struct net_device * dev,struct net_device * lower_dev)8207 void *netdev_lower_dev_get_private(struct net_device *dev,
8208 struct net_device *lower_dev)
8209 {
8210 struct netdev_adjacent *lower;
8211
8212 if (!lower_dev)
8213 return NULL;
8214 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8215 if (!lower)
8216 return NULL;
8217
8218 return lower->private;
8219 }
8220 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8221
8222
8223 /**
8224 * netdev_lower_change - Dispatch event about lower device state change
8225 * @lower_dev: device
8226 * @lower_state_info: state to dispatch
8227 *
8228 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8229 * The caller must hold the RTNL lock.
8230 */
netdev_lower_state_changed(struct net_device * lower_dev,void * lower_state_info)8231 void netdev_lower_state_changed(struct net_device *lower_dev,
8232 void *lower_state_info)
8233 {
8234 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8235 .info.dev = lower_dev,
8236 };
8237
8238 ASSERT_RTNL();
8239 changelowerstate_info.lower_state_info = lower_state_info;
8240 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8241 &changelowerstate_info.info);
8242 }
8243 EXPORT_SYMBOL(netdev_lower_state_changed);
8244
dev_change_rx_flags(struct net_device * dev,int flags)8245 static void dev_change_rx_flags(struct net_device *dev, int flags)
8246 {
8247 const struct net_device_ops *ops = dev->netdev_ops;
8248
8249 if (ops->ndo_change_rx_flags)
8250 ops->ndo_change_rx_flags(dev, flags);
8251 }
8252
__dev_set_promiscuity(struct net_device * dev,int inc,bool notify)8253 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8254 {
8255 unsigned int old_flags = dev->flags;
8256 kuid_t uid;
8257 kgid_t gid;
8258
8259 ASSERT_RTNL();
8260
8261 dev->flags |= IFF_PROMISC;
8262 dev->promiscuity += inc;
8263 if (dev->promiscuity == 0) {
8264 /*
8265 * Avoid overflow.
8266 * If inc causes overflow, untouch promisc and return error.
8267 */
8268 if (inc < 0)
8269 dev->flags &= ~IFF_PROMISC;
8270 else {
8271 dev->promiscuity -= inc;
8272 pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
8273 dev->name);
8274 return -EOVERFLOW;
8275 }
8276 }
8277 if (dev->flags != old_flags) {
8278 pr_info("device %s %s promiscuous mode\n",
8279 dev->name,
8280 dev->flags & IFF_PROMISC ? "entered" : "left");
8281 if (audit_enabled) {
8282 current_uid_gid(&uid, &gid);
8283 audit_log(audit_context(), GFP_ATOMIC,
8284 AUDIT_ANOM_PROMISCUOUS,
8285 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8286 dev->name, (dev->flags & IFF_PROMISC),
8287 (old_flags & IFF_PROMISC),
8288 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8289 from_kuid(&init_user_ns, uid),
8290 from_kgid(&init_user_ns, gid),
8291 audit_get_sessionid(current));
8292 }
8293
8294 dev_change_rx_flags(dev, IFF_PROMISC);
8295 }
8296 if (notify)
8297 __dev_notify_flags(dev, old_flags, IFF_PROMISC);
8298 return 0;
8299 }
8300
8301 /**
8302 * dev_set_promiscuity - update promiscuity count on a device
8303 * @dev: device
8304 * @inc: modifier
8305 *
8306 * Add or remove promiscuity from a device. While the count in the device
8307 * remains above zero the interface remains promiscuous. Once it hits zero
8308 * the device reverts back to normal filtering operation. A negative inc
8309 * value is used to drop promiscuity on the device.
8310 * Return 0 if successful or a negative errno code on error.
8311 */
dev_set_promiscuity(struct net_device * dev,int inc)8312 int dev_set_promiscuity(struct net_device *dev, int inc)
8313 {
8314 unsigned int old_flags = dev->flags;
8315 int err;
8316
8317 err = __dev_set_promiscuity(dev, inc, true);
8318 if (err < 0)
8319 return err;
8320 if (dev->flags != old_flags)
8321 dev_set_rx_mode(dev);
8322 return err;
8323 }
8324 EXPORT_SYMBOL(dev_set_promiscuity);
8325
__dev_set_allmulti(struct net_device * dev,int inc,bool notify)8326 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8327 {
8328 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8329
8330 ASSERT_RTNL();
8331
8332 dev->flags |= IFF_ALLMULTI;
8333 dev->allmulti += inc;
8334 if (dev->allmulti == 0) {
8335 /*
8336 * Avoid overflow.
8337 * If inc causes overflow, untouch allmulti and return error.
8338 */
8339 if (inc < 0)
8340 dev->flags &= ~IFF_ALLMULTI;
8341 else {
8342 dev->allmulti -= inc;
8343 pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
8344 dev->name);
8345 return -EOVERFLOW;
8346 }
8347 }
8348 if (dev->flags ^ old_flags) {
8349 dev_change_rx_flags(dev, IFF_ALLMULTI);
8350 dev_set_rx_mode(dev);
8351 if (notify)
8352 __dev_notify_flags(dev, old_flags,
8353 dev->gflags ^ old_gflags);
8354 }
8355 return 0;
8356 }
8357
8358 /**
8359 * dev_set_allmulti - update allmulti count on a device
8360 * @dev: device
8361 * @inc: modifier
8362 *
8363 * Add or remove reception of all multicast frames to a device. While the
8364 * count in the device remains above zero the interface remains listening
8365 * to all interfaces. Once it hits zero the device reverts back to normal
8366 * filtering operation. A negative @inc value is used to drop the counter
8367 * when releasing a resource needing all multicasts.
8368 * Return 0 if successful or a negative errno code on error.
8369 */
8370
dev_set_allmulti(struct net_device * dev,int inc)8371 int dev_set_allmulti(struct net_device *dev, int inc)
8372 {
8373 return __dev_set_allmulti(dev, inc, true);
8374 }
8375 EXPORT_SYMBOL(dev_set_allmulti);
8376
8377 /*
8378 * Upload unicast and multicast address lists to device and
8379 * configure RX filtering. When the device doesn't support unicast
8380 * filtering it is put in promiscuous mode while unicast addresses
8381 * are present.
8382 */
__dev_set_rx_mode(struct net_device * dev)8383 void __dev_set_rx_mode(struct net_device *dev)
8384 {
8385 const struct net_device_ops *ops = dev->netdev_ops;
8386
8387 /* dev_open will call this function so the list will stay sane. */
8388 if (!(dev->flags&IFF_UP))
8389 return;
8390
8391 if (!netif_device_present(dev))
8392 return;
8393
8394 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8395 /* Unicast addresses changes may only happen under the rtnl,
8396 * therefore calling __dev_set_promiscuity here is safe.
8397 */
8398 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8399 __dev_set_promiscuity(dev, 1, false);
8400 dev->uc_promisc = true;
8401 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8402 __dev_set_promiscuity(dev, -1, false);
8403 dev->uc_promisc = false;
8404 }
8405 }
8406
8407 if (ops->ndo_set_rx_mode)
8408 ops->ndo_set_rx_mode(dev);
8409 }
8410
dev_set_rx_mode(struct net_device * dev)8411 void dev_set_rx_mode(struct net_device *dev)
8412 {
8413 netif_addr_lock_bh(dev);
8414 __dev_set_rx_mode(dev);
8415 netif_addr_unlock_bh(dev);
8416 }
8417
8418 /**
8419 * dev_get_flags - get flags reported to userspace
8420 * @dev: device
8421 *
8422 * Get the combination of flag bits exported through APIs to userspace.
8423 */
dev_get_flags(const struct net_device * dev)8424 unsigned int dev_get_flags(const struct net_device *dev)
8425 {
8426 unsigned int flags;
8427
8428 flags = (dev->flags & ~(IFF_PROMISC |
8429 IFF_ALLMULTI |
8430 IFF_RUNNING |
8431 IFF_LOWER_UP |
8432 IFF_DORMANT)) |
8433 (dev->gflags & (IFF_PROMISC |
8434 IFF_ALLMULTI));
8435
8436 if (netif_running(dev)) {
8437 if (netif_oper_up(dev))
8438 flags |= IFF_RUNNING;
8439 if (netif_carrier_ok(dev))
8440 flags |= IFF_LOWER_UP;
8441 if (netif_dormant(dev))
8442 flags |= IFF_DORMANT;
8443 }
8444
8445 return flags;
8446 }
8447 EXPORT_SYMBOL(dev_get_flags);
8448
__dev_change_flags(struct net_device * dev,unsigned int flags,struct netlink_ext_ack * extack)8449 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8450 struct netlink_ext_ack *extack)
8451 {
8452 unsigned int old_flags = dev->flags;
8453 int ret;
8454
8455 ASSERT_RTNL();
8456
8457 /*
8458 * Set the flags on our device.
8459 */
8460
8461 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8462 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8463 IFF_AUTOMEDIA)) |
8464 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8465 IFF_ALLMULTI));
8466
8467 /*
8468 * Load in the correct multicast list now the flags have changed.
8469 */
8470
8471 if ((old_flags ^ flags) & IFF_MULTICAST)
8472 dev_change_rx_flags(dev, IFF_MULTICAST);
8473
8474 dev_set_rx_mode(dev);
8475
8476 /*
8477 * Have we downed the interface. We handle IFF_UP ourselves
8478 * according to user attempts to set it, rather than blindly
8479 * setting it.
8480 */
8481
8482 ret = 0;
8483 if ((old_flags ^ flags) & IFF_UP) {
8484 if (old_flags & IFF_UP)
8485 __dev_close(dev);
8486 else
8487 ret = __dev_open(dev, extack);
8488 }
8489
8490 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8491 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8492 unsigned int old_flags = dev->flags;
8493
8494 dev->gflags ^= IFF_PROMISC;
8495
8496 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8497 if (dev->flags != old_flags)
8498 dev_set_rx_mode(dev);
8499 }
8500
8501 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8502 * is important. Some (broken) drivers set IFF_PROMISC, when
8503 * IFF_ALLMULTI is requested not asking us and not reporting.
8504 */
8505 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8506 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8507
8508 dev->gflags ^= IFF_ALLMULTI;
8509 __dev_set_allmulti(dev, inc, false);
8510 }
8511
8512 return ret;
8513 }
8514
__dev_notify_flags(struct net_device * dev,unsigned int old_flags,unsigned int gchanges)8515 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8516 unsigned int gchanges)
8517 {
8518 unsigned int changes = dev->flags ^ old_flags;
8519
8520 if (gchanges)
8521 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
8522
8523 if (changes & IFF_UP) {
8524 if (dev->flags & IFF_UP)
8525 call_netdevice_notifiers(NETDEV_UP, dev);
8526 else
8527 call_netdevice_notifiers(NETDEV_DOWN, dev);
8528 }
8529
8530 if (dev->flags & IFF_UP &&
8531 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8532 struct netdev_notifier_change_info change_info = {
8533 .info = {
8534 .dev = dev,
8535 },
8536 .flags_changed = changes,
8537 };
8538
8539 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8540 }
8541 }
8542
8543 /**
8544 * dev_change_flags - change device settings
8545 * @dev: device
8546 * @flags: device state flags
8547 * @extack: netlink extended ack
8548 *
8549 * Change settings on device based state flags. The flags are
8550 * in the userspace exported format.
8551 */
dev_change_flags(struct net_device * dev,unsigned int flags,struct netlink_ext_ack * extack)8552 int dev_change_flags(struct net_device *dev, unsigned int flags,
8553 struct netlink_ext_ack *extack)
8554 {
8555 int ret;
8556 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8557
8558 ret = __dev_change_flags(dev, flags, extack);
8559 if (ret < 0)
8560 return ret;
8561
8562 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8563 __dev_notify_flags(dev, old_flags, changes);
8564 return ret;
8565 }
8566 EXPORT_SYMBOL(dev_change_flags);
8567
__dev_set_mtu(struct net_device * dev,int new_mtu)8568 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8569 {
8570 const struct net_device_ops *ops = dev->netdev_ops;
8571
8572 if (ops->ndo_change_mtu)
8573 return ops->ndo_change_mtu(dev, new_mtu);
8574
8575 /* Pairs with all the lockless reads of dev->mtu in the stack */
8576 WRITE_ONCE(dev->mtu, new_mtu);
8577 return 0;
8578 }
8579 EXPORT_SYMBOL(__dev_set_mtu);
8580
dev_validate_mtu(struct net_device * dev,int new_mtu,struct netlink_ext_ack * extack)8581 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8582 struct netlink_ext_ack *extack)
8583 {
8584 /* MTU must be positive, and in range */
8585 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8586 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8587 return -EINVAL;
8588 }
8589
8590 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8591 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8592 return -EINVAL;
8593 }
8594 return 0;
8595 }
8596
8597 /**
8598 * dev_set_mtu_ext - Change maximum transfer unit
8599 * @dev: device
8600 * @new_mtu: new transfer unit
8601 * @extack: netlink extended ack
8602 *
8603 * Change the maximum transfer size of the network device.
8604 */
dev_set_mtu_ext(struct net_device * dev,int new_mtu,struct netlink_ext_ack * extack)8605 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8606 struct netlink_ext_ack *extack)
8607 {
8608 int err, orig_mtu;
8609
8610 if (new_mtu == dev->mtu)
8611 return 0;
8612
8613 err = dev_validate_mtu(dev, new_mtu, extack);
8614 if (err)
8615 return err;
8616
8617 if (!netif_device_present(dev))
8618 return -ENODEV;
8619
8620 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8621 err = notifier_to_errno(err);
8622 if (err)
8623 return err;
8624
8625 orig_mtu = dev->mtu;
8626 err = __dev_set_mtu(dev, new_mtu);
8627
8628 if (!err) {
8629 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8630 orig_mtu);
8631 err = notifier_to_errno(err);
8632 if (err) {
8633 /* setting mtu back and notifying everyone again,
8634 * so that they have a chance to revert changes.
8635 */
8636 __dev_set_mtu(dev, orig_mtu);
8637 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8638 new_mtu);
8639 }
8640 }
8641 return err;
8642 }
8643
dev_set_mtu(struct net_device * dev,int new_mtu)8644 int dev_set_mtu(struct net_device *dev, int new_mtu)
8645 {
8646 struct netlink_ext_ack extack;
8647 int err;
8648
8649 memset(&extack, 0, sizeof(extack));
8650 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8651 if (err && extack._msg)
8652 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8653 return err;
8654 }
8655 EXPORT_SYMBOL(dev_set_mtu);
8656
8657 /**
8658 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8659 * @dev: device
8660 * @new_len: new tx queue length
8661 */
dev_change_tx_queue_len(struct net_device * dev,unsigned long new_len)8662 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8663 {
8664 unsigned int orig_len = dev->tx_queue_len;
8665 int res;
8666
8667 if (new_len != (unsigned int)new_len)
8668 return -ERANGE;
8669
8670 if (new_len != orig_len) {
8671 dev->tx_queue_len = new_len;
8672 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8673 res = notifier_to_errno(res);
8674 if (res)
8675 goto err_rollback;
8676 res = dev_qdisc_change_tx_queue_len(dev);
8677 if (res)
8678 goto err_rollback;
8679 }
8680
8681 return 0;
8682
8683 err_rollback:
8684 netdev_err(dev, "refused to change device tx_queue_len\n");
8685 dev->tx_queue_len = orig_len;
8686 return res;
8687 }
8688
8689 /**
8690 * dev_set_group - Change group this device belongs to
8691 * @dev: device
8692 * @new_group: group this device should belong to
8693 */
dev_set_group(struct net_device * dev,int new_group)8694 void dev_set_group(struct net_device *dev, int new_group)
8695 {
8696 dev->group = new_group;
8697 }
8698 EXPORT_SYMBOL(dev_set_group);
8699
8700 /**
8701 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8702 * @dev: device
8703 * @addr: new address
8704 * @extack: netlink extended ack
8705 */
dev_pre_changeaddr_notify(struct net_device * dev,const char * addr,struct netlink_ext_ack * extack)8706 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8707 struct netlink_ext_ack *extack)
8708 {
8709 struct netdev_notifier_pre_changeaddr_info info = {
8710 .info.dev = dev,
8711 .info.extack = extack,
8712 .dev_addr = addr,
8713 };
8714 int rc;
8715
8716 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8717 return notifier_to_errno(rc);
8718 }
8719 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8720
8721 /**
8722 * dev_set_mac_address - Change Media Access Control Address
8723 * @dev: device
8724 * @sa: new address
8725 * @extack: netlink extended ack
8726 *
8727 * Change the hardware (MAC) address of the device
8728 */
dev_set_mac_address(struct net_device * dev,struct sockaddr * sa,struct netlink_ext_ack * extack)8729 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8730 struct netlink_ext_ack *extack)
8731 {
8732 const struct net_device_ops *ops = dev->netdev_ops;
8733 int err;
8734
8735 if (!ops->ndo_set_mac_address)
8736 return -EOPNOTSUPP;
8737 if (sa->sa_family != dev->type)
8738 return -EINVAL;
8739 if (!netif_device_present(dev))
8740 return -ENODEV;
8741 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8742 if (err)
8743 return err;
8744 err = ops->ndo_set_mac_address(dev, sa);
8745 if (err)
8746 return err;
8747 dev->addr_assign_type = NET_ADDR_SET;
8748 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8749 add_device_randomness(dev->dev_addr, dev->addr_len);
8750 return 0;
8751 }
8752 EXPORT_SYMBOL(dev_set_mac_address);
8753
8754 static DECLARE_RWSEM(dev_addr_sem);
8755
dev_set_mac_address_user(struct net_device * dev,struct sockaddr * sa,struct netlink_ext_ack * extack)8756 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
8757 struct netlink_ext_ack *extack)
8758 {
8759 int ret;
8760
8761 down_write(&dev_addr_sem);
8762 ret = dev_set_mac_address(dev, sa, extack);
8763 up_write(&dev_addr_sem);
8764 return ret;
8765 }
8766 EXPORT_SYMBOL(dev_set_mac_address_user);
8767
dev_get_mac_address(struct sockaddr * sa,struct net * net,char * dev_name)8768 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
8769 {
8770 size_t size = sizeof(sa->sa_data);
8771 struct net_device *dev;
8772 int ret = 0;
8773
8774 down_read(&dev_addr_sem);
8775 rcu_read_lock();
8776
8777 dev = dev_get_by_name_rcu(net, dev_name);
8778 if (!dev) {
8779 ret = -ENODEV;
8780 goto unlock;
8781 }
8782 if (!dev->addr_len)
8783 memset(sa->sa_data, 0, size);
8784 else
8785 memcpy(sa->sa_data, dev->dev_addr,
8786 min_t(size_t, size, dev->addr_len));
8787 sa->sa_family = dev->type;
8788
8789 unlock:
8790 rcu_read_unlock();
8791 up_read(&dev_addr_sem);
8792 return ret;
8793 }
8794 EXPORT_SYMBOL(dev_get_mac_address);
8795
8796 /**
8797 * dev_change_carrier - Change device carrier
8798 * @dev: device
8799 * @new_carrier: new value
8800 *
8801 * Change device carrier
8802 */
dev_change_carrier(struct net_device * dev,bool new_carrier)8803 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8804 {
8805 const struct net_device_ops *ops = dev->netdev_ops;
8806
8807 if (!ops->ndo_change_carrier)
8808 return -EOPNOTSUPP;
8809 if (!netif_device_present(dev))
8810 return -ENODEV;
8811 return ops->ndo_change_carrier(dev, new_carrier);
8812 }
8813 EXPORT_SYMBOL(dev_change_carrier);
8814
8815 /**
8816 * dev_get_phys_port_id - Get device physical port ID
8817 * @dev: device
8818 * @ppid: port ID
8819 *
8820 * Get device physical port ID
8821 */
dev_get_phys_port_id(struct net_device * dev,struct netdev_phys_item_id * ppid)8822 int dev_get_phys_port_id(struct net_device *dev,
8823 struct netdev_phys_item_id *ppid)
8824 {
8825 const struct net_device_ops *ops = dev->netdev_ops;
8826
8827 if (!ops->ndo_get_phys_port_id)
8828 return -EOPNOTSUPP;
8829 return ops->ndo_get_phys_port_id(dev, ppid);
8830 }
8831 EXPORT_SYMBOL(dev_get_phys_port_id);
8832
8833 /**
8834 * dev_get_phys_port_name - Get device physical port name
8835 * @dev: device
8836 * @name: port name
8837 * @len: limit of bytes to copy to name
8838 *
8839 * Get device physical port name
8840 */
dev_get_phys_port_name(struct net_device * dev,char * name,size_t len)8841 int dev_get_phys_port_name(struct net_device *dev,
8842 char *name, size_t len)
8843 {
8844 const struct net_device_ops *ops = dev->netdev_ops;
8845 int err;
8846
8847 if (ops->ndo_get_phys_port_name) {
8848 err = ops->ndo_get_phys_port_name(dev, name, len);
8849 if (err != -EOPNOTSUPP)
8850 return err;
8851 }
8852 return devlink_compat_phys_port_name_get(dev, name, len);
8853 }
8854 EXPORT_SYMBOL(dev_get_phys_port_name);
8855
8856 /**
8857 * dev_get_port_parent_id - Get the device's port parent identifier
8858 * @dev: network device
8859 * @ppid: pointer to a storage for the port's parent identifier
8860 * @recurse: allow/disallow recursion to lower devices
8861 *
8862 * Get the devices's port parent identifier
8863 */
dev_get_port_parent_id(struct net_device * dev,struct netdev_phys_item_id * ppid,bool recurse)8864 int dev_get_port_parent_id(struct net_device *dev,
8865 struct netdev_phys_item_id *ppid,
8866 bool recurse)
8867 {
8868 const struct net_device_ops *ops = dev->netdev_ops;
8869 struct netdev_phys_item_id first = { };
8870 struct net_device *lower_dev;
8871 struct list_head *iter;
8872 int err;
8873
8874 if (ops->ndo_get_port_parent_id) {
8875 err = ops->ndo_get_port_parent_id(dev, ppid);
8876 if (err != -EOPNOTSUPP)
8877 return err;
8878 }
8879
8880 err = devlink_compat_switch_id_get(dev, ppid);
8881 if (!err || err != -EOPNOTSUPP)
8882 return err;
8883
8884 if (!recurse)
8885 return -EOPNOTSUPP;
8886
8887 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8888 err = dev_get_port_parent_id(lower_dev, ppid, recurse);
8889 if (err)
8890 break;
8891 if (!first.id_len)
8892 first = *ppid;
8893 else if (memcmp(&first, ppid, sizeof(*ppid)))
8894 return -EOPNOTSUPP;
8895 }
8896
8897 return err;
8898 }
8899 EXPORT_SYMBOL(dev_get_port_parent_id);
8900
8901 /**
8902 * netdev_port_same_parent_id - Indicate if two network devices have
8903 * the same port parent identifier
8904 * @a: first network device
8905 * @b: second network device
8906 */
netdev_port_same_parent_id(struct net_device * a,struct net_device * b)8907 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
8908 {
8909 struct netdev_phys_item_id a_id = { };
8910 struct netdev_phys_item_id b_id = { };
8911
8912 if (dev_get_port_parent_id(a, &a_id, true) ||
8913 dev_get_port_parent_id(b, &b_id, true))
8914 return false;
8915
8916 return netdev_phys_item_id_same(&a_id, &b_id);
8917 }
8918 EXPORT_SYMBOL(netdev_port_same_parent_id);
8919
8920 /**
8921 * dev_change_proto_down - update protocol port state information
8922 * @dev: device
8923 * @proto_down: new value
8924 *
8925 * This info can be used by switch drivers to set the phys state of the
8926 * port.
8927 */
dev_change_proto_down(struct net_device * dev,bool proto_down)8928 int dev_change_proto_down(struct net_device *dev, bool proto_down)
8929 {
8930 const struct net_device_ops *ops = dev->netdev_ops;
8931
8932 if (!ops->ndo_change_proto_down)
8933 return -EOPNOTSUPP;
8934 if (!netif_device_present(dev))
8935 return -ENODEV;
8936 return ops->ndo_change_proto_down(dev, proto_down);
8937 }
8938 EXPORT_SYMBOL(dev_change_proto_down);
8939
8940 /**
8941 * dev_change_proto_down_generic - generic implementation for
8942 * ndo_change_proto_down that sets carrier according to
8943 * proto_down.
8944 *
8945 * @dev: device
8946 * @proto_down: new value
8947 */
dev_change_proto_down_generic(struct net_device * dev,bool proto_down)8948 int dev_change_proto_down_generic(struct net_device *dev, bool proto_down)
8949 {
8950 if (proto_down)
8951 netif_carrier_off(dev);
8952 else
8953 netif_carrier_on(dev);
8954 dev->proto_down = proto_down;
8955 return 0;
8956 }
8957 EXPORT_SYMBOL(dev_change_proto_down_generic);
8958
8959 /**
8960 * dev_change_proto_down_reason - proto down reason
8961 *
8962 * @dev: device
8963 * @mask: proto down mask
8964 * @value: proto down value
8965 */
dev_change_proto_down_reason(struct net_device * dev,unsigned long mask,u32 value)8966 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
8967 u32 value)
8968 {
8969 int b;
8970
8971 if (!mask) {
8972 dev->proto_down_reason = value;
8973 } else {
8974 for_each_set_bit(b, &mask, 32) {
8975 if (value & (1 << b))
8976 dev->proto_down_reason |= BIT(b);
8977 else
8978 dev->proto_down_reason &= ~BIT(b);
8979 }
8980 }
8981 }
8982 EXPORT_SYMBOL(dev_change_proto_down_reason);
8983
8984 struct bpf_xdp_link {
8985 struct bpf_link link;
8986 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
8987 int flags;
8988 };
8989
dev_xdp_mode(struct net_device * dev,u32 flags)8990 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
8991 {
8992 if (flags & XDP_FLAGS_HW_MODE)
8993 return XDP_MODE_HW;
8994 if (flags & XDP_FLAGS_DRV_MODE)
8995 return XDP_MODE_DRV;
8996 if (flags & XDP_FLAGS_SKB_MODE)
8997 return XDP_MODE_SKB;
8998 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
8999 }
9000
dev_xdp_bpf_op(struct net_device * dev,enum bpf_xdp_mode mode)9001 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
9002 {
9003 switch (mode) {
9004 case XDP_MODE_SKB:
9005 return generic_xdp_install;
9006 case XDP_MODE_DRV:
9007 case XDP_MODE_HW:
9008 return dev->netdev_ops->ndo_bpf;
9009 default:
9010 return NULL;
9011 };
9012 }
9013
dev_xdp_link(struct net_device * dev,enum bpf_xdp_mode mode)9014 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
9015 enum bpf_xdp_mode mode)
9016 {
9017 return dev->xdp_state[mode].link;
9018 }
9019
dev_xdp_prog(struct net_device * dev,enum bpf_xdp_mode mode)9020 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
9021 enum bpf_xdp_mode mode)
9022 {
9023 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
9024
9025 if (link)
9026 return link->link.prog;
9027 return dev->xdp_state[mode].prog;
9028 }
9029
dev_xdp_prog_count(struct net_device * dev)9030 static u8 dev_xdp_prog_count(struct net_device *dev)
9031 {
9032 u8 count = 0;
9033 int i;
9034
9035 for (i = 0; i < __MAX_XDP_MODE; i++)
9036 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
9037 count++;
9038 return count;
9039 }
9040
dev_xdp_prog_id(struct net_device * dev,enum bpf_xdp_mode mode)9041 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
9042 {
9043 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
9044
9045 return prog ? prog->aux->id : 0;
9046 }
9047
dev_xdp_set_link(struct net_device * dev,enum bpf_xdp_mode mode,struct bpf_xdp_link * link)9048 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
9049 struct bpf_xdp_link *link)
9050 {
9051 dev->xdp_state[mode].link = link;
9052 dev->xdp_state[mode].prog = NULL;
9053 }
9054
dev_xdp_set_prog(struct net_device * dev,enum bpf_xdp_mode mode,struct bpf_prog * prog)9055 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
9056 struct bpf_prog *prog)
9057 {
9058 dev->xdp_state[mode].link = NULL;
9059 dev->xdp_state[mode].prog = prog;
9060 }
9061
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)9062 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
9063 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
9064 u32 flags, struct bpf_prog *prog)
9065 {
9066 struct netdev_bpf xdp;
9067 int err;
9068
9069 memset(&xdp, 0, sizeof(xdp));
9070 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
9071 xdp.extack = extack;
9072 xdp.flags = flags;
9073 xdp.prog = prog;
9074
9075 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
9076 * "moved" into driver), so they don't increment it on their own, but
9077 * they do decrement refcnt when program is detached or replaced.
9078 * Given net_device also owns link/prog, we need to bump refcnt here
9079 * to prevent drivers from underflowing it.
9080 */
9081 if (prog)
9082 bpf_prog_inc(prog);
9083 err = bpf_op(dev, &xdp);
9084 if (err) {
9085 if (prog)
9086 bpf_prog_put(prog);
9087 return err;
9088 }
9089
9090 if (mode != XDP_MODE_HW)
9091 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9092
9093 return 0;
9094 }
9095
dev_xdp_uninstall(struct net_device * dev)9096 static void dev_xdp_uninstall(struct net_device *dev)
9097 {
9098 struct bpf_xdp_link *link;
9099 struct bpf_prog *prog;
9100 enum bpf_xdp_mode mode;
9101 bpf_op_t bpf_op;
9102
9103 ASSERT_RTNL();
9104
9105 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9106 prog = dev_xdp_prog(dev, mode);
9107 if (!prog)
9108 continue;
9109
9110 bpf_op = dev_xdp_bpf_op(dev, mode);
9111 if (!bpf_op)
9112 continue;
9113
9114 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9115
9116 /* auto-detach link from net device */
9117 link = dev_xdp_link(dev, mode);
9118 if (link)
9119 link->dev = NULL;
9120 else
9121 bpf_prog_put(prog);
9122
9123 dev_xdp_set_link(dev, mode, NULL);
9124 }
9125 }
9126
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)9127 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9128 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9129 struct bpf_prog *old_prog, u32 flags)
9130 {
9131 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9132 struct bpf_prog *cur_prog;
9133 enum bpf_xdp_mode mode;
9134 bpf_op_t bpf_op;
9135 int err;
9136
9137 ASSERT_RTNL();
9138
9139 /* either link or prog attachment, never both */
9140 if (link && (new_prog || old_prog))
9141 return -EINVAL;
9142 /* link supports only XDP mode flags */
9143 if (link && (flags & ~XDP_FLAGS_MODES)) {
9144 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9145 return -EINVAL;
9146 }
9147 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9148 if (num_modes > 1) {
9149 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9150 return -EINVAL;
9151 }
9152 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9153 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9154 NL_SET_ERR_MSG(extack,
9155 "More than one program loaded, unset mode is ambiguous");
9156 return -EINVAL;
9157 }
9158 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9159 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9160 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9161 return -EINVAL;
9162 }
9163
9164 mode = dev_xdp_mode(dev, flags);
9165 /* can't replace attached link */
9166 if (dev_xdp_link(dev, mode)) {
9167 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9168 return -EBUSY;
9169 }
9170
9171 cur_prog = dev_xdp_prog(dev, mode);
9172 /* can't replace attached prog with link */
9173 if (link && cur_prog) {
9174 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9175 return -EBUSY;
9176 }
9177 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9178 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9179 return -EEXIST;
9180 }
9181
9182 /* put effective new program into new_prog */
9183 if (link)
9184 new_prog = link->link.prog;
9185
9186 if (new_prog) {
9187 bool offload = mode == XDP_MODE_HW;
9188 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9189 ? XDP_MODE_DRV : XDP_MODE_SKB;
9190
9191 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9192 NL_SET_ERR_MSG(extack, "XDP program already attached");
9193 return -EBUSY;
9194 }
9195 if (!offload && dev_xdp_prog(dev, other_mode)) {
9196 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9197 return -EEXIST;
9198 }
9199 if (!offload && bpf_prog_is_dev_bound(new_prog->aux)) {
9200 NL_SET_ERR_MSG(extack, "Using device-bound program without HW_MODE flag is not supported");
9201 return -EINVAL;
9202 }
9203 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9204 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9205 return -EINVAL;
9206 }
9207 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9208 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9209 return -EINVAL;
9210 }
9211 }
9212
9213 /* don't call drivers if the effective program didn't change */
9214 if (new_prog != cur_prog) {
9215 bpf_op = dev_xdp_bpf_op(dev, mode);
9216 if (!bpf_op) {
9217 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9218 return -EOPNOTSUPP;
9219 }
9220
9221 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9222 if (err)
9223 return err;
9224 }
9225
9226 if (link)
9227 dev_xdp_set_link(dev, mode, link);
9228 else
9229 dev_xdp_set_prog(dev, mode, new_prog);
9230 if (cur_prog)
9231 bpf_prog_put(cur_prog);
9232
9233 return 0;
9234 }
9235
dev_xdp_attach_link(struct net_device * dev,struct netlink_ext_ack * extack,struct bpf_xdp_link * link)9236 static int dev_xdp_attach_link(struct net_device *dev,
9237 struct netlink_ext_ack *extack,
9238 struct bpf_xdp_link *link)
9239 {
9240 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9241 }
9242
dev_xdp_detach_link(struct net_device * dev,struct netlink_ext_ack * extack,struct bpf_xdp_link * link)9243 static int dev_xdp_detach_link(struct net_device *dev,
9244 struct netlink_ext_ack *extack,
9245 struct bpf_xdp_link *link)
9246 {
9247 enum bpf_xdp_mode mode;
9248 bpf_op_t bpf_op;
9249
9250 ASSERT_RTNL();
9251
9252 mode = dev_xdp_mode(dev, link->flags);
9253 if (dev_xdp_link(dev, mode) != link)
9254 return -EINVAL;
9255
9256 bpf_op = dev_xdp_bpf_op(dev, mode);
9257 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9258 dev_xdp_set_link(dev, mode, NULL);
9259 return 0;
9260 }
9261
bpf_xdp_link_release(struct bpf_link * link)9262 static void bpf_xdp_link_release(struct bpf_link *link)
9263 {
9264 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9265
9266 rtnl_lock();
9267
9268 /* if racing with net_device's tear down, xdp_link->dev might be
9269 * already NULL, in which case link was already auto-detached
9270 */
9271 if (xdp_link->dev) {
9272 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9273 xdp_link->dev = NULL;
9274 }
9275
9276 rtnl_unlock();
9277 }
9278
bpf_xdp_link_detach(struct bpf_link * link)9279 static int bpf_xdp_link_detach(struct bpf_link *link)
9280 {
9281 bpf_xdp_link_release(link);
9282 return 0;
9283 }
9284
bpf_xdp_link_dealloc(struct bpf_link * link)9285 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9286 {
9287 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9288
9289 kfree(xdp_link);
9290 }
9291
bpf_xdp_link_show_fdinfo(const struct bpf_link * link,struct seq_file * seq)9292 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9293 struct seq_file *seq)
9294 {
9295 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9296 u32 ifindex = 0;
9297
9298 rtnl_lock();
9299 if (xdp_link->dev)
9300 ifindex = xdp_link->dev->ifindex;
9301 rtnl_unlock();
9302
9303 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9304 }
9305
bpf_xdp_link_fill_link_info(const struct bpf_link * link,struct bpf_link_info * info)9306 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9307 struct bpf_link_info *info)
9308 {
9309 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9310 u32 ifindex = 0;
9311
9312 rtnl_lock();
9313 if (xdp_link->dev)
9314 ifindex = xdp_link->dev->ifindex;
9315 rtnl_unlock();
9316
9317 info->xdp.ifindex = ifindex;
9318 return 0;
9319 }
9320
bpf_xdp_link_update(struct bpf_link * link,struct bpf_prog * new_prog,struct bpf_prog * old_prog)9321 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9322 struct bpf_prog *old_prog)
9323 {
9324 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9325 enum bpf_xdp_mode mode;
9326 bpf_op_t bpf_op;
9327 int err = 0;
9328
9329 rtnl_lock();
9330
9331 /* link might have been auto-released already, so fail */
9332 if (!xdp_link->dev) {
9333 err = -ENOLINK;
9334 goto out_unlock;
9335 }
9336
9337 if (old_prog && link->prog != old_prog) {
9338 err = -EPERM;
9339 goto out_unlock;
9340 }
9341 old_prog = link->prog;
9342 if (old_prog->type != new_prog->type ||
9343 old_prog->expected_attach_type != new_prog->expected_attach_type) {
9344 err = -EINVAL;
9345 goto out_unlock;
9346 }
9347
9348 if (old_prog == new_prog) {
9349 /* no-op, don't disturb drivers */
9350 bpf_prog_put(new_prog);
9351 goto out_unlock;
9352 }
9353
9354 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9355 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9356 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9357 xdp_link->flags, new_prog);
9358 if (err)
9359 goto out_unlock;
9360
9361 old_prog = xchg(&link->prog, new_prog);
9362 bpf_prog_put(old_prog);
9363
9364 out_unlock:
9365 rtnl_unlock();
9366 return err;
9367 }
9368
9369 static const struct bpf_link_ops bpf_xdp_link_lops = {
9370 .release = bpf_xdp_link_release,
9371 .dealloc = bpf_xdp_link_dealloc,
9372 .detach = bpf_xdp_link_detach,
9373 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9374 .fill_link_info = bpf_xdp_link_fill_link_info,
9375 .update_prog = bpf_xdp_link_update,
9376 };
9377
bpf_xdp_link_attach(const union bpf_attr * attr,struct bpf_prog * prog)9378 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9379 {
9380 struct net *net = current->nsproxy->net_ns;
9381 struct bpf_link_primer link_primer;
9382 struct bpf_xdp_link *link;
9383 struct net_device *dev;
9384 int err, fd;
9385
9386 rtnl_lock();
9387 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9388 if (!dev) {
9389 rtnl_unlock();
9390 return -EINVAL;
9391 }
9392
9393 link = kzalloc(sizeof(*link), GFP_USER);
9394 if (!link) {
9395 err = -ENOMEM;
9396 goto unlock;
9397 }
9398
9399 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9400 link->dev = dev;
9401 link->flags = attr->link_create.flags;
9402
9403 err = bpf_link_prime(&link->link, &link_primer);
9404 if (err) {
9405 kfree(link);
9406 goto unlock;
9407 }
9408
9409 err = dev_xdp_attach_link(dev, NULL, link);
9410 rtnl_unlock();
9411
9412 if (err) {
9413 link->dev = NULL;
9414 bpf_link_cleanup(&link_primer);
9415 goto out_put_dev;
9416 }
9417
9418 fd = bpf_link_settle(&link_primer);
9419 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9420 dev_put(dev);
9421 return fd;
9422
9423 unlock:
9424 rtnl_unlock();
9425
9426 out_put_dev:
9427 dev_put(dev);
9428 return err;
9429 }
9430
9431 /**
9432 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9433 * @dev: device
9434 * @extack: netlink extended ack
9435 * @fd: new program fd or negative value to clear
9436 * @expected_fd: old program fd that userspace expects to replace or clear
9437 * @flags: xdp-related flags
9438 *
9439 * Set or clear a bpf program for a device
9440 */
dev_change_xdp_fd(struct net_device * dev,struct netlink_ext_ack * extack,int fd,int expected_fd,u32 flags)9441 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9442 int fd, int expected_fd, u32 flags)
9443 {
9444 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9445 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9446 int err;
9447
9448 ASSERT_RTNL();
9449
9450 if (fd >= 0) {
9451 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9452 mode != XDP_MODE_SKB);
9453 if (IS_ERR(new_prog))
9454 return PTR_ERR(new_prog);
9455 }
9456
9457 if (expected_fd >= 0) {
9458 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9459 mode != XDP_MODE_SKB);
9460 if (IS_ERR(old_prog)) {
9461 err = PTR_ERR(old_prog);
9462 old_prog = NULL;
9463 goto err_out;
9464 }
9465 }
9466
9467 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9468
9469 err_out:
9470 if (err && new_prog)
9471 bpf_prog_put(new_prog);
9472 if (old_prog)
9473 bpf_prog_put(old_prog);
9474 return err;
9475 }
9476
9477 /**
9478 * dev_new_index - allocate an ifindex
9479 * @net: the applicable net namespace
9480 *
9481 * Returns a suitable unique value for a new device interface
9482 * number. The caller must hold the rtnl semaphore or the
9483 * dev_base_lock to be sure it remains unique.
9484 */
dev_new_index(struct net * net)9485 static int dev_new_index(struct net *net)
9486 {
9487 int ifindex = net->ifindex;
9488
9489 for (;;) {
9490 if (++ifindex <= 0)
9491 ifindex = 1;
9492 if (!__dev_get_by_index(net, ifindex))
9493 return net->ifindex = ifindex;
9494 }
9495 }
9496
9497 /* Delayed registration/unregisteration */
9498 static LIST_HEAD(net_todo_list);
9499 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9500
net_set_todo(struct net_device * dev)9501 static void net_set_todo(struct net_device *dev)
9502 {
9503 list_add_tail(&dev->todo_list, &net_todo_list);
9504 dev_net(dev)->dev_unreg_count++;
9505 }
9506
rollback_registered_many(struct list_head * head)9507 static void rollback_registered_many(struct list_head *head)
9508 {
9509 struct net_device *dev, *tmp;
9510 LIST_HEAD(close_head);
9511
9512 BUG_ON(dev_boot_phase);
9513 ASSERT_RTNL();
9514
9515 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
9516 /* Some devices call without registering
9517 * for initialization unwind. Remove those
9518 * devices and proceed with the remaining.
9519 */
9520 if (dev->reg_state == NETREG_UNINITIALIZED) {
9521 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
9522 dev->name, dev);
9523
9524 WARN_ON(1);
9525 list_del(&dev->unreg_list);
9526 continue;
9527 }
9528 dev->dismantle = true;
9529 BUG_ON(dev->reg_state != NETREG_REGISTERED);
9530 }
9531
9532 /* If device is running, close it first. */
9533 list_for_each_entry(dev, head, unreg_list)
9534 list_add_tail(&dev->close_list, &close_head);
9535 dev_close_many(&close_head, true);
9536
9537 list_for_each_entry(dev, head, unreg_list) {
9538 /* And unlink it from device chain. */
9539 unlist_netdevice(dev);
9540
9541 dev->reg_state = NETREG_UNREGISTERING;
9542 }
9543 flush_all_backlogs();
9544
9545 synchronize_net();
9546
9547 list_for_each_entry(dev, head, unreg_list) {
9548 struct sk_buff *skb = NULL;
9549
9550 /* Shutdown queueing discipline. */
9551 dev_shutdown(dev);
9552
9553 dev_xdp_uninstall(dev);
9554
9555 /* Notify protocols, that we are about to destroy
9556 * this device. They should clean all the things.
9557 */
9558 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
9559
9560 if (!dev->rtnl_link_ops ||
9561 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
9562 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
9563 GFP_KERNEL, NULL, 0);
9564
9565 /*
9566 * Flush the unicast and multicast chains
9567 */
9568 dev_uc_flush(dev);
9569 dev_mc_flush(dev);
9570
9571 netdev_name_node_alt_flush(dev);
9572 netdev_name_node_free(dev->name_node);
9573
9574 if (dev->netdev_ops->ndo_uninit)
9575 dev->netdev_ops->ndo_uninit(dev);
9576
9577 if (skb)
9578 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
9579
9580 /* Notifier chain MUST detach us all upper devices. */
9581 WARN_ON(netdev_has_any_upper_dev(dev));
9582 WARN_ON(netdev_has_any_lower_dev(dev));
9583
9584 /* Remove entries from kobject tree */
9585 netdev_unregister_kobject(dev);
9586 #ifdef CONFIG_XPS
9587 /* Remove XPS queueing entries */
9588 netif_reset_xps_queues_gt(dev, 0);
9589 #endif
9590 }
9591
9592 synchronize_net();
9593
9594 list_for_each_entry(dev, head, unreg_list)
9595 dev_put(dev);
9596 }
9597
rollback_registered(struct net_device * dev)9598 static void rollback_registered(struct net_device *dev)
9599 {
9600 LIST_HEAD(single);
9601
9602 list_add(&dev->unreg_list, &single);
9603 rollback_registered_many(&single);
9604 list_del(&single);
9605 }
9606
netdev_sync_upper_features(struct net_device * lower,struct net_device * upper,netdev_features_t features)9607 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9608 struct net_device *upper, netdev_features_t features)
9609 {
9610 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9611 netdev_features_t feature;
9612 int feature_bit;
9613
9614 for_each_netdev_feature(upper_disables, feature_bit) {
9615 feature = __NETIF_F_BIT(feature_bit);
9616 if (!(upper->wanted_features & feature)
9617 && (features & feature)) {
9618 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9619 &feature, upper->name);
9620 features &= ~feature;
9621 }
9622 }
9623
9624 return features;
9625 }
9626
netdev_sync_lower_features(struct net_device * upper,struct net_device * lower,netdev_features_t features)9627 static void netdev_sync_lower_features(struct net_device *upper,
9628 struct net_device *lower, netdev_features_t features)
9629 {
9630 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9631 netdev_features_t feature;
9632 int feature_bit;
9633
9634 for_each_netdev_feature(upper_disables, feature_bit) {
9635 feature = __NETIF_F_BIT(feature_bit);
9636 if (!(features & feature) && (lower->features & feature)) {
9637 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9638 &feature, lower->name);
9639 lower->wanted_features &= ~feature;
9640 __netdev_update_features(lower);
9641
9642 if (unlikely(lower->features & feature))
9643 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9644 &feature, lower->name);
9645 else
9646 netdev_features_change(lower);
9647 }
9648 }
9649 }
9650
netdev_fix_features(struct net_device * dev,netdev_features_t features)9651 static netdev_features_t netdev_fix_features(struct net_device *dev,
9652 netdev_features_t features)
9653 {
9654 /* Fix illegal checksum combinations */
9655 if ((features & NETIF_F_HW_CSUM) &&
9656 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9657 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9658 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9659 }
9660
9661 /* TSO requires that SG is present as well. */
9662 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9663 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9664 features &= ~NETIF_F_ALL_TSO;
9665 }
9666
9667 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9668 !(features & NETIF_F_IP_CSUM)) {
9669 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9670 features &= ~NETIF_F_TSO;
9671 features &= ~NETIF_F_TSO_ECN;
9672 }
9673
9674 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9675 !(features & NETIF_F_IPV6_CSUM)) {
9676 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9677 features &= ~NETIF_F_TSO6;
9678 }
9679
9680 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9681 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9682 features &= ~NETIF_F_TSO_MANGLEID;
9683
9684 /* TSO ECN requires that TSO is present as well. */
9685 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9686 features &= ~NETIF_F_TSO_ECN;
9687
9688 /* Software GSO depends on SG. */
9689 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9690 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9691 features &= ~NETIF_F_GSO;
9692 }
9693
9694 /* GSO partial features require GSO partial be set */
9695 if ((features & dev->gso_partial_features) &&
9696 !(features & NETIF_F_GSO_PARTIAL)) {
9697 netdev_dbg(dev,
9698 "Dropping partially supported GSO features since no GSO partial.\n");
9699 features &= ~dev->gso_partial_features;
9700 }
9701
9702 if (!(features & NETIF_F_RXCSUM)) {
9703 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9704 * successfully merged by hardware must also have the
9705 * checksum verified by hardware. If the user does not
9706 * want to enable RXCSUM, logically, we should disable GRO_HW.
9707 */
9708 if (features & NETIF_F_GRO_HW) {
9709 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9710 features &= ~NETIF_F_GRO_HW;
9711 }
9712 }
9713
9714 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9715 if (features & NETIF_F_RXFCS) {
9716 if (features & NETIF_F_LRO) {
9717 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9718 features &= ~NETIF_F_LRO;
9719 }
9720
9721 if (features & NETIF_F_GRO_HW) {
9722 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9723 features &= ~NETIF_F_GRO_HW;
9724 }
9725 }
9726
9727 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
9728 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
9729 features &= ~NETIF_F_HW_TLS_RX;
9730 }
9731
9732 return features;
9733 }
9734
__netdev_update_features(struct net_device * dev)9735 int __netdev_update_features(struct net_device *dev)
9736 {
9737 struct net_device *upper, *lower;
9738 netdev_features_t features;
9739 struct list_head *iter;
9740 int err = -1;
9741
9742 ASSERT_RTNL();
9743
9744 features = netdev_get_wanted_features(dev);
9745
9746 if (dev->netdev_ops->ndo_fix_features)
9747 features = dev->netdev_ops->ndo_fix_features(dev, features);
9748
9749 /* driver might be less strict about feature dependencies */
9750 features = netdev_fix_features(dev, features);
9751
9752 /* some features can't be enabled if they're off on an upper device */
9753 netdev_for_each_upper_dev_rcu(dev, upper, iter)
9754 features = netdev_sync_upper_features(dev, upper, features);
9755
9756 if (dev->features == features)
9757 goto sync_lower;
9758
9759 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9760 &dev->features, &features);
9761
9762 if (dev->netdev_ops->ndo_set_features)
9763 err = dev->netdev_ops->ndo_set_features(dev, features);
9764 else
9765 err = 0;
9766
9767 if (unlikely(err < 0)) {
9768 netdev_err(dev,
9769 "set_features() failed (%d); wanted %pNF, left %pNF\n",
9770 err, &features, &dev->features);
9771 /* return non-0 since some features might have changed and
9772 * it's better to fire a spurious notification than miss it
9773 */
9774 return -1;
9775 }
9776
9777 sync_lower:
9778 /* some features must be disabled on lower devices when disabled
9779 * on an upper device (think: bonding master or bridge)
9780 */
9781 netdev_for_each_lower_dev(dev, lower, iter)
9782 netdev_sync_lower_features(dev, lower, features);
9783
9784 if (!err) {
9785 netdev_features_t diff = features ^ dev->features;
9786
9787 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9788 /* udp_tunnel_{get,drop}_rx_info both need
9789 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9790 * device, or they won't do anything.
9791 * Thus we need to update dev->features
9792 * *before* calling udp_tunnel_get_rx_info,
9793 * but *after* calling udp_tunnel_drop_rx_info.
9794 */
9795 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9796 dev->features = features;
9797 udp_tunnel_get_rx_info(dev);
9798 } else {
9799 udp_tunnel_drop_rx_info(dev);
9800 }
9801 }
9802
9803 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9804 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9805 dev->features = features;
9806 err |= vlan_get_rx_ctag_filter_info(dev);
9807 } else {
9808 vlan_drop_rx_ctag_filter_info(dev);
9809 }
9810 }
9811
9812 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9813 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9814 dev->features = features;
9815 err |= vlan_get_rx_stag_filter_info(dev);
9816 } else {
9817 vlan_drop_rx_stag_filter_info(dev);
9818 }
9819 }
9820
9821 dev->features = features;
9822 }
9823
9824 return err < 0 ? 0 : 1;
9825 }
9826
9827 /**
9828 * netdev_update_features - recalculate device features
9829 * @dev: the device to check
9830 *
9831 * Recalculate dev->features set and send notifications if it
9832 * has changed. Should be called after driver or hardware dependent
9833 * conditions might have changed that influence the features.
9834 */
netdev_update_features(struct net_device * dev)9835 void netdev_update_features(struct net_device *dev)
9836 {
9837 if (__netdev_update_features(dev))
9838 netdev_features_change(dev);
9839 }
9840 EXPORT_SYMBOL(netdev_update_features);
9841
9842 /**
9843 * netdev_change_features - recalculate device features
9844 * @dev: the device to check
9845 *
9846 * Recalculate dev->features set and send notifications even
9847 * if they have not changed. Should be called instead of
9848 * netdev_update_features() if also dev->vlan_features might
9849 * have changed to allow the changes to be propagated to stacked
9850 * VLAN devices.
9851 */
netdev_change_features(struct net_device * dev)9852 void netdev_change_features(struct net_device *dev)
9853 {
9854 __netdev_update_features(dev);
9855 netdev_features_change(dev);
9856 }
9857 EXPORT_SYMBOL(netdev_change_features);
9858
9859 /**
9860 * netif_stacked_transfer_operstate - transfer operstate
9861 * @rootdev: the root or lower level device to transfer state from
9862 * @dev: the device to transfer operstate to
9863 *
9864 * Transfer operational state from root to device. This is normally
9865 * called when a stacking relationship exists between the root
9866 * device and the device(a leaf device).
9867 */
netif_stacked_transfer_operstate(const struct net_device * rootdev,struct net_device * dev)9868 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9869 struct net_device *dev)
9870 {
9871 if (rootdev->operstate == IF_OPER_DORMANT)
9872 netif_dormant_on(dev);
9873 else
9874 netif_dormant_off(dev);
9875
9876 if (rootdev->operstate == IF_OPER_TESTING)
9877 netif_testing_on(dev);
9878 else
9879 netif_testing_off(dev);
9880
9881 if (netif_carrier_ok(rootdev))
9882 netif_carrier_on(dev);
9883 else
9884 netif_carrier_off(dev);
9885 }
9886 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9887
netif_alloc_rx_queues(struct net_device * dev)9888 static int netif_alloc_rx_queues(struct net_device *dev)
9889 {
9890 unsigned int i, count = dev->num_rx_queues;
9891 struct netdev_rx_queue *rx;
9892 size_t sz = count * sizeof(*rx);
9893 int err = 0;
9894
9895 BUG_ON(count < 1);
9896
9897 rx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9898 if (!rx)
9899 return -ENOMEM;
9900
9901 dev->_rx = rx;
9902
9903 for (i = 0; i < count; i++) {
9904 rx[i].dev = dev;
9905
9906 /* XDP RX-queue setup */
9907 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i);
9908 if (err < 0)
9909 goto err_rxq_info;
9910 }
9911 return 0;
9912
9913 err_rxq_info:
9914 /* Rollback successful reg's and free other resources */
9915 while (i--)
9916 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9917 kvfree(dev->_rx);
9918 dev->_rx = NULL;
9919 return err;
9920 }
9921
netif_free_rx_queues(struct net_device * dev)9922 static void netif_free_rx_queues(struct net_device *dev)
9923 {
9924 unsigned int i, count = dev->num_rx_queues;
9925
9926 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9927 if (!dev->_rx)
9928 return;
9929
9930 for (i = 0; i < count; i++)
9931 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9932
9933 kvfree(dev->_rx);
9934 }
9935
netdev_init_one_queue(struct net_device * dev,struct netdev_queue * queue,void * _unused)9936 static void netdev_init_one_queue(struct net_device *dev,
9937 struct netdev_queue *queue, void *_unused)
9938 {
9939 /* Initialize queue lock */
9940 spin_lock_init(&queue->_xmit_lock);
9941 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
9942 queue->xmit_lock_owner = -1;
9943 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
9944 queue->dev = dev;
9945 #ifdef CONFIG_BQL
9946 dql_init(&queue->dql, HZ);
9947 #endif
9948 }
9949
netif_free_tx_queues(struct net_device * dev)9950 static void netif_free_tx_queues(struct net_device *dev)
9951 {
9952 kvfree(dev->_tx);
9953 }
9954
netif_alloc_netdev_queues(struct net_device * dev)9955 static int netif_alloc_netdev_queues(struct net_device *dev)
9956 {
9957 unsigned int count = dev->num_tx_queues;
9958 struct netdev_queue *tx;
9959 size_t sz = count * sizeof(*tx);
9960
9961 if (count < 1 || count > 0xffff)
9962 return -EINVAL;
9963
9964 tx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9965 if (!tx)
9966 return -ENOMEM;
9967
9968 dev->_tx = tx;
9969
9970 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
9971 spin_lock_init(&dev->tx_global_lock);
9972
9973 return 0;
9974 }
9975
netif_tx_stop_all_queues(struct net_device * dev)9976 void netif_tx_stop_all_queues(struct net_device *dev)
9977 {
9978 unsigned int i;
9979
9980 for (i = 0; i < dev->num_tx_queues; i++) {
9981 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
9982
9983 netif_tx_stop_queue(txq);
9984 }
9985 }
9986 EXPORT_SYMBOL(netif_tx_stop_all_queues);
9987
9988 /**
9989 * register_netdevice - register a network device
9990 * @dev: device to register
9991 *
9992 * Take a completed network device structure and add it to the kernel
9993 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9994 * chain. 0 is returned on success. A negative errno code is returned
9995 * on a failure to set up the device, or if the name is a duplicate.
9996 *
9997 * Callers must hold the rtnl semaphore. You may want
9998 * register_netdev() instead of this.
9999 *
10000 * BUGS:
10001 * The locking appears insufficient to guarantee two parallel registers
10002 * will not get the same name.
10003 */
10004
register_netdevice(struct net_device * dev)10005 int register_netdevice(struct net_device *dev)
10006 {
10007 int ret;
10008 struct net *net = dev_net(dev);
10009
10010 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
10011 NETDEV_FEATURE_COUNT);
10012 BUG_ON(dev_boot_phase);
10013 ASSERT_RTNL();
10014
10015 might_sleep();
10016
10017 /* When net_device's are persistent, this will be fatal. */
10018 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
10019 BUG_ON(!net);
10020
10021 ret = ethtool_check_ops(dev->ethtool_ops);
10022 if (ret)
10023 return ret;
10024
10025 spin_lock_init(&dev->addr_list_lock);
10026 netdev_set_addr_lockdep_class(dev);
10027
10028 ret = dev_get_valid_name(net, dev, dev->name);
10029 if (ret < 0)
10030 goto out;
10031
10032 ret = -ENOMEM;
10033 dev->name_node = netdev_name_node_head_alloc(dev);
10034 if (!dev->name_node)
10035 goto out;
10036
10037 /* Init, if this function is available */
10038 if (dev->netdev_ops->ndo_init) {
10039 ret = dev->netdev_ops->ndo_init(dev);
10040 if (ret) {
10041 if (ret > 0)
10042 ret = -EIO;
10043 goto err_free_name;
10044 }
10045 }
10046
10047 if (((dev->hw_features | dev->features) &
10048 NETIF_F_HW_VLAN_CTAG_FILTER) &&
10049 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
10050 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
10051 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
10052 ret = -EINVAL;
10053 goto err_uninit;
10054 }
10055
10056 ret = -EBUSY;
10057 if (!dev->ifindex)
10058 dev->ifindex = dev_new_index(net);
10059 else if (__dev_get_by_index(net, dev->ifindex))
10060 goto err_uninit;
10061
10062 /* Transfer changeable features to wanted_features and enable
10063 * software offloads (GSO and GRO).
10064 */
10065 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
10066 dev->features |= NETIF_F_SOFT_FEATURES;
10067
10068 if (dev->netdev_ops->ndo_udp_tunnel_add) {
10069 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10070 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10071 }
10072
10073 dev->wanted_features = dev->features & dev->hw_features;
10074
10075 if (!(dev->flags & IFF_LOOPBACK))
10076 dev->hw_features |= NETIF_F_NOCACHE_COPY;
10077
10078 /* If IPv4 TCP segmentation offload is supported we should also
10079 * allow the device to enable segmenting the frame with the option
10080 * of ignoring a static IP ID value. This doesn't enable the
10081 * feature itself but allows the user to enable it later.
10082 */
10083 if (dev->hw_features & NETIF_F_TSO)
10084 dev->hw_features |= NETIF_F_TSO_MANGLEID;
10085 if (dev->vlan_features & NETIF_F_TSO)
10086 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
10087 if (dev->mpls_features & NETIF_F_TSO)
10088 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
10089 if (dev->hw_enc_features & NETIF_F_TSO)
10090 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
10091
10092 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
10093 */
10094 dev->vlan_features |= NETIF_F_HIGHDMA;
10095
10096 /* Make NETIF_F_SG inheritable to tunnel devices.
10097 */
10098 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
10099
10100 /* Make NETIF_F_SG inheritable to MPLS.
10101 */
10102 dev->mpls_features |= NETIF_F_SG;
10103
10104 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
10105 ret = notifier_to_errno(ret);
10106 if (ret)
10107 goto err_uninit;
10108
10109 ret = netdev_register_kobject(dev);
10110 if (ret) {
10111 dev->reg_state = NETREG_UNREGISTERED;
10112 goto err_uninit;
10113 }
10114 dev->reg_state = NETREG_REGISTERED;
10115
10116 __netdev_update_features(dev);
10117
10118 /*
10119 * Default initial state at registry is that the
10120 * device is present.
10121 */
10122
10123 set_bit(__LINK_STATE_PRESENT, &dev->state);
10124
10125 linkwatch_init_dev(dev);
10126
10127 dev_init_scheduler(dev);
10128 dev_hold(dev);
10129 list_netdevice(dev);
10130 add_device_randomness(dev->dev_addr, dev->addr_len);
10131
10132 /* If the device has permanent device address, driver should
10133 * set dev_addr and also addr_assign_type should be set to
10134 * NET_ADDR_PERM (default value).
10135 */
10136 if (dev->addr_assign_type == NET_ADDR_PERM)
10137 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
10138
10139 /* Notify protocols, that a new device appeared. */
10140 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
10141 ret = notifier_to_errno(ret);
10142 if (ret) {
10143 /* Expect explicit free_netdev() on failure */
10144 dev->needs_free_netdev = false;
10145 rollback_registered(dev);
10146 net_set_todo(dev);
10147 goto out;
10148 }
10149 /*
10150 * Prevent userspace races by waiting until the network
10151 * device is fully setup before sending notifications.
10152 */
10153 if (!dev->rtnl_link_ops ||
10154 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10155 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10156
10157 out:
10158 return ret;
10159
10160 err_uninit:
10161 if (dev->netdev_ops->ndo_uninit)
10162 dev->netdev_ops->ndo_uninit(dev);
10163 if (dev->priv_destructor)
10164 dev->priv_destructor(dev);
10165 err_free_name:
10166 netdev_name_node_free(dev->name_node);
10167 goto out;
10168 }
10169 EXPORT_SYMBOL(register_netdevice);
10170
10171 /**
10172 * init_dummy_netdev - init a dummy network device for NAPI
10173 * @dev: device to init
10174 *
10175 * This takes a network device structure and initialize the minimum
10176 * amount of fields so it can be used to schedule NAPI polls without
10177 * registering a full blown interface. This is to be used by drivers
10178 * that need to tie several hardware interfaces to a single NAPI
10179 * poll scheduler due to HW limitations.
10180 */
init_dummy_netdev(struct net_device * dev)10181 int init_dummy_netdev(struct net_device *dev)
10182 {
10183 /* Clear everything. Note we don't initialize spinlocks
10184 * are they aren't supposed to be taken by any of the
10185 * NAPI code and this dummy netdev is supposed to be
10186 * only ever used for NAPI polls
10187 */
10188 memset(dev, 0, sizeof(struct net_device));
10189
10190 /* make sure we BUG if trying to hit standard
10191 * register/unregister code path
10192 */
10193 dev->reg_state = NETREG_DUMMY;
10194
10195 /* NAPI wants this */
10196 INIT_LIST_HEAD(&dev->napi_list);
10197
10198 /* a dummy interface is started by default */
10199 set_bit(__LINK_STATE_PRESENT, &dev->state);
10200 set_bit(__LINK_STATE_START, &dev->state);
10201
10202 /* napi_busy_loop stats accounting wants this */
10203 dev_net_set(dev, &init_net);
10204
10205 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10206 * because users of this 'device' dont need to change
10207 * its refcount.
10208 */
10209
10210 return 0;
10211 }
10212 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10213
10214
10215 /**
10216 * register_netdev - register a network device
10217 * @dev: device to register
10218 *
10219 * Take a completed network device structure and add it to the kernel
10220 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10221 * chain. 0 is returned on success. A negative errno code is returned
10222 * on a failure to set up the device, or if the name is a duplicate.
10223 *
10224 * This is a wrapper around register_netdevice that takes the rtnl semaphore
10225 * and expands the device name if you passed a format string to
10226 * alloc_netdev.
10227 */
register_netdev(struct net_device * dev)10228 int register_netdev(struct net_device *dev)
10229 {
10230 int err;
10231
10232 if (rtnl_lock_killable())
10233 return -EINTR;
10234 err = register_netdevice(dev);
10235 rtnl_unlock();
10236 return err;
10237 }
10238 EXPORT_SYMBOL(register_netdev);
10239
netdev_refcnt_read(const struct net_device * dev)10240 int netdev_refcnt_read(const struct net_device *dev)
10241 {
10242 int i, refcnt = 0;
10243
10244 for_each_possible_cpu(i)
10245 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10246 return refcnt;
10247 }
10248 EXPORT_SYMBOL(netdev_refcnt_read);
10249
10250 #define WAIT_REFS_MIN_MSECS 1
10251 #define WAIT_REFS_MAX_MSECS 250
10252 /**
10253 * netdev_wait_allrefs - wait until all references are gone.
10254 * @dev: target net_device
10255 *
10256 * This is called when unregistering network devices.
10257 *
10258 * Any protocol or device that holds a reference should register
10259 * for netdevice notification, and cleanup and put back the
10260 * reference if they receive an UNREGISTER event.
10261 * We can get stuck here if buggy protocols don't correctly
10262 * call dev_put.
10263 */
netdev_wait_allrefs(struct net_device * dev)10264 static void netdev_wait_allrefs(struct net_device *dev)
10265 {
10266 unsigned long rebroadcast_time, warning_time;
10267 int wait = 0, refcnt;
10268
10269 linkwatch_forget_dev(dev);
10270
10271 rebroadcast_time = warning_time = jiffies;
10272 refcnt = netdev_refcnt_read(dev);
10273
10274 while (refcnt != 0) {
10275 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10276 rtnl_lock();
10277
10278 /* Rebroadcast unregister notification */
10279 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10280
10281 __rtnl_unlock();
10282 rcu_barrier();
10283 rtnl_lock();
10284
10285 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10286 &dev->state)) {
10287 /* We must not have linkwatch events
10288 * pending on unregister. If this
10289 * happens, we simply run the queue
10290 * unscheduled, resulting in a noop
10291 * for this device.
10292 */
10293 linkwatch_run_queue();
10294 }
10295
10296 __rtnl_unlock();
10297
10298 rebroadcast_time = jiffies;
10299 }
10300
10301 if (!wait) {
10302 rcu_barrier();
10303 wait = WAIT_REFS_MIN_MSECS;
10304 } else {
10305 msleep(wait);
10306 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10307 }
10308
10309 refcnt = netdev_refcnt_read(dev);
10310
10311 if (refcnt && time_after(jiffies, warning_time + 10 * HZ)) {
10312 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10313 dev->name, refcnt);
10314 warning_time = jiffies;
10315 }
10316 }
10317 }
10318
10319 /* The sequence is:
10320 *
10321 * rtnl_lock();
10322 * ...
10323 * register_netdevice(x1);
10324 * register_netdevice(x2);
10325 * ...
10326 * unregister_netdevice(y1);
10327 * unregister_netdevice(y2);
10328 * ...
10329 * rtnl_unlock();
10330 * free_netdev(y1);
10331 * free_netdev(y2);
10332 *
10333 * We are invoked by rtnl_unlock().
10334 * This allows us to deal with problems:
10335 * 1) We can delete sysfs objects which invoke hotplug
10336 * without deadlocking with linkwatch via keventd.
10337 * 2) Since we run with the RTNL semaphore not held, we can sleep
10338 * safely in order to wait for the netdev refcnt to drop to zero.
10339 *
10340 * We must not return until all unregister events added during
10341 * the interval the lock was held have been completed.
10342 */
netdev_run_todo(void)10343 void netdev_run_todo(void)
10344 {
10345 struct list_head list;
10346 #ifdef CONFIG_LOCKDEP
10347 struct list_head unlink_list;
10348
10349 list_replace_init(&net_unlink_list, &unlink_list);
10350
10351 while (!list_empty(&unlink_list)) {
10352 struct net_device *dev = list_first_entry(&unlink_list,
10353 struct net_device,
10354 unlink_list);
10355 list_del_init(&dev->unlink_list);
10356 dev->nested_level = dev->lower_level - 1;
10357 }
10358 #endif
10359
10360 /* Snapshot list, allow later requests */
10361 list_replace_init(&net_todo_list, &list);
10362
10363 __rtnl_unlock();
10364
10365
10366 /* Wait for rcu callbacks to finish before next phase */
10367 if (!list_empty(&list))
10368 rcu_barrier();
10369
10370 while (!list_empty(&list)) {
10371 struct net_device *dev
10372 = list_first_entry(&list, struct net_device, todo_list);
10373 list_del(&dev->todo_list);
10374
10375 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10376 pr_err("network todo '%s' but state %d\n",
10377 dev->name, dev->reg_state);
10378 dump_stack();
10379 continue;
10380 }
10381
10382 dev->reg_state = NETREG_UNREGISTERED;
10383
10384 netdev_wait_allrefs(dev);
10385
10386 /* paranoia */
10387 BUG_ON(netdev_refcnt_read(dev));
10388 BUG_ON(!list_empty(&dev->ptype_all));
10389 BUG_ON(!list_empty(&dev->ptype_specific));
10390 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10391 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10392 #if IS_ENABLED(CONFIG_DECNET)
10393 WARN_ON(dev->dn_ptr);
10394 #endif
10395 if (dev->priv_destructor)
10396 dev->priv_destructor(dev);
10397 if (dev->needs_free_netdev)
10398 free_netdev(dev);
10399
10400 /* Report a network device has been unregistered */
10401 rtnl_lock();
10402 dev_net(dev)->dev_unreg_count--;
10403 __rtnl_unlock();
10404 wake_up(&netdev_unregistering_wq);
10405
10406 /* Free network device */
10407 kobject_put(&dev->dev.kobj);
10408 }
10409 }
10410
10411 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10412 * all the same fields in the same order as net_device_stats, with only
10413 * the type differing, but rtnl_link_stats64 may have additional fields
10414 * at the end for newer counters.
10415 */
netdev_stats_to_stats64(struct rtnl_link_stats64 * stats64,const struct net_device_stats * netdev_stats)10416 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10417 const struct net_device_stats *netdev_stats)
10418 {
10419 #if BITS_PER_LONG == 64
10420 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
10421 memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
10422 /* zero out counters that only exist in rtnl_link_stats64 */
10423 memset((char *)stats64 + sizeof(*netdev_stats), 0,
10424 sizeof(*stats64) - sizeof(*netdev_stats));
10425 #else
10426 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
10427 const unsigned long *src = (const unsigned long *)netdev_stats;
10428 u64 *dst = (u64 *)stats64;
10429
10430 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10431 for (i = 0; i < n; i++)
10432 dst[i] = src[i];
10433 /* zero out counters that only exist in rtnl_link_stats64 */
10434 memset((char *)stats64 + n * sizeof(u64), 0,
10435 sizeof(*stats64) - n * sizeof(u64));
10436 #endif
10437 }
10438 EXPORT_SYMBOL(netdev_stats_to_stats64);
10439
10440 /**
10441 * dev_get_stats - get network device statistics
10442 * @dev: device to get statistics from
10443 * @storage: place to store stats
10444 *
10445 * Get network statistics from device. Return @storage.
10446 * The device driver may provide its own method by setting
10447 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10448 * otherwise the internal statistics structure is used.
10449 */
dev_get_stats(struct net_device * dev,struct rtnl_link_stats64 * storage)10450 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10451 struct rtnl_link_stats64 *storage)
10452 {
10453 const struct net_device_ops *ops = dev->netdev_ops;
10454
10455 if (ops->ndo_get_stats64) {
10456 memset(storage, 0, sizeof(*storage));
10457 ops->ndo_get_stats64(dev, storage);
10458 } else if (ops->ndo_get_stats) {
10459 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10460 } else {
10461 netdev_stats_to_stats64(storage, &dev->stats);
10462 }
10463 storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
10464 storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
10465 storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
10466 return storage;
10467 }
10468 EXPORT_SYMBOL(dev_get_stats);
10469
10470 /**
10471 * dev_fetch_sw_netstats - get per-cpu network device statistics
10472 * @s: place to store stats
10473 * @netstats: per-cpu network stats to read from
10474 *
10475 * Read per-cpu network statistics and populate the related fields in @s.
10476 */
dev_fetch_sw_netstats(struct rtnl_link_stats64 * s,const struct pcpu_sw_netstats __percpu * netstats)10477 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10478 const struct pcpu_sw_netstats __percpu *netstats)
10479 {
10480 int cpu;
10481
10482 for_each_possible_cpu(cpu) {
10483 const struct pcpu_sw_netstats *stats;
10484 struct pcpu_sw_netstats tmp;
10485 unsigned int start;
10486
10487 stats = per_cpu_ptr(netstats, cpu);
10488 do {
10489 start = u64_stats_fetch_begin_irq(&stats->syncp);
10490 tmp.rx_packets = stats->rx_packets;
10491 tmp.rx_bytes = stats->rx_bytes;
10492 tmp.tx_packets = stats->tx_packets;
10493 tmp.tx_bytes = stats->tx_bytes;
10494 } while (u64_stats_fetch_retry_irq(&stats->syncp, start));
10495
10496 s->rx_packets += tmp.rx_packets;
10497 s->rx_bytes += tmp.rx_bytes;
10498 s->tx_packets += tmp.tx_packets;
10499 s->tx_bytes += tmp.tx_bytes;
10500 }
10501 }
10502 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10503
dev_ingress_queue_create(struct net_device * dev)10504 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10505 {
10506 struct netdev_queue *queue = dev_ingress_queue(dev);
10507
10508 #ifdef CONFIG_NET_CLS_ACT
10509 if (queue)
10510 return queue;
10511 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10512 if (!queue)
10513 return NULL;
10514 netdev_init_one_queue(dev, queue, NULL);
10515 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10516 queue->qdisc_sleeping = &noop_qdisc;
10517 rcu_assign_pointer(dev->ingress_queue, queue);
10518 #endif
10519 return queue;
10520 }
10521
10522 static const struct ethtool_ops default_ethtool_ops;
10523
netdev_set_default_ethtool_ops(struct net_device * dev,const struct ethtool_ops * ops)10524 void netdev_set_default_ethtool_ops(struct net_device *dev,
10525 const struct ethtool_ops *ops)
10526 {
10527 if (dev->ethtool_ops == &default_ethtool_ops)
10528 dev->ethtool_ops = ops;
10529 }
10530 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10531
netdev_freemem(struct net_device * dev)10532 void netdev_freemem(struct net_device *dev)
10533 {
10534 char *addr = (char *)dev - dev->padded;
10535
10536 kvfree(addr);
10537 }
10538
10539 /**
10540 * alloc_netdev_mqs - allocate network device
10541 * @sizeof_priv: size of private data to allocate space for
10542 * @name: device name format string
10543 * @name_assign_type: origin of device name
10544 * @setup: callback to initialize device
10545 * @txqs: the number of TX subqueues to allocate
10546 * @rxqs: the number of RX subqueues to allocate
10547 *
10548 * Allocates a struct net_device with private data area for driver use
10549 * and performs basic initialization. Also allocates subqueue structs
10550 * for each queue on the device.
10551 */
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)10552 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10553 unsigned char name_assign_type,
10554 void (*setup)(struct net_device *),
10555 unsigned int txqs, unsigned int rxqs)
10556 {
10557 struct net_device *dev;
10558 unsigned int alloc_size;
10559 struct net_device *p;
10560
10561 BUG_ON(strlen(name) >= sizeof(dev->name));
10562
10563 if (txqs < 1) {
10564 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10565 return NULL;
10566 }
10567
10568 if (rxqs < 1) {
10569 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10570 return NULL;
10571 }
10572
10573 alloc_size = sizeof(struct net_device);
10574 if (sizeof_priv) {
10575 /* ensure 32-byte alignment of private area */
10576 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10577 alloc_size += sizeof_priv;
10578 }
10579 /* ensure 32-byte alignment of whole construct */
10580 alloc_size += NETDEV_ALIGN - 1;
10581
10582 p = kvzalloc(alloc_size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
10583 if (!p)
10584 return NULL;
10585
10586 dev = PTR_ALIGN(p, NETDEV_ALIGN);
10587 dev->padded = (char *)dev - (char *)p;
10588
10589 dev->pcpu_refcnt = alloc_percpu(int);
10590 if (!dev->pcpu_refcnt)
10591 goto free_dev;
10592
10593 if (dev_addr_init(dev))
10594 goto free_pcpu;
10595
10596 dev_mc_init(dev);
10597 dev_uc_init(dev);
10598
10599 dev_net_set(dev, &init_net);
10600
10601 dev->gso_max_size = GSO_MAX_SIZE;
10602 dev->gso_max_segs = GSO_MAX_SEGS;
10603 dev->upper_level = 1;
10604 dev->lower_level = 1;
10605 #ifdef CONFIG_LOCKDEP
10606 dev->nested_level = 0;
10607 INIT_LIST_HEAD(&dev->unlink_list);
10608 #endif
10609
10610 INIT_LIST_HEAD(&dev->napi_list);
10611 INIT_LIST_HEAD(&dev->unreg_list);
10612 INIT_LIST_HEAD(&dev->close_list);
10613 INIT_LIST_HEAD(&dev->link_watch_list);
10614 INIT_LIST_HEAD(&dev->adj_list.upper);
10615 INIT_LIST_HEAD(&dev->adj_list.lower);
10616 INIT_LIST_HEAD(&dev->ptype_all);
10617 INIT_LIST_HEAD(&dev->ptype_specific);
10618 INIT_LIST_HEAD(&dev->net_notifier_list);
10619 #ifdef CONFIG_NET_SCHED
10620 hash_init(dev->qdisc_hash);
10621 #endif
10622 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10623 setup(dev);
10624
10625 if (!dev->tx_queue_len) {
10626 dev->priv_flags |= IFF_NO_QUEUE;
10627 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10628 }
10629
10630 dev->num_tx_queues = txqs;
10631 dev->real_num_tx_queues = txqs;
10632 if (netif_alloc_netdev_queues(dev))
10633 goto free_all;
10634
10635 dev->num_rx_queues = rxqs;
10636 dev->real_num_rx_queues = rxqs;
10637 if (netif_alloc_rx_queues(dev))
10638 goto free_all;
10639
10640 strcpy(dev->name, name);
10641 dev->name_assign_type = name_assign_type;
10642 dev->group = INIT_NETDEV_GROUP;
10643 if (!dev->ethtool_ops)
10644 dev->ethtool_ops = &default_ethtool_ops;
10645
10646 nf_hook_ingress_init(dev);
10647
10648 return dev;
10649
10650 free_all:
10651 free_netdev(dev);
10652 return NULL;
10653
10654 free_pcpu:
10655 free_percpu(dev->pcpu_refcnt);
10656 free_dev:
10657 netdev_freemem(dev);
10658 return NULL;
10659 }
10660 EXPORT_SYMBOL(alloc_netdev_mqs);
10661
10662 /**
10663 * free_netdev - free network device
10664 * @dev: device
10665 *
10666 * This function does the last stage of destroying an allocated device
10667 * interface. The reference to the device object is released. If this
10668 * is the last reference then it will be freed.Must be called in process
10669 * context.
10670 */
free_netdev(struct net_device * dev)10671 void free_netdev(struct net_device *dev)
10672 {
10673 struct napi_struct *p, *n;
10674
10675 might_sleep();
10676
10677 /* When called immediately after register_netdevice() failed the unwind
10678 * handling may still be dismantling the device. Handle that case by
10679 * deferring the free.
10680 */
10681 if (dev->reg_state == NETREG_UNREGISTERING) {
10682 ASSERT_RTNL();
10683 dev->needs_free_netdev = true;
10684 return;
10685 }
10686
10687 netif_free_tx_queues(dev);
10688 netif_free_rx_queues(dev);
10689
10690 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10691
10692 /* Flush device addresses */
10693 dev_addr_flush(dev);
10694
10695 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10696 netif_napi_del(p);
10697
10698 free_percpu(dev->pcpu_refcnt);
10699 dev->pcpu_refcnt = NULL;
10700 free_percpu(dev->xdp_bulkq);
10701 dev->xdp_bulkq = NULL;
10702
10703 /* Compatibility with error handling in drivers */
10704 if (dev->reg_state == NETREG_UNINITIALIZED) {
10705 netdev_freemem(dev);
10706 return;
10707 }
10708
10709 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
10710 dev->reg_state = NETREG_RELEASED;
10711
10712 /* will free via device release */
10713 put_device(&dev->dev);
10714 }
10715 EXPORT_SYMBOL(free_netdev);
10716
10717 /**
10718 * synchronize_net - Synchronize with packet receive processing
10719 *
10720 * Wait for packets currently being received to be done.
10721 * Does not block later packets from starting.
10722 */
synchronize_net(void)10723 void synchronize_net(void)
10724 {
10725 might_sleep();
10726 if (rtnl_is_locked())
10727 synchronize_rcu_expedited();
10728 else
10729 synchronize_rcu();
10730 }
10731 EXPORT_SYMBOL(synchronize_net);
10732
10733 /**
10734 * unregister_netdevice_queue - remove device from the kernel
10735 * @dev: device
10736 * @head: list
10737 *
10738 * This function shuts down a device interface and removes it
10739 * from the kernel tables.
10740 * If head not NULL, device is queued to be unregistered later.
10741 *
10742 * Callers must hold the rtnl semaphore. You may want
10743 * unregister_netdev() instead of this.
10744 */
10745
unregister_netdevice_queue(struct net_device * dev,struct list_head * head)10746 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
10747 {
10748 ASSERT_RTNL();
10749
10750 if (head) {
10751 list_move_tail(&dev->unreg_list, head);
10752 } else {
10753 rollback_registered(dev);
10754 /* Finish processing unregister after unlock */
10755 net_set_todo(dev);
10756 }
10757 }
10758 EXPORT_SYMBOL(unregister_netdevice_queue);
10759
10760 /**
10761 * unregister_netdevice_many - unregister many devices
10762 * @head: list of devices
10763 *
10764 * Note: As most callers use a stack allocated list_head,
10765 * we force a list_del() to make sure stack wont be corrupted later.
10766 */
unregister_netdevice_many(struct list_head * head)10767 void unregister_netdevice_many(struct list_head *head)
10768 {
10769 struct net_device *dev;
10770
10771 if (!list_empty(head)) {
10772 rollback_registered_many(head);
10773 list_for_each_entry(dev, head, unreg_list)
10774 net_set_todo(dev);
10775 list_del(head);
10776 }
10777 }
10778 EXPORT_SYMBOL(unregister_netdevice_many);
10779
10780 /**
10781 * unregister_netdev - remove device from the kernel
10782 * @dev: device
10783 *
10784 * This function shuts down a device interface and removes it
10785 * from the kernel tables.
10786 *
10787 * This is just a wrapper for unregister_netdevice that takes
10788 * the rtnl semaphore. In general you want to use this and not
10789 * unregister_netdevice.
10790 */
unregister_netdev(struct net_device * dev)10791 void unregister_netdev(struct net_device *dev)
10792 {
10793 rtnl_lock();
10794 unregister_netdevice(dev);
10795 rtnl_unlock();
10796 }
10797 EXPORT_SYMBOL(unregister_netdev);
10798
10799 /**
10800 * dev_change_net_namespace - move device to different nethost namespace
10801 * @dev: device
10802 * @net: network namespace
10803 * @pat: If not NULL name pattern to try if the current device name
10804 * is already taken in the destination network namespace.
10805 *
10806 * This function shuts down a device interface and moves it
10807 * to a new network namespace. On success 0 is returned, on
10808 * a failure a netagive errno code is returned.
10809 *
10810 * Callers must hold the rtnl semaphore.
10811 */
10812
dev_change_net_namespace(struct net_device * dev,struct net * net,const char * pat)10813 int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
10814 {
10815 struct net *net_old = dev_net(dev);
10816 int err, new_nsid, new_ifindex;
10817
10818 ASSERT_RTNL();
10819
10820 /* Don't allow namespace local devices to be moved. */
10821 err = -EINVAL;
10822 if (dev->features & NETIF_F_NETNS_LOCAL)
10823 goto out;
10824
10825 /* Ensure the device has been registrered */
10826 if (dev->reg_state != NETREG_REGISTERED)
10827 goto out;
10828
10829 /* Get out if there is nothing todo */
10830 err = 0;
10831 if (net_eq(net_old, net))
10832 goto out;
10833
10834 /* Pick the destination device name, and ensure
10835 * we can use it in the destination network namespace.
10836 */
10837 err = -EEXIST;
10838 if (__dev_get_by_name(net, dev->name)) {
10839 /* We get here if we can't use the current device name */
10840 if (!pat)
10841 goto out;
10842 err = dev_get_valid_name(net, dev, pat);
10843 if (err < 0)
10844 goto out;
10845 }
10846
10847 /*
10848 * And now a mini version of register_netdevice unregister_netdevice.
10849 */
10850
10851 /* If device is running close it first. */
10852 dev_close(dev);
10853
10854 /* And unlink it from device chain */
10855 unlist_netdevice(dev);
10856
10857 synchronize_net();
10858
10859 /* Shutdown queueing discipline. */
10860 dev_shutdown(dev);
10861
10862 /* Notify protocols, that we are about to destroy
10863 * this device. They should clean all the things.
10864 *
10865 * Note that dev->reg_state stays at NETREG_REGISTERED.
10866 * This is wanted because this way 8021q and macvlan know
10867 * the device is just moving and can keep their slaves up.
10868 */
10869 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10870 rcu_barrier();
10871
10872 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
10873 /* If there is an ifindex conflict assign a new one */
10874 if (__dev_get_by_index(net, dev->ifindex))
10875 new_ifindex = dev_new_index(net);
10876 else
10877 new_ifindex = dev->ifindex;
10878
10879 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
10880 new_ifindex);
10881
10882 /*
10883 * Flush the unicast and multicast chains
10884 */
10885 dev_uc_flush(dev);
10886 dev_mc_flush(dev);
10887
10888 /* Send a netdev-removed uevent to the old namespace */
10889 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
10890 netdev_adjacent_del_links(dev);
10891
10892 /* Move per-net netdevice notifiers that are following the netdevice */
10893 move_netdevice_notifiers_dev_net(dev, net);
10894
10895 /* Actually switch the network namespace */
10896 dev_net_set(dev, net);
10897 dev->ifindex = new_ifindex;
10898
10899 /* Send a netdev-add uevent to the new namespace */
10900 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
10901 netdev_adjacent_add_links(dev);
10902
10903 /* Fixup kobjects */
10904 err = device_rename(&dev->dev, dev->name);
10905 WARN_ON(err);
10906
10907 /* Adapt owner in case owning user namespace of target network
10908 * namespace is different from the original one.
10909 */
10910 err = netdev_change_owner(dev, net_old, net);
10911 WARN_ON(err);
10912
10913 /* Add the device back in the hashes */
10914 list_netdevice(dev);
10915
10916 /* Notify protocols, that a new device appeared. */
10917 call_netdevice_notifiers(NETDEV_REGISTER, dev);
10918
10919 /*
10920 * Prevent userspace races by waiting until the network
10921 * device is fully setup before sending notifications.
10922 */
10923 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10924
10925 synchronize_net();
10926 err = 0;
10927 out:
10928 return err;
10929 }
10930 EXPORT_SYMBOL_GPL(dev_change_net_namespace);
10931
dev_cpu_dead(unsigned int oldcpu)10932 static int dev_cpu_dead(unsigned int oldcpu)
10933 {
10934 struct sk_buff **list_skb;
10935 struct sk_buff *skb;
10936 unsigned int cpu;
10937 struct softnet_data *sd, *oldsd, *remsd = NULL;
10938
10939 local_irq_disable();
10940 cpu = smp_processor_id();
10941 sd = &per_cpu(softnet_data, cpu);
10942 oldsd = &per_cpu(softnet_data, oldcpu);
10943
10944 /* Find end of our completion_queue. */
10945 list_skb = &sd->completion_queue;
10946 while (*list_skb)
10947 list_skb = &(*list_skb)->next;
10948 /* Append completion queue from offline CPU. */
10949 *list_skb = oldsd->completion_queue;
10950 oldsd->completion_queue = NULL;
10951
10952 /* Append output queue from offline CPU. */
10953 if (oldsd->output_queue) {
10954 *sd->output_queue_tailp = oldsd->output_queue;
10955 sd->output_queue_tailp = oldsd->output_queue_tailp;
10956 oldsd->output_queue = NULL;
10957 oldsd->output_queue_tailp = &oldsd->output_queue;
10958 }
10959 /* Append NAPI poll list from offline CPU, with one exception :
10960 * process_backlog() must be called by cpu owning percpu backlog.
10961 * We properly handle process_queue & input_pkt_queue later.
10962 */
10963 while (!list_empty(&oldsd->poll_list)) {
10964 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
10965 struct napi_struct,
10966 poll_list);
10967
10968 list_del_init(&napi->poll_list);
10969 if (napi->poll == process_backlog)
10970 napi->state = 0;
10971 else
10972 ____napi_schedule(sd, napi);
10973 }
10974
10975 raise_softirq_irqoff(NET_TX_SOFTIRQ);
10976 local_irq_enable();
10977
10978 #ifdef CONFIG_RPS
10979 remsd = oldsd->rps_ipi_list;
10980 oldsd->rps_ipi_list = NULL;
10981 #endif
10982 /* send out pending IPI's on offline CPU */
10983 net_rps_send_ipi(remsd);
10984
10985 /* Process offline CPU's input_pkt_queue */
10986 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
10987 netif_rx_ni(skb);
10988 input_queue_head_incr(oldsd);
10989 }
10990 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
10991 netif_rx_ni(skb);
10992 input_queue_head_incr(oldsd);
10993 }
10994
10995 return 0;
10996 }
10997
10998 /**
10999 * netdev_increment_features - increment feature set by one
11000 * @all: current feature set
11001 * @one: new feature set
11002 * @mask: mask feature set
11003 *
11004 * Computes a new feature set after adding a device with feature set
11005 * @one to the master device with current feature set @all. Will not
11006 * enable anything that is off in @mask. Returns the new feature set.
11007 */
netdev_increment_features(netdev_features_t all,netdev_features_t one,netdev_features_t mask)11008 netdev_features_t netdev_increment_features(netdev_features_t all,
11009 netdev_features_t one, netdev_features_t mask)
11010 {
11011 if (mask & NETIF_F_HW_CSUM)
11012 mask |= NETIF_F_CSUM_MASK;
11013 mask |= NETIF_F_VLAN_CHALLENGED;
11014
11015 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11016 all &= one | ~NETIF_F_ALL_FOR_ALL;
11017
11018 /* If one device supports hw checksumming, set for all. */
11019 if (all & NETIF_F_HW_CSUM)
11020 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11021
11022 return all;
11023 }
11024 EXPORT_SYMBOL(netdev_increment_features);
11025
netdev_create_hash(void)11026 static struct hlist_head * __net_init netdev_create_hash(void)
11027 {
11028 int i;
11029 struct hlist_head *hash;
11030
11031 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11032 if (hash != NULL)
11033 for (i = 0; i < NETDEV_HASHENTRIES; i++)
11034 INIT_HLIST_HEAD(&hash[i]);
11035
11036 return hash;
11037 }
11038
11039 /* Initialize per network namespace state */
netdev_init(struct net * net)11040 static int __net_init netdev_init(struct net *net)
11041 {
11042 BUILD_BUG_ON(GRO_HASH_BUCKETS >
11043 8 * sizeof_field(struct napi_struct, gro_bitmask));
11044
11045 if (net != &init_net)
11046 INIT_LIST_HEAD(&net->dev_base_head);
11047
11048 net->dev_name_head = netdev_create_hash();
11049 if (net->dev_name_head == NULL)
11050 goto err_name;
11051
11052 net->dev_index_head = netdev_create_hash();
11053 if (net->dev_index_head == NULL)
11054 goto err_idx;
11055
11056 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11057
11058 return 0;
11059
11060 err_idx:
11061 kfree(net->dev_name_head);
11062 err_name:
11063 return -ENOMEM;
11064 }
11065
11066 /**
11067 * netdev_drivername - network driver for the device
11068 * @dev: network device
11069 *
11070 * Determine network driver for device.
11071 */
netdev_drivername(const struct net_device * dev)11072 const char *netdev_drivername(const struct net_device *dev)
11073 {
11074 const struct device_driver *driver;
11075 const struct device *parent;
11076 const char *empty = "";
11077
11078 parent = dev->dev.parent;
11079 if (!parent)
11080 return empty;
11081
11082 driver = parent->driver;
11083 if (driver && driver->name)
11084 return driver->name;
11085 return empty;
11086 }
11087
__netdev_printk(const char * level,const struct net_device * dev,struct va_format * vaf)11088 static void __netdev_printk(const char *level, const struct net_device *dev,
11089 struct va_format *vaf)
11090 {
11091 if (dev && dev->dev.parent) {
11092 dev_printk_emit(level[1] - '0',
11093 dev->dev.parent,
11094 "%s %s %s%s: %pV",
11095 dev_driver_string(dev->dev.parent),
11096 dev_name(dev->dev.parent),
11097 netdev_name(dev), netdev_reg_state(dev),
11098 vaf);
11099 } else if (dev) {
11100 printk("%s%s%s: %pV",
11101 level, netdev_name(dev), netdev_reg_state(dev), vaf);
11102 } else {
11103 printk("%s(NULL net_device): %pV", level, vaf);
11104 }
11105 }
11106
netdev_printk(const char * level,const struct net_device * dev,const char * format,...)11107 void netdev_printk(const char *level, const struct net_device *dev,
11108 const char *format, ...)
11109 {
11110 struct va_format vaf;
11111 va_list args;
11112
11113 va_start(args, format);
11114
11115 vaf.fmt = format;
11116 vaf.va = &args;
11117
11118 __netdev_printk(level, dev, &vaf);
11119
11120 va_end(args);
11121 }
11122 EXPORT_SYMBOL(netdev_printk);
11123
11124 #define define_netdev_printk_level(func, level) \
11125 void func(const struct net_device *dev, const char *fmt, ...) \
11126 { \
11127 struct va_format vaf; \
11128 va_list args; \
11129 \
11130 va_start(args, fmt); \
11131 \
11132 vaf.fmt = fmt; \
11133 vaf.va = &args; \
11134 \
11135 __netdev_printk(level, dev, &vaf); \
11136 \
11137 va_end(args); \
11138 } \
11139 EXPORT_SYMBOL(func);
11140
11141 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11142 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11143 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11144 define_netdev_printk_level(netdev_err, KERN_ERR);
11145 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11146 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11147 define_netdev_printk_level(netdev_info, KERN_INFO);
11148
netdev_exit(struct net * net)11149 static void __net_exit netdev_exit(struct net *net)
11150 {
11151 kfree(net->dev_name_head);
11152 kfree(net->dev_index_head);
11153 if (net != &init_net)
11154 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11155 }
11156
11157 static struct pernet_operations __net_initdata netdev_net_ops = {
11158 .init = netdev_init,
11159 .exit = netdev_exit,
11160 };
11161
default_device_exit(struct net * net)11162 static void __net_exit default_device_exit(struct net *net)
11163 {
11164 struct net_device *dev, *aux;
11165 /*
11166 * Push all migratable network devices back to the
11167 * initial network namespace
11168 */
11169 rtnl_lock();
11170 for_each_netdev_safe(net, dev, aux) {
11171 int err;
11172 char fb_name[IFNAMSIZ];
11173
11174 /* Ignore unmoveable devices (i.e. loopback) */
11175 if (dev->features & NETIF_F_NETNS_LOCAL)
11176 continue;
11177
11178 /* Leave virtual devices for the generic cleanup */
11179 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11180 continue;
11181
11182 /* Push remaining network devices to init_net */
11183 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11184 if (__dev_get_by_name(&init_net, fb_name))
11185 snprintf(fb_name, IFNAMSIZ, "dev%%d");
11186 err = dev_change_net_namespace(dev, &init_net, fb_name);
11187 if (err) {
11188 pr_emerg("%s: failed to move %s to init_net: %d\n",
11189 __func__, dev->name, err);
11190 BUG();
11191 }
11192 }
11193 rtnl_unlock();
11194 }
11195
rtnl_lock_unregistering(struct list_head * net_list)11196 static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
11197 {
11198 /* Return with the rtnl_lock held when there are no network
11199 * devices unregistering in any network namespace in net_list.
11200 */
11201 struct net *net;
11202 bool unregistering;
11203 DEFINE_WAIT_FUNC(wait, woken_wake_function);
11204
11205 add_wait_queue(&netdev_unregistering_wq, &wait);
11206 for (;;) {
11207 unregistering = false;
11208 rtnl_lock();
11209 list_for_each_entry(net, net_list, exit_list) {
11210 if (net->dev_unreg_count > 0) {
11211 unregistering = true;
11212 break;
11213 }
11214 }
11215 if (!unregistering)
11216 break;
11217 __rtnl_unlock();
11218
11219 wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
11220 }
11221 remove_wait_queue(&netdev_unregistering_wq, &wait);
11222 }
11223
default_device_exit_batch(struct list_head * net_list)11224 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11225 {
11226 /* At exit all network devices most be removed from a network
11227 * namespace. Do this in the reverse order of registration.
11228 * Do this across as many network namespaces as possible to
11229 * improve batching efficiency.
11230 */
11231 struct net_device *dev;
11232 struct net *net;
11233 LIST_HEAD(dev_kill_list);
11234
11235 /* To prevent network device cleanup code from dereferencing
11236 * loopback devices or network devices that have been freed
11237 * wait here for all pending unregistrations to complete,
11238 * before unregistring the loopback device and allowing the
11239 * network namespace be freed.
11240 *
11241 * The netdev todo list containing all network devices
11242 * unregistrations that happen in default_device_exit_batch
11243 * will run in the rtnl_unlock() at the end of
11244 * default_device_exit_batch.
11245 */
11246 rtnl_lock_unregistering(net_list);
11247 list_for_each_entry(net, net_list, exit_list) {
11248 for_each_netdev_reverse(net, dev) {
11249 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11250 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11251 else
11252 unregister_netdevice_queue(dev, &dev_kill_list);
11253 }
11254 }
11255 unregister_netdevice_many(&dev_kill_list);
11256 rtnl_unlock();
11257 }
11258
11259 static struct pernet_operations __net_initdata default_device_ops = {
11260 .exit = default_device_exit,
11261 .exit_batch = default_device_exit_batch,
11262 };
11263
11264 /*
11265 * Initialize the DEV module. At boot time this walks the device list and
11266 * unhooks any devices that fail to initialise (normally hardware not
11267 * present) and leaves us with a valid list of present and active devices.
11268 *
11269 */
11270
11271 /*
11272 * This is called single threaded during boot, so no need
11273 * to take the rtnl semaphore.
11274 */
net_dev_init(void)11275 static int __init net_dev_init(void)
11276 {
11277 int i, rc = -ENOMEM;
11278
11279 BUG_ON(!dev_boot_phase);
11280
11281 if (dev_proc_init())
11282 goto out;
11283
11284 if (netdev_kobject_init())
11285 goto out;
11286
11287 INIT_LIST_HEAD(&ptype_all);
11288 for (i = 0; i < PTYPE_HASH_SIZE; i++)
11289 INIT_LIST_HEAD(&ptype_base[i]);
11290
11291 INIT_LIST_HEAD(&offload_base);
11292
11293 if (register_pernet_subsys(&netdev_net_ops))
11294 goto out;
11295
11296 /*
11297 * Initialise the packet receive queues.
11298 */
11299
11300 for_each_possible_cpu(i) {
11301 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
11302 struct softnet_data *sd = &per_cpu(softnet_data, i);
11303
11304 INIT_WORK(flush, flush_backlog);
11305
11306 skb_queue_head_init(&sd->input_pkt_queue);
11307 skb_queue_head_init(&sd->process_queue);
11308 #ifdef CONFIG_XFRM_OFFLOAD
11309 skb_queue_head_init(&sd->xfrm_backlog);
11310 #endif
11311 INIT_LIST_HEAD(&sd->poll_list);
11312 sd->output_queue_tailp = &sd->output_queue;
11313 #ifdef CONFIG_RPS
11314 sd->csd.func = rps_trigger_softirq;
11315 sd->csd.info = sd;
11316 sd->cpu = i;
11317 #endif
11318
11319 init_gro_hash(&sd->backlog);
11320 sd->backlog.poll = process_backlog;
11321 sd->backlog.weight = weight_p;
11322 }
11323
11324 dev_boot_phase = 0;
11325
11326 /* The loopback device is special if any other network devices
11327 * is present in a network namespace the loopback device must
11328 * be present. Since we now dynamically allocate and free the
11329 * loopback device ensure this invariant is maintained by
11330 * keeping the loopback device as the first device on the
11331 * list of network devices. Ensuring the loopback devices
11332 * is the first device that appears and the last network device
11333 * that disappears.
11334 */
11335 if (register_pernet_device(&loopback_net_ops))
11336 goto out;
11337
11338 if (register_pernet_device(&default_device_ops))
11339 goto out;
11340
11341 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11342 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11343
11344 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11345 NULL, dev_cpu_dead);
11346 WARN_ON(rc < 0);
11347 rc = 0;
11348 out:
11349 return rc;
11350 }
11351
11352 subsys_initcall(net_dev_init);
11353