1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * NET3 Protocol independent device support routines.
5 * Derived from the non IP parts of dev.c 1.0.19
7 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
8 * Mark Evans, <evansmp@uhura.aston.ac.uk>
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>
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
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
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
47 * Rudi Cilibrasi : Pass the right thing to
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
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
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
71 #include <linux/uaccess.h>
72 #include <linux/bitmap.h>
73 #include <linux/capability.h>
74 #include <linux/cpu.h>
75 #include <linux/types.h>
76 #include <linux/kernel.h>
77 #include <linux/hash.h>
78 #include <linux/slab.h>
79 #include <linux/sched.h>
80 #include <linux/sched/mm.h>
81 #include <linux/mutex.h>
82 #include <linux/rwsem.h>
83 #include <linux/string.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/kthread.h>
95 #include <linux/bpf.h>
96 #include <linux/bpf_trace.h>
97 #include <net/net_namespace.h>
99 #include <net/busy_poll.h>
100 #include <linux/rtnetlink.h>
101 #include <linux/stat.h>
104 #include <net/dst_metadata.h>
106 #include <net/pkt_sched.h>
107 #include <net/pkt_cls.h>
108 #include <net/checksum.h>
109 #include <net/xfrm.h>
111 #include <linux/highmem.h>
112 #include <linux/init.h>
113 #include <linux/module.h>
114 #include <linux/netpoll.h>
115 #include <linux/rcupdate.h>
116 #include <linux/delay.h>
117 #include <net/iw_handler.h>
118 #include <asm/current.h>
119 #include <linux/audit.h>
120 #include <linux/dmaengine.h>
121 #include <linux/err.h>
122 #include <linux/ctype.h>
123 #include <linux/if_arp.h>
124 #include <linux/if_vlan.h>
125 #include <linux/ip.h>
127 #include <net/mpls.h>
128 #include <linux/ipv6.h>
129 #include <linux/in.h>
130 #include <linux/jhash.h>
131 #include <linux/random.h>
132 #include <trace/events/napi.h>
133 #include <trace/events/net.h>
134 #include <trace/events/skb.h>
135 #include <trace/events/qdisc.h>
136 #include <trace/events/xdp.h>
137 #include <linux/inetdevice.h>
138 #include <linux/cpu_rmap.h>
139 #include <linux/static_key.h>
140 #include <linux/hashtable.h>
141 #include <linux/vmalloc.h>
142 #include <linux/if_macvlan.h>
143 #include <linux/errqueue.h>
144 #include <linux/hrtimer.h>
145 #include <linux/netfilter_netdev.h>
146 #include <linux/crash_dump.h>
147 #include <linux/sctp.h>
148 #include <net/udp_tunnel.h>
149 #include <linux/net_namespace.h>
150 #include <linux/indirect_call_wrapper.h>
151 #include <net/devlink.h>
152 #include <linux/pm_runtime.h>
153 #include <linux/prandom.h>
154 #include <linux/once_lite.h>
155 #include <net/netdev_rx_queue.h>
158 #include "net-sysfs.h"
160 static DEFINE_SPINLOCK(ptype_lock);
161 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
162 struct list_head ptype_all __read_mostly; /* Taps */
164 static int netif_rx_internal(struct sk_buff *skb);
165 static int call_netdevice_notifiers_extack(unsigned long val,
166 struct net_device *dev,
167 struct netlink_ext_ack *extack);
168 static struct napi_struct *napi_by_id(unsigned int napi_id);
171 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
174 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
176 * Writers must hold the rtnl semaphore while they loop through the
177 * dev_base_head list, and hold dev_base_lock for writing when they do the
178 * actual updates. This allows pure readers to access the list even
179 * while a writer is preparing to update it.
181 * To put it another way, dev_base_lock is held for writing only to
182 * protect against pure readers; the rtnl semaphore provides the
183 * protection against other writers.
185 * See, for example usages, register_netdevice() and
186 * unregister_netdevice(), which must be called with the rtnl
189 DEFINE_RWLOCK(dev_base_lock);
190 EXPORT_SYMBOL(dev_base_lock);
192 static DEFINE_MUTEX(ifalias_mutex);
194 /* protects napi_hash addition/deletion and napi_gen_id */
195 static DEFINE_SPINLOCK(napi_hash_lock);
197 static unsigned int napi_gen_id = NR_CPUS;
198 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
200 static DECLARE_RWSEM(devnet_rename_sem);
202 static inline void dev_base_seq_inc(struct net *net)
204 while (++net->dev_base_seq == 0)
208 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
210 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
212 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
215 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
217 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
220 static inline void rps_lock_irqsave(struct softnet_data *sd,
221 unsigned long *flags)
223 if (IS_ENABLED(CONFIG_RPS))
224 spin_lock_irqsave(&sd->input_pkt_queue.lock, *flags);
225 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
226 local_irq_save(*flags);
229 static inline void rps_lock_irq_disable(struct softnet_data *sd)
231 if (IS_ENABLED(CONFIG_RPS))
232 spin_lock_irq(&sd->input_pkt_queue.lock);
233 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
237 static inline void rps_unlock_irq_restore(struct softnet_data *sd,
238 unsigned long *flags)
240 if (IS_ENABLED(CONFIG_RPS))
241 spin_unlock_irqrestore(&sd->input_pkt_queue.lock, *flags);
242 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
243 local_irq_restore(*flags);
246 static inline void rps_unlock_irq_enable(struct softnet_data *sd)
248 if (IS_ENABLED(CONFIG_RPS))
249 spin_unlock_irq(&sd->input_pkt_queue.lock);
250 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
254 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
257 struct netdev_name_node *name_node;
259 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
262 INIT_HLIST_NODE(&name_node->hlist);
263 name_node->dev = dev;
264 name_node->name = name;
268 static struct netdev_name_node *
269 netdev_name_node_head_alloc(struct net_device *dev)
271 struct netdev_name_node *name_node;
273 name_node = netdev_name_node_alloc(dev, dev->name);
276 INIT_LIST_HEAD(&name_node->list);
280 static void netdev_name_node_free(struct netdev_name_node *name_node)
285 static void netdev_name_node_add(struct net *net,
286 struct netdev_name_node *name_node)
288 hlist_add_head_rcu(&name_node->hlist,
289 dev_name_hash(net, name_node->name));
292 static void netdev_name_node_del(struct netdev_name_node *name_node)
294 hlist_del_rcu(&name_node->hlist);
297 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
300 struct hlist_head *head = dev_name_hash(net, name);
301 struct netdev_name_node *name_node;
303 hlist_for_each_entry(name_node, head, hlist)
304 if (!strcmp(name_node->name, name))
309 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
312 struct hlist_head *head = dev_name_hash(net, name);
313 struct netdev_name_node *name_node;
315 hlist_for_each_entry_rcu(name_node, head, hlist)
316 if (!strcmp(name_node->name, name))
321 bool netdev_name_in_use(struct net *net, const char *name)
323 return netdev_name_node_lookup(net, name);
325 EXPORT_SYMBOL(netdev_name_in_use);
327 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
329 struct netdev_name_node *name_node;
330 struct net *net = dev_net(dev);
332 name_node = netdev_name_node_lookup(net, name);
335 name_node = netdev_name_node_alloc(dev, name);
338 netdev_name_node_add(net, name_node);
339 /* The node that holds dev->name acts as a head of per-device list. */
340 list_add_tail(&name_node->list, &dev->name_node->list);
345 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
347 list_del(&name_node->list);
348 netdev_name_node_del(name_node);
349 kfree(name_node->name);
350 netdev_name_node_free(name_node);
353 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
355 struct netdev_name_node *name_node;
356 struct net *net = dev_net(dev);
358 name_node = netdev_name_node_lookup(net, name);
361 /* lookup might have found our primary name or a name belonging
364 if (name_node == dev->name_node || name_node->dev != dev)
367 __netdev_name_node_alt_destroy(name_node);
372 static void netdev_name_node_alt_flush(struct net_device *dev)
374 struct netdev_name_node *name_node, *tmp;
376 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list)
377 __netdev_name_node_alt_destroy(name_node);
380 /* Device list insertion */
381 static void list_netdevice(struct net_device *dev)
383 struct net *net = dev_net(dev);
387 write_lock(&dev_base_lock);
388 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
389 netdev_name_node_add(net, dev->name_node);
390 hlist_add_head_rcu(&dev->index_hlist,
391 dev_index_hash(net, dev->ifindex));
392 write_unlock(&dev_base_lock);
393 /* We reserved the ifindex, this can't fail */
394 WARN_ON(xa_store(&net->dev_by_index, dev->ifindex, dev, GFP_KERNEL));
396 dev_base_seq_inc(net);
399 /* Device list removal
400 * caller must respect a RCU grace period before freeing/reusing dev
402 static void unlist_netdevice(struct net_device *dev, bool lock)
404 struct net *net = dev_net(dev);
408 xa_erase(&net->dev_by_index, dev->ifindex);
410 /* Unlink dev from the device chain */
412 write_lock(&dev_base_lock);
413 list_del_rcu(&dev->dev_list);
414 netdev_name_node_del(dev->name_node);
415 hlist_del_rcu(&dev->index_hlist);
417 write_unlock(&dev_base_lock);
419 dev_base_seq_inc(dev_net(dev));
426 static RAW_NOTIFIER_HEAD(netdev_chain);
429 * Device drivers call our routines to queue packets here. We empty the
430 * queue in the local softnet handler.
433 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
434 EXPORT_PER_CPU_SYMBOL(softnet_data);
436 #ifdef CONFIG_LOCKDEP
438 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
439 * according to dev->type
441 static const unsigned short netdev_lock_type[] = {
442 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
443 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
444 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
445 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
446 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
447 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
448 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
449 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
450 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
451 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
452 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
453 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
454 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
455 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
456 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
458 static const char *const netdev_lock_name[] = {
459 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
460 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
461 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
462 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
463 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
464 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
465 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
466 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
467 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
468 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
469 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
470 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
471 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
472 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
473 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
475 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
476 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
478 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
482 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
483 if (netdev_lock_type[i] == dev_type)
485 /* the last key is used by default */
486 return ARRAY_SIZE(netdev_lock_type) - 1;
489 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
490 unsigned short dev_type)
494 i = netdev_lock_pos(dev_type);
495 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
496 netdev_lock_name[i]);
499 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
503 i = netdev_lock_pos(dev->type);
504 lockdep_set_class_and_name(&dev->addr_list_lock,
505 &netdev_addr_lock_key[i],
506 netdev_lock_name[i]);
509 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
510 unsigned short dev_type)
514 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
519 /*******************************************************************************
521 * Protocol management and registration routines
523 *******************************************************************************/
527 * Add a protocol ID to the list. Now that the input handler is
528 * smarter we can dispense with all the messy stuff that used to be
531 * BEWARE!!! Protocol handlers, mangling input packets,
532 * MUST BE last in hash buckets and checking protocol handlers
533 * MUST start from promiscuous ptype_all chain in net_bh.
534 * It is true now, do not change it.
535 * Explanation follows: if protocol handler, mangling packet, will
536 * be the first on list, it is not able to sense, that packet
537 * is cloned and should be copied-on-write, so that it will
538 * change it and subsequent readers will get broken packet.
542 static inline struct list_head *ptype_head(const struct packet_type *pt)
544 if (pt->type == htons(ETH_P_ALL))
545 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
547 return pt->dev ? &pt->dev->ptype_specific :
548 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
552 * dev_add_pack - add packet handler
553 * @pt: packet type declaration
555 * Add a protocol handler to the networking stack. The passed &packet_type
556 * is linked into kernel lists and may not be freed until it has been
557 * removed from the kernel lists.
559 * This call does not sleep therefore it can not
560 * guarantee all CPU's that are in middle of receiving packets
561 * will see the new packet type (until the next received packet).
564 void dev_add_pack(struct packet_type *pt)
566 struct list_head *head = ptype_head(pt);
568 spin_lock(&ptype_lock);
569 list_add_rcu(&pt->list, head);
570 spin_unlock(&ptype_lock);
572 EXPORT_SYMBOL(dev_add_pack);
575 * __dev_remove_pack - remove packet handler
576 * @pt: packet type declaration
578 * Remove a protocol handler that was previously added to the kernel
579 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
580 * from the kernel lists and can be freed or reused once this function
583 * The packet type might still be in use by receivers
584 * and must not be freed until after all the CPU's have gone
585 * through a quiescent state.
587 void __dev_remove_pack(struct packet_type *pt)
589 struct list_head *head = ptype_head(pt);
590 struct packet_type *pt1;
592 spin_lock(&ptype_lock);
594 list_for_each_entry(pt1, head, list) {
596 list_del_rcu(&pt->list);
601 pr_warn("dev_remove_pack: %p not found\n", pt);
603 spin_unlock(&ptype_lock);
605 EXPORT_SYMBOL(__dev_remove_pack);
608 * dev_remove_pack - remove packet handler
609 * @pt: packet type declaration
611 * Remove a protocol handler that was previously added to the kernel
612 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
613 * from the kernel lists and can be freed or reused once this function
616 * This call sleeps to guarantee that no CPU is looking at the packet
619 void dev_remove_pack(struct packet_type *pt)
621 __dev_remove_pack(pt);
625 EXPORT_SYMBOL(dev_remove_pack);
628 /*******************************************************************************
630 * Device Interface Subroutines
632 *******************************************************************************/
635 * dev_get_iflink - get 'iflink' value of a interface
636 * @dev: targeted interface
638 * Indicates the ifindex the interface is linked to.
639 * Physical interfaces have the same 'ifindex' and 'iflink' values.
642 int dev_get_iflink(const struct net_device *dev)
644 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
645 return dev->netdev_ops->ndo_get_iflink(dev);
649 EXPORT_SYMBOL(dev_get_iflink);
652 * dev_fill_metadata_dst - Retrieve tunnel egress information.
653 * @dev: targeted interface
656 * For better visibility of tunnel traffic OVS needs to retrieve
657 * egress tunnel information for a packet. Following API allows
658 * user to get this info.
660 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
662 struct ip_tunnel_info *info;
664 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
667 info = skb_tunnel_info_unclone(skb);
670 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
673 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
675 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
677 static struct net_device_path *dev_fwd_path(struct net_device_path_stack *stack)
679 int k = stack->num_paths++;
681 if (WARN_ON_ONCE(k >= NET_DEVICE_PATH_STACK_MAX))
684 return &stack->path[k];
687 int dev_fill_forward_path(const struct net_device *dev, const u8 *daddr,
688 struct net_device_path_stack *stack)
690 const struct net_device *last_dev;
691 struct net_device_path_ctx ctx = {
694 struct net_device_path *path;
697 memcpy(ctx.daddr, daddr, sizeof(ctx.daddr));
698 stack->num_paths = 0;
699 while (ctx.dev && ctx.dev->netdev_ops->ndo_fill_forward_path) {
701 path = dev_fwd_path(stack);
705 memset(path, 0, sizeof(struct net_device_path));
706 ret = ctx.dev->netdev_ops->ndo_fill_forward_path(&ctx, path);
710 if (WARN_ON_ONCE(last_dev == ctx.dev))
717 path = dev_fwd_path(stack);
720 path->type = DEV_PATH_ETHERNET;
725 EXPORT_SYMBOL_GPL(dev_fill_forward_path);
728 * __dev_get_by_name - find a device by its name
729 * @net: the applicable net namespace
730 * @name: name to find
732 * Find an interface by name. Must be called under RTNL semaphore
733 * or @dev_base_lock. If the name is found a pointer to the device
734 * is returned. If the name is not found then %NULL is returned. The
735 * reference counters are not incremented so the caller must be
736 * careful with locks.
739 struct net_device *__dev_get_by_name(struct net *net, const char *name)
741 struct netdev_name_node *node_name;
743 node_name = netdev_name_node_lookup(net, name);
744 return node_name ? node_name->dev : NULL;
746 EXPORT_SYMBOL(__dev_get_by_name);
749 * dev_get_by_name_rcu - find a device by its name
750 * @net: the applicable net namespace
751 * @name: name to find
753 * Find an interface by name.
754 * If the name is found a pointer to the device is returned.
755 * If the name is not found then %NULL is returned.
756 * The reference counters are not incremented so the caller must be
757 * careful with locks. The caller must hold RCU lock.
760 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
762 struct netdev_name_node *node_name;
764 node_name = netdev_name_node_lookup_rcu(net, name);
765 return node_name ? node_name->dev : NULL;
767 EXPORT_SYMBOL(dev_get_by_name_rcu);
769 /* Deprecated for new users, call netdev_get_by_name() instead */
770 struct net_device *dev_get_by_name(struct net *net, const char *name)
772 struct net_device *dev;
775 dev = dev_get_by_name_rcu(net, name);
780 EXPORT_SYMBOL(dev_get_by_name);
783 * netdev_get_by_name() - find a device by its name
784 * @net: the applicable net namespace
785 * @name: name to find
786 * @tracker: tracking object for the acquired reference
787 * @gfp: allocation flags for the tracker
789 * Find an interface by name. This can be called from any
790 * context and does its own locking. The returned handle has
791 * the usage count incremented and the caller must use netdev_put() to
792 * release it when it is no longer needed. %NULL is returned if no
793 * matching device is found.
795 struct net_device *netdev_get_by_name(struct net *net, const char *name,
796 netdevice_tracker *tracker, gfp_t gfp)
798 struct net_device *dev;
800 dev = dev_get_by_name(net, name);
802 netdev_tracker_alloc(dev, tracker, gfp);
805 EXPORT_SYMBOL(netdev_get_by_name);
808 * __dev_get_by_index - find a device by its ifindex
809 * @net: the applicable net namespace
810 * @ifindex: index of device
812 * Search for an interface by index. Returns %NULL if the device
813 * is not found or a pointer to the device. The device has not
814 * had its reference counter increased so the caller must be careful
815 * about locking. The caller must hold either the RTNL semaphore
819 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
821 struct net_device *dev;
822 struct hlist_head *head = dev_index_hash(net, ifindex);
824 hlist_for_each_entry(dev, head, index_hlist)
825 if (dev->ifindex == ifindex)
830 EXPORT_SYMBOL(__dev_get_by_index);
833 * dev_get_by_index_rcu - find a device by its ifindex
834 * @net: the applicable net namespace
835 * @ifindex: index of device
837 * Search for an interface by index. Returns %NULL if the device
838 * is not found or a pointer to the device. The device has not
839 * had its reference counter increased so the caller must be careful
840 * about locking. The caller must hold RCU lock.
843 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
845 struct net_device *dev;
846 struct hlist_head *head = dev_index_hash(net, ifindex);
848 hlist_for_each_entry_rcu(dev, head, index_hlist)
849 if (dev->ifindex == ifindex)
854 EXPORT_SYMBOL(dev_get_by_index_rcu);
856 /* Deprecated for new users, call netdev_get_by_index() instead */
857 struct net_device *dev_get_by_index(struct net *net, int ifindex)
859 struct net_device *dev;
862 dev = dev_get_by_index_rcu(net, ifindex);
867 EXPORT_SYMBOL(dev_get_by_index);
870 * netdev_get_by_index() - find a device by its ifindex
871 * @net: the applicable net namespace
872 * @ifindex: index of device
873 * @tracker: tracking object for the acquired reference
874 * @gfp: allocation flags for the tracker
876 * Search for an interface by index. Returns NULL if the device
877 * is not found or a pointer to the device. The device returned has
878 * had a reference added and the pointer is safe until the user calls
879 * netdev_put() to indicate they have finished with it.
881 struct net_device *netdev_get_by_index(struct net *net, int ifindex,
882 netdevice_tracker *tracker, gfp_t gfp)
884 struct net_device *dev;
886 dev = dev_get_by_index(net, ifindex);
888 netdev_tracker_alloc(dev, tracker, gfp);
891 EXPORT_SYMBOL(netdev_get_by_index);
894 * dev_get_by_napi_id - find a device by napi_id
895 * @napi_id: ID of the NAPI struct
897 * Search for an interface by NAPI ID. Returns %NULL if the device
898 * is not found or a pointer to the device. The device has not had
899 * its reference counter increased so the caller must be careful
900 * about locking. The caller must hold RCU lock.
903 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
905 struct napi_struct *napi;
907 WARN_ON_ONCE(!rcu_read_lock_held());
909 if (napi_id < MIN_NAPI_ID)
912 napi = napi_by_id(napi_id);
914 return napi ? napi->dev : NULL;
916 EXPORT_SYMBOL(dev_get_by_napi_id);
919 * netdev_get_name - get a netdevice name, knowing its ifindex.
920 * @net: network namespace
921 * @name: a pointer to the buffer where the name will be stored.
922 * @ifindex: the ifindex of the interface to get the name from.
924 int netdev_get_name(struct net *net, char *name, int ifindex)
926 struct net_device *dev;
929 down_read(&devnet_rename_sem);
932 dev = dev_get_by_index_rcu(net, ifindex);
938 strcpy(name, dev->name);
943 up_read(&devnet_rename_sem);
948 * dev_getbyhwaddr_rcu - find a device by its hardware address
949 * @net: the applicable net namespace
950 * @type: media type of device
951 * @ha: hardware address
953 * Search for an interface by MAC address. Returns NULL if the device
954 * is not found or a pointer to the device.
955 * The caller must hold RCU or RTNL.
956 * The returned device has not had its ref count increased
957 * and the caller must therefore be careful about locking
961 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
964 struct net_device *dev;
966 for_each_netdev_rcu(net, dev)
967 if (dev->type == type &&
968 !memcmp(dev->dev_addr, ha, dev->addr_len))
973 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
975 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
977 struct net_device *dev, *ret = NULL;
980 for_each_netdev_rcu(net, dev)
981 if (dev->type == type) {
989 EXPORT_SYMBOL(dev_getfirstbyhwtype);
992 * __dev_get_by_flags - find any device with given flags
993 * @net: the applicable net namespace
994 * @if_flags: IFF_* values
995 * @mask: bitmask of bits in if_flags to check
997 * Search for any interface with the given flags. Returns NULL if a device
998 * is not found or a pointer to the device. Must be called inside
999 * rtnl_lock(), and result refcount is unchanged.
1002 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1003 unsigned short mask)
1005 struct net_device *dev, *ret;
1010 for_each_netdev(net, dev) {
1011 if (((dev->flags ^ if_flags) & mask) == 0) {
1018 EXPORT_SYMBOL(__dev_get_by_flags);
1021 * dev_valid_name - check if name is okay for network device
1022 * @name: name string
1024 * Network device names need to be valid file names to
1025 * allow sysfs to work. We also disallow any kind of
1028 bool dev_valid_name(const char *name)
1032 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1034 if (!strcmp(name, ".") || !strcmp(name, ".."))
1038 if (*name == '/' || *name == ':' || isspace(*name))
1044 EXPORT_SYMBOL(dev_valid_name);
1047 * __dev_alloc_name - allocate a name for a device
1048 * @net: network namespace to allocate the device name in
1049 * @name: name format string
1050 * @buf: scratch buffer and result name string
1052 * Passed a format string - eg "lt%d" it will try and find a suitable
1053 * id. It scans list of devices to build up a free map, then chooses
1054 * the first empty slot. The caller must hold the dev_base or rtnl lock
1055 * while allocating the name and adding the device in order to avoid
1057 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1058 * Returns the number of the unit assigned or a negative errno code.
1061 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1065 const int max_netdevices = 8*PAGE_SIZE;
1066 unsigned long *inuse;
1067 struct net_device *d;
1069 if (!dev_valid_name(name))
1072 p = strchr(name, '%');
1075 * Verify the string as this thing may have come from
1076 * the user. There must be either one "%d" and no other "%"
1079 if (p[1] != 'd' || strchr(p + 2, '%'))
1082 /* Use one page as a bit array of possible slots */
1083 inuse = bitmap_zalloc(max_netdevices, GFP_ATOMIC);
1087 for_each_netdev(net, d) {
1088 struct netdev_name_node *name_node;
1089 list_for_each_entry(name_node, &d->name_node->list, list) {
1090 if (!sscanf(name_node->name, name, &i))
1092 if (i < 0 || i >= max_netdevices)
1095 /* avoid cases where sscanf is not exact inverse of printf */
1096 snprintf(buf, IFNAMSIZ, name, i);
1097 if (!strncmp(buf, name_node->name, IFNAMSIZ))
1098 __set_bit(i, inuse);
1100 if (!sscanf(d->name, name, &i))
1102 if (i < 0 || i >= max_netdevices)
1105 /* avoid cases where sscanf is not exact inverse of printf */
1106 snprintf(buf, IFNAMSIZ, name, i);
1107 if (!strncmp(buf, d->name, IFNAMSIZ))
1108 __set_bit(i, inuse);
1111 i = find_first_zero_bit(inuse, max_netdevices);
1115 snprintf(buf, IFNAMSIZ, name, i);
1116 if (!netdev_name_in_use(net, buf))
1119 /* It is possible to run out of possible slots
1120 * when the name is long and there isn't enough space left
1121 * for the digits, or if all bits are used.
1126 static int dev_prep_valid_name(struct net *net, struct net_device *dev,
1127 const char *want_name, char *out_name)
1131 if (!dev_valid_name(want_name))
1134 if (strchr(want_name, '%')) {
1135 ret = __dev_alloc_name(net, want_name, out_name);
1136 return ret < 0 ? ret : 0;
1137 } else if (netdev_name_in_use(net, want_name)) {
1139 } else if (out_name != want_name) {
1140 strscpy(out_name, want_name, IFNAMSIZ);
1146 static int dev_alloc_name_ns(struct net *net,
1147 struct net_device *dev,
1154 ret = __dev_alloc_name(net, name, buf);
1156 strscpy(dev->name, buf, IFNAMSIZ);
1161 * dev_alloc_name - allocate a name for a device
1163 * @name: name format string
1165 * Passed a format string - eg "lt%d" it will try and find a suitable
1166 * id. It scans list of devices to build up a free map, then chooses
1167 * the first empty slot. The caller must hold the dev_base or rtnl lock
1168 * while allocating the name and adding the device in order to avoid
1170 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1171 * Returns the number of the unit assigned or a negative errno code.
1174 int dev_alloc_name(struct net_device *dev, const char *name)
1176 return dev_alloc_name_ns(dev_net(dev), dev, name);
1178 EXPORT_SYMBOL(dev_alloc_name);
1180 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1186 ret = dev_prep_valid_name(net, dev, name, buf);
1188 strscpy(dev->name, buf, IFNAMSIZ);
1193 * dev_change_name - change name of a device
1195 * @newname: name (or format string) must be at least IFNAMSIZ
1197 * Change name of a device, can pass format strings "eth%d".
1200 int dev_change_name(struct net_device *dev, const char *newname)
1202 unsigned char old_assign_type;
1203 char oldname[IFNAMSIZ];
1209 BUG_ON(!dev_net(dev));
1213 down_write(&devnet_rename_sem);
1215 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1216 up_write(&devnet_rename_sem);
1220 memcpy(oldname, dev->name, IFNAMSIZ);
1222 err = dev_get_valid_name(net, dev, newname);
1224 up_write(&devnet_rename_sem);
1228 if (oldname[0] && !strchr(oldname, '%'))
1229 netdev_info(dev, "renamed from %s%s\n", oldname,
1230 dev->flags & IFF_UP ? " (while UP)" : "");
1232 old_assign_type = dev->name_assign_type;
1233 dev->name_assign_type = NET_NAME_RENAMED;
1236 ret = device_rename(&dev->dev, dev->name);
1238 memcpy(dev->name, oldname, IFNAMSIZ);
1239 dev->name_assign_type = old_assign_type;
1240 up_write(&devnet_rename_sem);
1244 up_write(&devnet_rename_sem);
1246 netdev_adjacent_rename_links(dev, oldname);
1248 write_lock(&dev_base_lock);
1249 netdev_name_node_del(dev->name_node);
1250 write_unlock(&dev_base_lock);
1254 write_lock(&dev_base_lock);
1255 netdev_name_node_add(net, dev->name_node);
1256 write_unlock(&dev_base_lock);
1258 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1259 ret = notifier_to_errno(ret);
1262 /* err >= 0 after dev_alloc_name() or stores the first errno */
1265 down_write(&devnet_rename_sem);
1266 memcpy(dev->name, oldname, IFNAMSIZ);
1267 memcpy(oldname, newname, IFNAMSIZ);
1268 dev->name_assign_type = old_assign_type;
1269 old_assign_type = NET_NAME_RENAMED;
1272 netdev_err(dev, "name change rollback failed: %d\n",
1281 * dev_set_alias - change ifalias of a device
1283 * @alias: name up to IFALIASZ
1284 * @len: limit of bytes to copy from info
1286 * Set ifalias for a device,
1288 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1290 struct dev_ifalias *new_alias = NULL;
1292 if (len >= IFALIASZ)
1296 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1300 memcpy(new_alias->ifalias, alias, len);
1301 new_alias->ifalias[len] = 0;
1304 mutex_lock(&ifalias_mutex);
1305 new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1306 mutex_is_locked(&ifalias_mutex));
1307 mutex_unlock(&ifalias_mutex);
1310 kfree_rcu(new_alias, rcuhead);
1314 EXPORT_SYMBOL(dev_set_alias);
1317 * dev_get_alias - get ifalias of a device
1319 * @name: buffer to store name of ifalias
1320 * @len: size of buffer
1322 * get ifalias for a device. Caller must make sure dev cannot go
1323 * away, e.g. rcu read lock or own a reference count to device.
1325 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1327 const struct dev_ifalias *alias;
1331 alias = rcu_dereference(dev->ifalias);
1333 ret = snprintf(name, len, "%s", alias->ifalias);
1340 * netdev_features_change - device changes features
1341 * @dev: device to cause notification
1343 * Called to indicate a device has changed features.
1345 void netdev_features_change(struct net_device *dev)
1347 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1349 EXPORT_SYMBOL(netdev_features_change);
1352 * netdev_state_change - device changes state
1353 * @dev: device to cause notification
1355 * Called to indicate a device has changed state. This function calls
1356 * the notifier chains for netdev_chain and sends a NEWLINK message
1357 * to the routing socket.
1359 void netdev_state_change(struct net_device *dev)
1361 if (dev->flags & IFF_UP) {
1362 struct netdev_notifier_change_info change_info = {
1366 call_netdevice_notifiers_info(NETDEV_CHANGE,
1368 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL, 0, NULL);
1371 EXPORT_SYMBOL(netdev_state_change);
1374 * __netdev_notify_peers - notify network peers about existence of @dev,
1375 * to be called when rtnl lock is already held.
1376 * @dev: network device
1378 * Generate traffic such that interested network peers are aware of
1379 * @dev, such as by generating a gratuitous ARP. This may be used when
1380 * a device wants to inform the rest of the network about some sort of
1381 * reconfiguration such as a failover event or virtual machine
1384 void __netdev_notify_peers(struct net_device *dev)
1387 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1388 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1390 EXPORT_SYMBOL(__netdev_notify_peers);
1393 * netdev_notify_peers - notify network peers about existence of @dev
1394 * @dev: network device
1396 * Generate traffic such that interested network peers are aware of
1397 * @dev, such as by generating a gratuitous ARP. This may be used when
1398 * a device wants to inform the rest of the network about some sort of
1399 * reconfiguration such as a failover event or virtual machine
1402 void netdev_notify_peers(struct net_device *dev)
1405 __netdev_notify_peers(dev);
1408 EXPORT_SYMBOL(netdev_notify_peers);
1410 static int napi_threaded_poll(void *data);
1412 static int napi_kthread_create(struct napi_struct *n)
1416 /* Create and wake up the kthread once to put it in
1417 * TASK_INTERRUPTIBLE mode to avoid the blocked task
1418 * warning and work with loadavg.
1420 n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d",
1421 n->dev->name, n->napi_id);
1422 if (IS_ERR(n->thread)) {
1423 err = PTR_ERR(n->thread);
1424 pr_err("kthread_run failed with err %d\n", err);
1431 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1433 const struct net_device_ops *ops = dev->netdev_ops;
1437 dev_addr_check(dev);
1439 if (!netif_device_present(dev)) {
1440 /* may be detached because parent is runtime-suspended */
1441 if (dev->dev.parent)
1442 pm_runtime_resume(dev->dev.parent);
1443 if (!netif_device_present(dev))
1447 /* Block netpoll from trying to do any rx path servicing.
1448 * If we don't do this there is a chance ndo_poll_controller
1449 * or ndo_poll may be running while we open the device
1451 netpoll_poll_disable(dev);
1453 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1454 ret = notifier_to_errno(ret);
1458 set_bit(__LINK_STATE_START, &dev->state);
1460 if (ops->ndo_validate_addr)
1461 ret = ops->ndo_validate_addr(dev);
1463 if (!ret && ops->ndo_open)
1464 ret = ops->ndo_open(dev);
1466 netpoll_poll_enable(dev);
1469 clear_bit(__LINK_STATE_START, &dev->state);
1471 dev->flags |= IFF_UP;
1472 dev_set_rx_mode(dev);
1474 add_device_randomness(dev->dev_addr, dev->addr_len);
1481 * dev_open - prepare an interface for use.
1482 * @dev: device to open
1483 * @extack: netlink extended ack
1485 * Takes a device from down to up state. The device's private open
1486 * function is invoked and then the multicast lists are loaded. Finally
1487 * the device is moved into the up state and a %NETDEV_UP message is
1488 * sent to the netdev notifier chain.
1490 * Calling this function on an active interface is a nop. On a failure
1491 * a negative errno code is returned.
1493 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1497 if (dev->flags & IFF_UP)
1500 ret = __dev_open(dev, extack);
1504 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1505 call_netdevice_notifiers(NETDEV_UP, dev);
1509 EXPORT_SYMBOL(dev_open);
1511 static void __dev_close_many(struct list_head *head)
1513 struct net_device *dev;
1518 list_for_each_entry(dev, head, close_list) {
1519 /* Temporarily disable netpoll until the interface is down */
1520 netpoll_poll_disable(dev);
1522 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1524 clear_bit(__LINK_STATE_START, &dev->state);
1526 /* Synchronize to scheduled poll. We cannot touch poll list, it
1527 * can be even on different cpu. So just clear netif_running().
1529 * dev->stop() will invoke napi_disable() on all of it's
1530 * napi_struct instances on this device.
1532 smp_mb__after_atomic(); /* Commit netif_running(). */
1535 dev_deactivate_many(head);
1537 list_for_each_entry(dev, head, close_list) {
1538 const struct net_device_ops *ops = dev->netdev_ops;
1541 * Call the device specific close. This cannot fail.
1542 * Only if device is UP
1544 * We allow it to be called even after a DETACH hot-plug
1550 dev->flags &= ~IFF_UP;
1551 netpoll_poll_enable(dev);
1555 static void __dev_close(struct net_device *dev)
1559 list_add(&dev->close_list, &single);
1560 __dev_close_many(&single);
1564 void dev_close_many(struct list_head *head, bool unlink)
1566 struct net_device *dev, *tmp;
1568 /* Remove the devices that don't need to be closed */
1569 list_for_each_entry_safe(dev, tmp, head, close_list)
1570 if (!(dev->flags & IFF_UP))
1571 list_del_init(&dev->close_list);
1573 __dev_close_many(head);
1575 list_for_each_entry_safe(dev, tmp, head, close_list) {
1576 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1577 call_netdevice_notifiers(NETDEV_DOWN, dev);
1579 list_del_init(&dev->close_list);
1582 EXPORT_SYMBOL(dev_close_many);
1585 * dev_close - shutdown an interface.
1586 * @dev: device to shutdown
1588 * This function moves an active device into down state. A
1589 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1590 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1593 void dev_close(struct net_device *dev)
1595 if (dev->flags & IFF_UP) {
1598 list_add(&dev->close_list, &single);
1599 dev_close_many(&single, true);
1603 EXPORT_SYMBOL(dev_close);
1607 * dev_disable_lro - disable Large Receive Offload on a device
1610 * Disable Large Receive Offload (LRO) on a net device. Must be
1611 * called under RTNL. This is needed if received packets may be
1612 * forwarded to another interface.
1614 void dev_disable_lro(struct net_device *dev)
1616 struct net_device *lower_dev;
1617 struct list_head *iter;
1619 dev->wanted_features &= ~NETIF_F_LRO;
1620 netdev_update_features(dev);
1622 if (unlikely(dev->features & NETIF_F_LRO))
1623 netdev_WARN(dev, "failed to disable LRO!\n");
1625 netdev_for_each_lower_dev(dev, lower_dev, iter)
1626 dev_disable_lro(lower_dev);
1628 EXPORT_SYMBOL(dev_disable_lro);
1631 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1634 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1635 * called under RTNL. This is needed if Generic XDP is installed on
1638 static void dev_disable_gro_hw(struct net_device *dev)
1640 dev->wanted_features &= ~NETIF_F_GRO_HW;
1641 netdev_update_features(dev);
1643 if (unlikely(dev->features & NETIF_F_GRO_HW))
1644 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1647 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1650 case NETDEV_##val: \
1651 return "NETDEV_" __stringify(val);
1653 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1654 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1655 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1656 N(POST_INIT) N(PRE_UNINIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN)
1657 N(CHANGEUPPER) N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA)
1658 N(BONDING_INFO) N(PRECHANGEUPPER) N(CHANGELOWERSTATE)
1659 N(UDP_TUNNEL_PUSH_INFO) N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1660 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1661 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1662 N(PRE_CHANGEADDR) N(OFFLOAD_XSTATS_ENABLE) N(OFFLOAD_XSTATS_DISABLE)
1663 N(OFFLOAD_XSTATS_REPORT_USED) N(OFFLOAD_XSTATS_REPORT_DELTA)
1667 return "UNKNOWN_NETDEV_EVENT";
1669 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1671 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1672 struct net_device *dev)
1674 struct netdev_notifier_info info = {
1678 return nb->notifier_call(nb, val, &info);
1681 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1682 struct net_device *dev)
1686 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1687 err = notifier_to_errno(err);
1691 if (!(dev->flags & IFF_UP))
1694 call_netdevice_notifier(nb, NETDEV_UP, dev);
1698 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1699 struct net_device *dev)
1701 if (dev->flags & IFF_UP) {
1702 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1704 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1706 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1709 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1712 struct net_device *dev;
1715 for_each_netdev(net, dev) {
1716 err = call_netdevice_register_notifiers(nb, dev);
1723 for_each_netdev_continue_reverse(net, dev)
1724 call_netdevice_unregister_notifiers(nb, dev);
1728 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1731 struct net_device *dev;
1733 for_each_netdev(net, dev)
1734 call_netdevice_unregister_notifiers(nb, dev);
1737 static int dev_boot_phase = 1;
1740 * register_netdevice_notifier - register a network notifier block
1743 * Register a notifier to be called when network device events occur.
1744 * The notifier passed is linked into the kernel structures and must
1745 * not be reused until it has been unregistered. A negative errno code
1746 * is returned on a failure.
1748 * When registered all registration and up events are replayed
1749 * to the new notifier to allow device to have a race free
1750 * view of the network device list.
1753 int register_netdevice_notifier(struct notifier_block *nb)
1758 /* Close race with setup_net() and cleanup_net() */
1759 down_write(&pernet_ops_rwsem);
1761 err = raw_notifier_chain_register(&netdev_chain, nb);
1767 err = call_netdevice_register_net_notifiers(nb, net);
1774 up_write(&pernet_ops_rwsem);
1778 for_each_net_continue_reverse(net)
1779 call_netdevice_unregister_net_notifiers(nb, net);
1781 raw_notifier_chain_unregister(&netdev_chain, nb);
1784 EXPORT_SYMBOL(register_netdevice_notifier);
1787 * unregister_netdevice_notifier - unregister a network notifier block
1790 * Unregister a notifier previously registered by
1791 * register_netdevice_notifier(). The notifier is unlinked into the
1792 * kernel structures and may then be reused. A negative errno code
1793 * is returned on a failure.
1795 * After unregistering unregister and down device events are synthesized
1796 * for all devices on the device list to the removed notifier to remove
1797 * the need for special case cleanup code.
1800 int unregister_netdevice_notifier(struct notifier_block *nb)
1805 /* Close race with setup_net() and cleanup_net() */
1806 down_write(&pernet_ops_rwsem);
1808 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1813 call_netdevice_unregister_net_notifiers(nb, net);
1817 up_write(&pernet_ops_rwsem);
1820 EXPORT_SYMBOL(unregister_netdevice_notifier);
1822 static int __register_netdevice_notifier_net(struct net *net,
1823 struct notifier_block *nb,
1824 bool ignore_call_fail)
1828 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1834 err = call_netdevice_register_net_notifiers(nb, net);
1835 if (err && !ignore_call_fail)
1836 goto chain_unregister;
1841 raw_notifier_chain_unregister(&net->netdev_chain, nb);
1845 static int __unregister_netdevice_notifier_net(struct net *net,
1846 struct notifier_block *nb)
1850 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1854 call_netdevice_unregister_net_notifiers(nb, net);
1859 * register_netdevice_notifier_net - register a per-netns network notifier block
1860 * @net: network namespace
1863 * Register a notifier to be called when network device events occur.
1864 * The notifier passed is linked into the kernel structures and must
1865 * not be reused until it has been unregistered. A negative errno code
1866 * is returned on a failure.
1868 * When registered all registration and up events are replayed
1869 * to the new notifier to allow device to have a race free
1870 * view of the network device list.
1873 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1878 err = __register_netdevice_notifier_net(net, nb, false);
1882 EXPORT_SYMBOL(register_netdevice_notifier_net);
1885 * unregister_netdevice_notifier_net - unregister a per-netns
1886 * network notifier block
1887 * @net: network namespace
1890 * Unregister a notifier previously registered by
1891 * register_netdevice_notifier_net(). The notifier is unlinked from the
1892 * kernel structures and may then be reused. A negative errno code
1893 * is returned on a failure.
1895 * After unregistering unregister and down device events are synthesized
1896 * for all devices on the device list to the removed notifier to remove
1897 * the need for special case cleanup code.
1900 int unregister_netdevice_notifier_net(struct net *net,
1901 struct notifier_block *nb)
1906 err = __unregister_netdevice_notifier_net(net, nb);
1910 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1912 static void __move_netdevice_notifier_net(struct net *src_net,
1913 struct net *dst_net,
1914 struct notifier_block *nb)
1916 __unregister_netdevice_notifier_net(src_net, nb);
1917 __register_netdevice_notifier_net(dst_net, nb, true);
1920 int register_netdevice_notifier_dev_net(struct net_device *dev,
1921 struct notifier_block *nb,
1922 struct netdev_net_notifier *nn)
1927 err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
1930 list_add(&nn->list, &dev->net_notifier_list);
1935 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
1937 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
1938 struct notifier_block *nb,
1939 struct netdev_net_notifier *nn)
1944 list_del(&nn->list);
1945 err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
1949 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
1951 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
1954 struct netdev_net_notifier *nn;
1956 list_for_each_entry(nn, &dev->net_notifier_list, list)
1957 __move_netdevice_notifier_net(dev_net(dev), net, nn->nb);
1961 * call_netdevice_notifiers_info - call all network notifier blocks
1962 * @val: value passed unmodified to notifier function
1963 * @info: notifier information data
1965 * Call all network notifier blocks. Parameters and return value
1966 * are as for raw_notifier_call_chain().
1969 int call_netdevice_notifiers_info(unsigned long val,
1970 struct netdev_notifier_info *info)
1972 struct net *net = dev_net(info->dev);
1977 /* Run per-netns notifier block chain first, then run the global one.
1978 * Hopefully, one day, the global one is going to be removed after
1979 * all notifier block registrators get converted to be per-netns.
1981 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
1982 if (ret & NOTIFY_STOP_MASK)
1984 return raw_notifier_call_chain(&netdev_chain, val, info);
1988 * call_netdevice_notifiers_info_robust - call per-netns notifier blocks
1989 * for and rollback on error
1990 * @val_up: value passed unmodified to notifier function
1991 * @val_down: value passed unmodified to the notifier function when
1992 * recovering from an error on @val_up
1993 * @info: notifier information data
1995 * Call all per-netns network notifier blocks, but not notifier blocks on
1996 * the global notifier chain. Parameters and return value are as for
1997 * raw_notifier_call_chain_robust().
2001 call_netdevice_notifiers_info_robust(unsigned long val_up,
2002 unsigned long val_down,
2003 struct netdev_notifier_info *info)
2005 struct net *net = dev_net(info->dev);
2009 return raw_notifier_call_chain_robust(&net->netdev_chain,
2010 val_up, val_down, info);
2013 static int call_netdevice_notifiers_extack(unsigned long val,
2014 struct net_device *dev,
2015 struct netlink_ext_ack *extack)
2017 struct netdev_notifier_info info = {
2022 return call_netdevice_notifiers_info(val, &info);
2026 * call_netdevice_notifiers - call all network notifier blocks
2027 * @val: value passed unmodified to notifier function
2028 * @dev: net_device pointer passed unmodified to notifier function
2030 * Call all network notifier blocks. Parameters and return value
2031 * are as for raw_notifier_call_chain().
2034 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
2036 return call_netdevice_notifiers_extack(val, dev, NULL);
2038 EXPORT_SYMBOL(call_netdevice_notifiers);
2041 * call_netdevice_notifiers_mtu - call all network notifier blocks
2042 * @val: value passed unmodified to notifier function
2043 * @dev: net_device pointer passed unmodified to notifier function
2044 * @arg: additional u32 argument passed to the notifier function
2046 * Call all network notifier blocks. Parameters and return value
2047 * are as for raw_notifier_call_chain().
2049 static int call_netdevice_notifiers_mtu(unsigned long val,
2050 struct net_device *dev, u32 arg)
2052 struct netdev_notifier_info_ext info = {
2057 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2059 return call_netdevice_notifiers_info(val, &info.info);
2062 #ifdef CONFIG_NET_INGRESS
2063 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2065 void net_inc_ingress_queue(void)
2067 static_branch_inc(&ingress_needed_key);
2069 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2071 void net_dec_ingress_queue(void)
2073 static_branch_dec(&ingress_needed_key);
2075 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2078 #ifdef CONFIG_NET_EGRESS
2079 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2081 void net_inc_egress_queue(void)
2083 static_branch_inc(&egress_needed_key);
2085 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2087 void net_dec_egress_queue(void)
2089 static_branch_dec(&egress_needed_key);
2091 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2094 DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2095 EXPORT_SYMBOL(netstamp_needed_key);
2096 #ifdef CONFIG_JUMP_LABEL
2097 static atomic_t netstamp_needed_deferred;
2098 static atomic_t netstamp_wanted;
2099 static void netstamp_clear(struct work_struct *work)
2101 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2104 wanted = atomic_add_return(deferred, &netstamp_wanted);
2106 static_branch_enable(&netstamp_needed_key);
2108 static_branch_disable(&netstamp_needed_key);
2110 static DECLARE_WORK(netstamp_work, netstamp_clear);
2113 void net_enable_timestamp(void)
2115 #ifdef CONFIG_JUMP_LABEL
2116 int wanted = atomic_read(&netstamp_wanted);
2118 while (wanted > 0) {
2119 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted + 1))
2122 atomic_inc(&netstamp_needed_deferred);
2123 schedule_work(&netstamp_work);
2125 static_branch_inc(&netstamp_needed_key);
2128 EXPORT_SYMBOL(net_enable_timestamp);
2130 void net_disable_timestamp(void)
2132 #ifdef CONFIG_JUMP_LABEL
2133 int wanted = atomic_read(&netstamp_wanted);
2135 while (wanted > 1) {
2136 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted - 1))
2139 atomic_dec(&netstamp_needed_deferred);
2140 schedule_work(&netstamp_work);
2142 static_branch_dec(&netstamp_needed_key);
2145 EXPORT_SYMBOL(net_disable_timestamp);
2147 static inline void net_timestamp_set(struct sk_buff *skb)
2150 skb->mono_delivery_time = 0;
2151 if (static_branch_unlikely(&netstamp_needed_key))
2152 skb->tstamp = ktime_get_real();
2155 #define net_timestamp_check(COND, SKB) \
2156 if (static_branch_unlikely(&netstamp_needed_key)) { \
2157 if ((COND) && !(SKB)->tstamp) \
2158 (SKB)->tstamp = ktime_get_real(); \
2161 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2163 return __is_skb_forwardable(dev, skb, true);
2165 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2167 static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb,
2170 int ret = ____dev_forward_skb(dev, skb, check_mtu);
2173 skb->protocol = eth_type_trans(skb, dev);
2174 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2180 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2182 return __dev_forward_skb2(dev, skb, true);
2184 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2187 * dev_forward_skb - loopback an skb to another netif
2189 * @dev: destination network device
2190 * @skb: buffer to forward
2193 * NET_RX_SUCCESS (no congestion)
2194 * NET_RX_DROP (packet was dropped, but freed)
2196 * dev_forward_skb can be used for injecting an skb from the
2197 * start_xmit function of one device into the receive queue
2198 * of another device.
2200 * The receiving device may be in another namespace, so
2201 * we have to clear all information in the skb that could
2202 * impact namespace isolation.
2204 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2206 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2208 EXPORT_SYMBOL_GPL(dev_forward_skb);
2210 int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb)
2212 return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb);
2215 static inline int deliver_skb(struct sk_buff *skb,
2216 struct packet_type *pt_prev,
2217 struct net_device *orig_dev)
2219 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2221 refcount_inc(&skb->users);
2222 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2225 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2226 struct packet_type **pt,
2227 struct net_device *orig_dev,
2229 struct list_head *ptype_list)
2231 struct packet_type *ptype, *pt_prev = *pt;
2233 list_for_each_entry_rcu(ptype, ptype_list, list) {
2234 if (ptype->type != type)
2237 deliver_skb(skb, pt_prev, orig_dev);
2243 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2245 if (!ptype->af_packet_priv || !skb->sk)
2248 if (ptype->id_match)
2249 return ptype->id_match(ptype, skb->sk);
2250 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2257 * dev_nit_active - return true if any network interface taps are in use
2259 * @dev: network device to check for the presence of taps
2261 bool dev_nit_active(struct net_device *dev)
2263 return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2265 EXPORT_SYMBOL_GPL(dev_nit_active);
2268 * Support routine. Sends outgoing frames to any network
2269 * taps currently in use.
2272 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2274 struct packet_type *ptype;
2275 struct sk_buff *skb2 = NULL;
2276 struct packet_type *pt_prev = NULL;
2277 struct list_head *ptype_list = &ptype_all;
2281 list_for_each_entry_rcu(ptype, ptype_list, list) {
2282 if (ptype->ignore_outgoing)
2285 /* Never send packets back to the socket
2286 * they originated from - MvS (miquels@drinkel.ow.org)
2288 if (skb_loop_sk(ptype, skb))
2292 deliver_skb(skb2, pt_prev, skb->dev);
2297 /* need to clone skb, done only once */
2298 skb2 = skb_clone(skb, GFP_ATOMIC);
2302 net_timestamp_set(skb2);
2304 /* skb->nh should be correctly
2305 * set by sender, so that the second statement is
2306 * just protection against buggy protocols.
2308 skb_reset_mac_header(skb2);
2310 if (skb_network_header(skb2) < skb2->data ||
2311 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2312 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2313 ntohs(skb2->protocol),
2315 skb_reset_network_header(skb2);
2318 skb2->transport_header = skb2->network_header;
2319 skb2->pkt_type = PACKET_OUTGOING;
2323 if (ptype_list == &ptype_all) {
2324 ptype_list = &dev->ptype_all;
2329 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2330 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2336 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2339 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2340 * @dev: Network device
2341 * @txq: number of queues available
2343 * If real_num_tx_queues is changed the tc mappings may no longer be
2344 * valid. To resolve this verify the tc mapping remains valid and if
2345 * not NULL the mapping. With no priorities mapping to this
2346 * offset/count pair it will no longer be used. In the worst case TC0
2347 * is invalid nothing can be done so disable priority mappings. If is
2348 * expected that drivers will fix this mapping if they can before
2349 * calling netif_set_real_num_tx_queues.
2351 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2354 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2356 /* If TC0 is invalidated disable TC mapping */
2357 if (tc->offset + tc->count > txq) {
2358 netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2363 /* Invalidated prio to tc mappings set to TC0 */
2364 for (i = 1; i < TC_BITMASK + 1; i++) {
2365 int q = netdev_get_prio_tc_map(dev, i);
2367 tc = &dev->tc_to_txq[q];
2368 if (tc->offset + tc->count > txq) {
2369 netdev_warn(dev, "Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
2371 netdev_set_prio_tc_map(dev, i, 0);
2376 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2379 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2382 /* walk through the TCs and see if it falls into any of them */
2383 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2384 if ((txq - tc->offset) < tc->count)
2388 /* didn't find it, just return -1 to indicate no match */
2394 EXPORT_SYMBOL(netdev_txq_to_tc);
2397 static struct static_key xps_needed __read_mostly;
2398 static struct static_key xps_rxqs_needed __read_mostly;
2399 static DEFINE_MUTEX(xps_map_mutex);
2400 #define xmap_dereference(P) \
2401 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2403 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2404 struct xps_dev_maps *old_maps, int tci, u16 index)
2406 struct xps_map *map = NULL;
2409 map = xmap_dereference(dev_maps->attr_map[tci]);
2413 for (pos = map->len; pos--;) {
2414 if (map->queues[pos] != index)
2418 map->queues[pos] = map->queues[--map->len];
2423 RCU_INIT_POINTER(old_maps->attr_map[tci], NULL);
2424 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2425 kfree_rcu(map, rcu);
2432 static bool remove_xps_queue_cpu(struct net_device *dev,
2433 struct xps_dev_maps *dev_maps,
2434 int cpu, u16 offset, u16 count)
2436 int num_tc = dev_maps->num_tc;
2437 bool active = false;
2440 for (tci = cpu * num_tc; num_tc--; tci++) {
2443 for (i = count, j = offset; i--; j++) {
2444 if (!remove_xps_queue(dev_maps, NULL, tci, j))
2454 static void reset_xps_maps(struct net_device *dev,
2455 struct xps_dev_maps *dev_maps,
2456 enum xps_map_type type)
2458 static_key_slow_dec_cpuslocked(&xps_needed);
2459 if (type == XPS_RXQS)
2460 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2462 RCU_INIT_POINTER(dev->xps_maps[type], NULL);
2464 kfree_rcu(dev_maps, rcu);
2467 static void clean_xps_maps(struct net_device *dev, enum xps_map_type type,
2468 u16 offset, u16 count)
2470 struct xps_dev_maps *dev_maps;
2471 bool active = false;
2474 dev_maps = xmap_dereference(dev->xps_maps[type]);
2478 for (j = 0; j < dev_maps->nr_ids; j++)
2479 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count);
2481 reset_xps_maps(dev, dev_maps, type);
2483 if (type == XPS_CPUS) {
2484 for (i = offset + (count - 1); count--; i--)
2485 netdev_queue_numa_node_write(
2486 netdev_get_tx_queue(dev, i), NUMA_NO_NODE);
2490 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2493 if (!static_key_false(&xps_needed))
2497 mutex_lock(&xps_map_mutex);
2499 if (static_key_false(&xps_rxqs_needed))
2500 clean_xps_maps(dev, XPS_RXQS, offset, count);
2502 clean_xps_maps(dev, XPS_CPUS, offset, count);
2504 mutex_unlock(&xps_map_mutex);
2508 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2510 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2513 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2514 u16 index, bool is_rxqs_map)
2516 struct xps_map *new_map;
2517 int alloc_len = XPS_MIN_MAP_ALLOC;
2520 for (pos = 0; map && pos < map->len; pos++) {
2521 if (map->queues[pos] != index)
2526 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2528 if (pos < map->alloc_len)
2531 alloc_len = map->alloc_len * 2;
2534 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2538 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2540 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2541 cpu_to_node(attr_index));
2545 for (i = 0; i < pos; i++)
2546 new_map->queues[i] = map->queues[i];
2547 new_map->alloc_len = alloc_len;
2553 /* Copy xps maps at a given index */
2554 static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps,
2555 struct xps_dev_maps *new_dev_maps, int index,
2556 int tc, bool skip_tc)
2558 int i, tci = index * dev_maps->num_tc;
2559 struct xps_map *map;
2561 /* copy maps belonging to foreign traffic classes */
2562 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2563 if (i == tc && skip_tc)
2566 /* fill in the new device map from the old device map */
2567 map = xmap_dereference(dev_maps->attr_map[tci]);
2568 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2572 /* Must be called under cpus_read_lock */
2573 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2574 u16 index, enum xps_map_type type)
2576 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL;
2577 const unsigned long *online_mask = NULL;
2578 bool active = false, copy = false;
2579 int i, j, tci, numa_node_id = -2;
2580 int maps_sz, num_tc = 1, tc = 0;
2581 struct xps_map *map, *new_map;
2582 unsigned int nr_ids;
2584 WARN_ON_ONCE(index >= dev->num_tx_queues);
2587 /* Do not allow XPS on subordinate device directly */
2588 num_tc = dev->num_tc;
2592 /* If queue belongs to subordinate dev use its map */
2593 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2595 tc = netdev_txq_to_tc(dev, index);
2600 mutex_lock(&xps_map_mutex);
2602 dev_maps = xmap_dereference(dev->xps_maps[type]);
2603 if (type == XPS_RXQS) {
2604 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2605 nr_ids = dev->num_rx_queues;
2607 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2608 if (num_possible_cpus() > 1)
2609 online_mask = cpumask_bits(cpu_online_mask);
2610 nr_ids = nr_cpu_ids;
2613 if (maps_sz < L1_CACHE_BYTES)
2614 maps_sz = L1_CACHE_BYTES;
2616 /* The old dev_maps could be larger or smaller than the one we're
2617 * setting up now, as dev->num_tc or nr_ids could have been updated in
2618 * between. We could try to be smart, but let's be safe instead and only
2619 * copy foreign traffic classes if the two map sizes match.
2622 dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids)
2625 /* allocate memory for queue storage */
2626 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2628 if (!new_dev_maps) {
2629 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2630 if (!new_dev_maps) {
2631 mutex_unlock(&xps_map_mutex);
2635 new_dev_maps->nr_ids = nr_ids;
2636 new_dev_maps->num_tc = num_tc;
2639 tci = j * num_tc + tc;
2640 map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL;
2642 map = expand_xps_map(map, j, index, type == XPS_RXQS);
2646 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2650 goto out_no_new_maps;
2653 /* Increment static keys at most once per type */
2654 static_key_slow_inc_cpuslocked(&xps_needed);
2655 if (type == XPS_RXQS)
2656 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2659 for (j = 0; j < nr_ids; j++) {
2660 bool skip_tc = false;
2662 tci = j * num_tc + tc;
2663 if (netif_attr_test_mask(j, mask, nr_ids) &&
2664 netif_attr_test_online(j, online_mask, nr_ids)) {
2665 /* add tx-queue to CPU/rx-queue maps */
2670 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2671 while ((pos < map->len) && (map->queues[pos] != index))
2674 if (pos == map->len)
2675 map->queues[map->len++] = index;
2677 if (type == XPS_CPUS) {
2678 if (numa_node_id == -2)
2679 numa_node_id = cpu_to_node(j);
2680 else if (numa_node_id != cpu_to_node(j))
2687 xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc,
2691 rcu_assign_pointer(dev->xps_maps[type], new_dev_maps);
2693 /* Cleanup old maps */
2695 goto out_no_old_maps;
2697 for (j = 0; j < dev_maps->nr_ids; j++) {
2698 for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
2699 map = xmap_dereference(dev_maps->attr_map[tci]);
2704 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2709 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2710 kfree_rcu(map, rcu);
2714 old_dev_maps = dev_maps;
2717 dev_maps = new_dev_maps;
2721 if (type == XPS_CPUS)
2722 /* update Tx queue numa node */
2723 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2724 (numa_node_id >= 0) ?
2725 numa_node_id : NUMA_NO_NODE);
2730 /* removes tx-queue from unused CPUs/rx-queues */
2731 for (j = 0; j < dev_maps->nr_ids; j++) {
2732 tci = j * dev_maps->num_tc;
2734 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2736 netif_attr_test_mask(j, mask, dev_maps->nr_ids) &&
2737 netif_attr_test_online(j, online_mask, dev_maps->nr_ids))
2740 active |= remove_xps_queue(dev_maps,
2741 copy ? old_dev_maps : NULL,
2747 kfree_rcu(old_dev_maps, rcu);
2749 /* free map if not active */
2751 reset_xps_maps(dev, dev_maps, type);
2754 mutex_unlock(&xps_map_mutex);
2758 /* remove any maps that we added */
2759 for (j = 0; j < nr_ids; j++) {
2760 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2761 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2763 xmap_dereference(dev_maps->attr_map[tci]) :
2765 if (new_map && new_map != map)
2770 mutex_unlock(&xps_map_mutex);
2772 kfree(new_dev_maps);
2775 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2777 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2783 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS);
2788 EXPORT_SYMBOL(netif_set_xps_queue);
2791 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2793 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2795 /* Unbind any subordinate channels */
2796 while (txq-- != &dev->_tx[0]) {
2798 netdev_unbind_sb_channel(dev, txq->sb_dev);
2802 void netdev_reset_tc(struct net_device *dev)
2805 netif_reset_xps_queues_gt(dev, 0);
2807 netdev_unbind_all_sb_channels(dev);
2809 /* Reset TC configuration of device */
2811 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2812 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2814 EXPORT_SYMBOL(netdev_reset_tc);
2816 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2818 if (tc >= dev->num_tc)
2822 netif_reset_xps_queues(dev, offset, count);
2824 dev->tc_to_txq[tc].count = count;
2825 dev->tc_to_txq[tc].offset = offset;
2828 EXPORT_SYMBOL(netdev_set_tc_queue);
2830 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2832 if (num_tc > TC_MAX_QUEUE)
2836 netif_reset_xps_queues_gt(dev, 0);
2838 netdev_unbind_all_sb_channels(dev);
2840 dev->num_tc = num_tc;
2843 EXPORT_SYMBOL(netdev_set_num_tc);
2845 void netdev_unbind_sb_channel(struct net_device *dev,
2846 struct net_device *sb_dev)
2848 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2851 netif_reset_xps_queues_gt(sb_dev, 0);
2853 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2854 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2856 while (txq-- != &dev->_tx[0]) {
2857 if (txq->sb_dev == sb_dev)
2861 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2863 int netdev_bind_sb_channel_queue(struct net_device *dev,
2864 struct net_device *sb_dev,
2865 u8 tc, u16 count, u16 offset)
2867 /* Make certain the sb_dev and dev are already configured */
2868 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2871 /* We cannot hand out queues we don't have */
2872 if ((offset + count) > dev->real_num_tx_queues)
2875 /* Record the mapping */
2876 sb_dev->tc_to_txq[tc].count = count;
2877 sb_dev->tc_to_txq[tc].offset = offset;
2879 /* Provide a way for Tx queue to find the tc_to_txq map or
2880 * XPS map for itself.
2883 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2887 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2889 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2891 /* Do not use a multiqueue device to represent a subordinate channel */
2892 if (netif_is_multiqueue(dev))
2895 /* We allow channels 1 - 32767 to be used for subordinate channels.
2896 * Channel 0 is meant to be "native" mode and used only to represent
2897 * the main root device. We allow writing 0 to reset the device back
2898 * to normal mode after being used as a subordinate channel.
2900 if (channel > S16_MAX)
2903 dev->num_tc = -channel;
2907 EXPORT_SYMBOL(netdev_set_sb_channel);
2910 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2911 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2913 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2918 disabling = txq < dev->real_num_tx_queues;
2920 if (txq < 1 || txq > dev->num_tx_queues)
2923 if (dev->reg_state == NETREG_REGISTERED ||
2924 dev->reg_state == NETREG_UNREGISTERING) {
2927 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2933 netif_setup_tc(dev, txq);
2935 dev_qdisc_change_real_num_tx(dev, txq);
2937 dev->real_num_tx_queues = txq;
2941 qdisc_reset_all_tx_gt(dev, txq);
2943 netif_reset_xps_queues_gt(dev, txq);
2947 dev->real_num_tx_queues = txq;
2952 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2956 * netif_set_real_num_rx_queues - set actual number of RX queues used
2957 * @dev: Network device
2958 * @rxq: Actual number of RX queues
2960 * This must be called either with the rtnl_lock held or before
2961 * registration of the net device. Returns 0 on success, or a
2962 * negative error code. If called before registration, it always
2965 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2969 if (rxq < 1 || rxq > dev->num_rx_queues)
2972 if (dev->reg_state == NETREG_REGISTERED) {
2975 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2981 dev->real_num_rx_queues = rxq;
2984 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2988 * netif_set_real_num_queues - set actual number of RX and TX queues used
2989 * @dev: Network device
2990 * @txq: Actual number of TX queues
2991 * @rxq: Actual number of RX queues
2993 * Set the real number of both TX and RX queues.
2994 * Does nothing if the number of queues is already correct.
2996 int netif_set_real_num_queues(struct net_device *dev,
2997 unsigned int txq, unsigned int rxq)
2999 unsigned int old_rxq = dev->real_num_rx_queues;
3002 if (txq < 1 || txq > dev->num_tx_queues ||
3003 rxq < 1 || rxq > dev->num_rx_queues)
3006 /* Start from increases, so the error path only does decreases -
3007 * decreases can't fail.
3009 if (rxq > dev->real_num_rx_queues) {
3010 err = netif_set_real_num_rx_queues(dev, rxq);
3014 if (txq > dev->real_num_tx_queues) {
3015 err = netif_set_real_num_tx_queues(dev, txq);
3019 if (rxq < dev->real_num_rx_queues)
3020 WARN_ON(netif_set_real_num_rx_queues(dev, rxq));
3021 if (txq < dev->real_num_tx_queues)
3022 WARN_ON(netif_set_real_num_tx_queues(dev, txq));
3026 WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq));
3029 EXPORT_SYMBOL(netif_set_real_num_queues);
3032 * netif_set_tso_max_size() - set the max size of TSO frames supported
3033 * @dev: netdev to update
3034 * @size: max skb->len of a TSO frame
3036 * Set the limit on the size of TSO super-frames the device can handle.
3037 * Unless explicitly set the stack will assume the value of
3038 * %GSO_LEGACY_MAX_SIZE.
3040 void netif_set_tso_max_size(struct net_device *dev, unsigned int size)
3042 dev->tso_max_size = min(GSO_MAX_SIZE, size);
3043 if (size < READ_ONCE(dev->gso_max_size))
3044 netif_set_gso_max_size(dev, size);
3045 if (size < READ_ONCE(dev->gso_ipv4_max_size))
3046 netif_set_gso_ipv4_max_size(dev, size);
3048 EXPORT_SYMBOL(netif_set_tso_max_size);
3051 * netif_set_tso_max_segs() - set the max number of segs supported for TSO
3052 * @dev: netdev to update
3053 * @segs: max number of TCP segments
3055 * Set the limit on the number of TCP segments the device can generate from
3056 * a single TSO super-frame.
3057 * Unless explicitly set the stack will assume the value of %GSO_MAX_SEGS.
3059 void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs)
3061 dev->tso_max_segs = segs;
3062 if (segs < READ_ONCE(dev->gso_max_segs))
3063 netif_set_gso_max_segs(dev, segs);
3065 EXPORT_SYMBOL(netif_set_tso_max_segs);
3068 * netif_inherit_tso_max() - copy all TSO limits from a lower device to an upper
3069 * @to: netdev to update
3070 * @from: netdev from which to copy the limits
3072 void netif_inherit_tso_max(struct net_device *to, const struct net_device *from)
3074 netif_set_tso_max_size(to, from->tso_max_size);
3075 netif_set_tso_max_segs(to, from->tso_max_segs);
3077 EXPORT_SYMBOL(netif_inherit_tso_max);
3080 * netif_get_num_default_rss_queues - default number of RSS queues
3082 * Default value is the number of physical cores if there are only 1 or 2, or
3083 * divided by 2 if there are more.
3085 int netif_get_num_default_rss_queues(void)
3090 if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL)))
3093 cpumask_copy(cpus, cpu_online_mask);
3094 for_each_cpu(cpu, cpus) {
3096 cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu));
3098 free_cpumask_var(cpus);
3100 return count > 2 ? DIV_ROUND_UP(count, 2) : count;
3102 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3104 static void __netif_reschedule(struct Qdisc *q)
3106 struct softnet_data *sd;
3107 unsigned long flags;
3109 local_irq_save(flags);
3110 sd = this_cpu_ptr(&softnet_data);
3111 q->next_sched = NULL;
3112 *sd->output_queue_tailp = q;
3113 sd->output_queue_tailp = &q->next_sched;
3114 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3115 local_irq_restore(flags);
3118 void __netif_schedule(struct Qdisc *q)
3120 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3121 __netif_reschedule(q);
3123 EXPORT_SYMBOL(__netif_schedule);
3125 struct dev_kfree_skb_cb {
3126 enum skb_drop_reason reason;
3129 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3131 return (struct dev_kfree_skb_cb *)skb->cb;
3134 void netif_schedule_queue(struct netdev_queue *txq)
3137 if (!netif_xmit_stopped(txq)) {
3138 struct Qdisc *q = rcu_dereference(txq->qdisc);
3140 __netif_schedule(q);
3144 EXPORT_SYMBOL(netif_schedule_queue);
3146 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3148 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3152 q = rcu_dereference(dev_queue->qdisc);
3153 __netif_schedule(q);
3157 EXPORT_SYMBOL(netif_tx_wake_queue);
3159 void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3161 unsigned long flags;
3166 if (likely(refcount_read(&skb->users) == 1)) {
3168 refcount_set(&skb->users, 0);
3169 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3172 get_kfree_skb_cb(skb)->reason = reason;
3173 local_irq_save(flags);
3174 skb->next = __this_cpu_read(softnet_data.completion_queue);
3175 __this_cpu_write(softnet_data.completion_queue, skb);
3176 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3177 local_irq_restore(flags);
3179 EXPORT_SYMBOL(dev_kfree_skb_irq_reason);
3181 void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3183 if (in_hardirq() || irqs_disabled())
3184 dev_kfree_skb_irq_reason(skb, reason);
3186 kfree_skb_reason(skb, reason);
3188 EXPORT_SYMBOL(dev_kfree_skb_any_reason);
3192 * netif_device_detach - mark device as removed
3193 * @dev: network device
3195 * Mark device as removed from system and therefore no longer available.
3197 void netif_device_detach(struct net_device *dev)
3199 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3200 netif_running(dev)) {
3201 netif_tx_stop_all_queues(dev);
3204 EXPORT_SYMBOL(netif_device_detach);
3207 * netif_device_attach - mark device as attached
3208 * @dev: network device
3210 * Mark device as attached from system and restart if needed.
3212 void netif_device_attach(struct net_device *dev)
3214 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3215 netif_running(dev)) {
3216 netif_tx_wake_all_queues(dev);
3217 __netdev_watchdog_up(dev);
3220 EXPORT_SYMBOL(netif_device_attach);
3223 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3224 * to be used as a distribution range.
3226 static u16 skb_tx_hash(const struct net_device *dev,
3227 const struct net_device *sb_dev,
3228 struct sk_buff *skb)
3232 u16 qcount = dev->real_num_tx_queues;
3235 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3237 qoffset = sb_dev->tc_to_txq[tc].offset;
3238 qcount = sb_dev->tc_to_txq[tc].count;
3239 if (unlikely(!qcount)) {
3240 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3241 sb_dev->name, qoffset, tc);
3243 qcount = dev->real_num_tx_queues;
3247 if (skb_rx_queue_recorded(skb)) {
3248 DEBUG_NET_WARN_ON_ONCE(qcount == 0);
3249 hash = skb_get_rx_queue(skb);
3250 if (hash >= qoffset)
3252 while (unlikely(hash >= qcount))
3254 return hash + qoffset;
3257 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3260 void skb_warn_bad_offload(const struct sk_buff *skb)
3262 static const netdev_features_t null_features;
3263 struct net_device *dev = skb->dev;
3264 const char *name = "";
3266 if (!net_ratelimit())
3270 if (dev->dev.parent)
3271 name = dev_driver_string(dev->dev.parent);
3273 name = netdev_name(dev);
3275 skb_dump(KERN_WARNING, skb, false);
3276 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3277 name, dev ? &dev->features : &null_features,
3278 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3282 * Invalidate hardware checksum when packet is to be mangled, and
3283 * complete checksum manually on outgoing path.
3285 int skb_checksum_help(struct sk_buff *skb)
3288 int ret = 0, offset;
3290 if (skb->ip_summed == CHECKSUM_COMPLETE)
3291 goto out_set_summed;
3293 if (unlikely(skb_is_gso(skb))) {
3294 skb_warn_bad_offload(skb);
3298 /* Before computing a checksum, we should make sure no frag could
3299 * be modified by an external entity : checksum could be wrong.
3301 if (skb_has_shared_frag(skb)) {
3302 ret = __skb_linearize(skb);
3307 offset = skb_checksum_start_offset(skb);
3309 if (unlikely(offset >= skb_headlen(skb))) {
3310 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3311 WARN_ONCE(true, "offset (%d) >= skb_headlen() (%u)\n",
3312 offset, skb_headlen(skb));
3315 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3317 offset += skb->csum_offset;
3318 if (unlikely(offset + sizeof(__sum16) > skb_headlen(skb))) {
3319 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3320 WARN_ONCE(true, "offset+2 (%zu) > skb_headlen() (%u)\n",
3321 offset + sizeof(__sum16), skb_headlen(skb));
3324 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3328 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3330 skb->ip_summed = CHECKSUM_NONE;
3334 EXPORT_SYMBOL(skb_checksum_help);
3336 int skb_crc32c_csum_help(struct sk_buff *skb)
3339 int ret = 0, offset, start;
3341 if (skb->ip_summed != CHECKSUM_PARTIAL)
3344 if (unlikely(skb_is_gso(skb)))
3347 /* Before computing a checksum, we should make sure no frag could
3348 * be modified by an external entity : checksum could be wrong.
3350 if (unlikely(skb_has_shared_frag(skb))) {
3351 ret = __skb_linearize(skb);
3355 start = skb_checksum_start_offset(skb);
3356 offset = start + offsetof(struct sctphdr, checksum);
3357 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3362 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3366 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3367 skb->len - start, ~(__u32)0,
3369 *(__le32 *)(skb->data + offset) = crc32c_csum;
3370 skb_reset_csum_not_inet(skb);
3375 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3377 __be16 type = skb->protocol;
3379 /* Tunnel gso handlers can set protocol to ethernet. */
3380 if (type == htons(ETH_P_TEB)) {
3383 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3386 eth = (struct ethhdr *)skb->data;
3387 type = eth->h_proto;
3390 return vlan_get_protocol_and_depth(skb, type, depth);
3394 /* Take action when hardware reception checksum errors are detected. */
3396 static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3398 netdev_err(dev, "hw csum failure\n");
3399 skb_dump(KERN_ERR, skb, true);
3403 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3405 DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb);
3407 EXPORT_SYMBOL(netdev_rx_csum_fault);
3410 /* XXX: check that highmem exists at all on the given machine. */
3411 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3413 #ifdef CONFIG_HIGHMEM
3416 if (!(dev->features & NETIF_F_HIGHDMA)) {
3417 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3418 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3420 if (PageHighMem(skb_frag_page(frag)))
3428 /* If MPLS offload request, verify we are testing hardware MPLS features
3429 * instead of standard features for the netdev.
3431 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3432 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3433 netdev_features_t features,
3436 if (eth_p_mpls(type))
3437 features &= skb->dev->mpls_features;
3442 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3443 netdev_features_t features,
3450 static netdev_features_t harmonize_features(struct sk_buff *skb,
3451 netdev_features_t features)
3455 type = skb_network_protocol(skb, NULL);
3456 features = net_mpls_features(skb, features, type);
3458 if (skb->ip_summed != CHECKSUM_NONE &&
3459 !can_checksum_protocol(features, type)) {
3460 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3462 if (illegal_highdma(skb->dev, skb))
3463 features &= ~NETIF_F_SG;
3468 netdev_features_t passthru_features_check(struct sk_buff *skb,
3469 struct net_device *dev,
3470 netdev_features_t features)
3474 EXPORT_SYMBOL(passthru_features_check);
3476 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3477 struct net_device *dev,
3478 netdev_features_t features)
3480 return vlan_features_check(skb, features);
3483 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3484 struct net_device *dev,
3485 netdev_features_t features)
3487 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3489 if (gso_segs > READ_ONCE(dev->gso_max_segs))
3490 return features & ~NETIF_F_GSO_MASK;
3492 if (!skb_shinfo(skb)->gso_type) {
3493 skb_warn_bad_offload(skb);
3494 return features & ~NETIF_F_GSO_MASK;
3497 /* Support for GSO partial features requires software
3498 * intervention before we can actually process the packets
3499 * so we need to strip support for any partial features now
3500 * and we can pull them back in after we have partially
3501 * segmented the frame.
3503 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3504 features &= ~dev->gso_partial_features;
3506 /* Make sure to clear the IPv4 ID mangling feature if the
3507 * IPv4 header has the potential to be fragmented.
3509 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3510 struct iphdr *iph = skb->encapsulation ?
3511 inner_ip_hdr(skb) : ip_hdr(skb);
3513 if (!(iph->frag_off & htons(IP_DF)))
3514 features &= ~NETIF_F_TSO_MANGLEID;
3520 netdev_features_t netif_skb_features(struct sk_buff *skb)
3522 struct net_device *dev = skb->dev;
3523 netdev_features_t features = dev->features;
3525 if (skb_is_gso(skb))
3526 features = gso_features_check(skb, dev, features);
3528 /* If encapsulation offload request, verify we are testing
3529 * hardware encapsulation features instead of standard
3530 * features for the netdev
3532 if (skb->encapsulation)
3533 features &= dev->hw_enc_features;
3535 if (skb_vlan_tagged(skb))
3536 features = netdev_intersect_features(features,
3537 dev->vlan_features |
3538 NETIF_F_HW_VLAN_CTAG_TX |
3539 NETIF_F_HW_VLAN_STAG_TX);
3541 if (dev->netdev_ops->ndo_features_check)
3542 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3545 features &= dflt_features_check(skb, dev, features);
3547 return harmonize_features(skb, features);
3549 EXPORT_SYMBOL(netif_skb_features);
3551 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3552 struct netdev_queue *txq, bool more)
3557 if (dev_nit_active(dev))
3558 dev_queue_xmit_nit(skb, dev);
3561 trace_net_dev_start_xmit(skb, dev);
3562 rc = netdev_start_xmit(skb, dev, txq, more);
3563 trace_net_dev_xmit(skb, rc, dev, len);
3568 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3569 struct netdev_queue *txq, int *ret)
3571 struct sk_buff *skb = first;
3572 int rc = NETDEV_TX_OK;
3575 struct sk_buff *next = skb->next;
3577 skb_mark_not_on_list(skb);
3578 rc = xmit_one(skb, dev, txq, next != NULL);
3579 if (unlikely(!dev_xmit_complete(rc))) {
3585 if (netif_tx_queue_stopped(txq) && skb) {
3586 rc = NETDEV_TX_BUSY;
3596 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3597 netdev_features_t features)
3599 if (skb_vlan_tag_present(skb) &&
3600 !vlan_hw_offload_capable(features, skb->vlan_proto))
3601 skb = __vlan_hwaccel_push_inside(skb);
3605 int skb_csum_hwoffload_help(struct sk_buff *skb,
3606 const netdev_features_t features)
3608 if (unlikely(skb_csum_is_sctp(skb)))
3609 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3610 skb_crc32c_csum_help(skb);
3612 if (features & NETIF_F_HW_CSUM)
3615 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
3616 switch (skb->csum_offset) {
3617 case offsetof(struct tcphdr, check):
3618 case offsetof(struct udphdr, check):
3623 return skb_checksum_help(skb);
3625 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3627 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3629 netdev_features_t features;
3631 features = netif_skb_features(skb);
3632 skb = validate_xmit_vlan(skb, features);
3636 skb = sk_validate_xmit_skb(skb, dev);
3640 if (netif_needs_gso(skb, features)) {
3641 struct sk_buff *segs;
3643 segs = skb_gso_segment(skb, features);
3651 if (skb_needs_linearize(skb, features) &&
3652 __skb_linearize(skb))
3655 /* If packet is not checksummed and device does not
3656 * support checksumming for this protocol, complete
3657 * checksumming here.
3659 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3660 if (skb->encapsulation)
3661 skb_set_inner_transport_header(skb,
3662 skb_checksum_start_offset(skb));
3664 skb_set_transport_header(skb,
3665 skb_checksum_start_offset(skb));
3666 if (skb_csum_hwoffload_help(skb, features))
3671 skb = validate_xmit_xfrm(skb, features, again);
3678 dev_core_stats_tx_dropped_inc(dev);
3682 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3684 struct sk_buff *next, *head = NULL, *tail;
3686 for (; skb != NULL; skb = next) {
3688 skb_mark_not_on_list(skb);
3690 /* in case skb wont be segmented, point to itself */
3693 skb = validate_xmit_skb(skb, dev, again);
3701 /* If skb was segmented, skb->prev points to
3702 * the last segment. If not, it still contains skb.
3708 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3710 static void qdisc_pkt_len_init(struct sk_buff *skb)
3712 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3714 qdisc_skb_cb(skb)->pkt_len = skb->len;
3716 /* To get more precise estimation of bytes sent on wire,
3717 * we add to pkt_len the headers size of all segments
3719 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3720 u16 gso_segs = shinfo->gso_segs;
3721 unsigned int hdr_len;
3723 /* mac layer + network layer */
3724 hdr_len = skb_transport_offset(skb);
3726 /* + transport layer */
3727 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3728 const struct tcphdr *th;
3729 struct tcphdr _tcphdr;
3731 th = skb_header_pointer(skb, hdr_len,
3732 sizeof(_tcphdr), &_tcphdr);
3734 hdr_len += __tcp_hdrlen(th);
3736 struct udphdr _udphdr;
3738 if (skb_header_pointer(skb, hdr_len,
3739 sizeof(_udphdr), &_udphdr))
3740 hdr_len += sizeof(struct udphdr);
3743 if (shinfo->gso_type & SKB_GSO_DODGY)
3744 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3747 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3751 static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q,
3752 struct sk_buff **to_free,
3753 struct netdev_queue *txq)
3757 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK;
3758 if (rc == NET_XMIT_SUCCESS)
3759 trace_qdisc_enqueue(q, txq, skb);
3763 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3764 struct net_device *dev,
3765 struct netdev_queue *txq)
3767 spinlock_t *root_lock = qdisc_lock(q);
3768 struct sk_buff *to_free = NULL;
3772 qdisc_calculate_pkt_len(skb, q);
3774 if (q->flags & TCQ_F_NOLOCK) {
3775 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) &&
3776 qdisc_run_begin(q)) {
3777 /* Retest nolock_qdisc_is_empty() within the protection
3778 * of q->seqlock to protect from racing with requeuing.
3780 if (unlikely(!nolock_qdisc_is_empty(q))) {
3781 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3788 qdisc_bstats_cpu_update(q, skb);
3789 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) &&
3790 !nolock_qdisc_is_empty(q))
3794 return NET_XMIT_SUCCESS;
3797 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3801 if (unlikely(to_free))
3802 kfree_skb_list_reason(to_free,
3803 SKB_DROP_REASON_QDISC_DROP);
3808 * Heuristic to force contended enqueues to serialize on a
3809 * separate lock before trying to get qdisc main lock.
3810 * This permits qdisc->running owner to get the lock more
3811 * often and dequeue packets faster.
3812 * On PREEMPT_RT it is possible to preempt the qdisc owner during xmit
3813 * and then other tasks will only enqueue packets. The packets will be
3814 * sent after the qdisc owner is scheduled again. To prevent this
3815 * scenario the task always serialize on the lock.
3817 contended = qdisc_is_running(q) || IS_ENABLED(CONFIG_PREEMPT_RT);
3818 if (unlikely(contended))
3819 spin_lock(&q->busylock);
3821 spin_lock(root_lock);
3822 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3823 __qdisc_drop(skb, &to_free);
3825 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3826 qdisc_run_begin(q)) {
3828 * This is a work-conserving queue; there are no old skbs
3829 * waiting to be sent out; and the qdisc is not running -
3830 * xmit the skb directly.
3833 qdisc_bstats_update(q, skb);
3835 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3836 if (unlikely(contended)) {
3837 spin_unlock(&q->busylock);
3844 rc = NET_XMIT_SUCCESS;
3846 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3847 if (qdisc_run_begin(q)) {
3848 if (unlikely(contended)) {
3849 spin_unlock(&q->busylock);
3856 spin_unlock(root_lock);
3857 if (unlikely(to_free))
3858 kfree_skb_list_reason(to_free, SKB_DROP_REASON_QDISC_DROP);
3859 if (unlikely(contended))
3860 spin_unlock(&q->busylock);
3864 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3865 static void skb_update_prio(struct sk_buff *skb)
3867 const struct netprio_map *map;
3868 const struct sock *sk;
3869 unsigned int prioidx;
3873 map = rcu_dereference_bh(skb->dev->priomap);
3876 sk = skb_to_full_sk(skb);
3880 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3882 if (prioidx < map->priomap_len)
3883 skb->priority = map->priomap[prioidx];
3886 #define skb_update_prio(skb)
3890 * dev_loopback_xmit - loop back @skb
3891 * @net: network namespace this loopback is happening in
3892 * @sk: sk needed to be a netfilter okfn
3893 * @skb: buffer to transmit
3895 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3897 skb_reset_mac_header(skb);
3898 __skb_pull(skb, skb_network_offset(skb));
3899 skb->pkt_type = PACKET_LOOPBACK;
3900 if (skb->ip_summed == CHECKSUM_NONE)
3901 skb->ip_summed = CHECKSUM_UNNECESSARY;
3902 DEBUG_NET_WARN_ON_ONCE(!skb_dst(skb));
3907 EXPORT_SYMBOL(dev_loopback_xmit);
3909 #ifdef CONFIG_NET_EGRESS
3910 static struct netdev_queue *
3911 netdev_tx_queue_mapping(struct net_device *dev, struct sk_buff *skb)
3913 int qm = skb_get_queue_mapping(skb);
3915 return netdev_get_tx_queue(dev, netdev_cap_txqueue(dev, qm));
3918 static bool netdev_xmit_txqueue_skipped(void)
3920 return __this_cpu_read(softnet_data.xmit.skip_txqueue);
3923 void netdev_xmit_skip_txqueue(bool skip)
3925 __this_cpu_write(softnet_data.xmit.skip_txqueue, skip);
3927 EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
3928 #endif /* CONFIG_NET_EGRESS */
3930 #ifdef CONFIG_NET_XGRESS
3931 static int tc_run(struct tcx_entry *entry, struct sk_buff *skb)
3933 int ret = TC_ACT_UNSPEC;
3934 #ifdef CONFIG_NET_CLS_ACT
3935 struct mini_Qdisc *miniq = rcu_dereference_bh(entry->miniq);
3936 struct tcf_result res;
3941 tc_skb_cb(skb)->mru = 0;
3942 tc_skb_cb(skb)->post_ct = false;
3944 mini_qdisc_bstats_cpu_update(miniq, skb);
3945 ret = tcf_classify(skb, miniq->block, miniq->filter_list, &res, false);
3946 /* Only tcf related quirks below. */
3949 mini_qdisc_qstats_cpu_drop(miniq);
3952 case TC_ACT_RECLASSIFY:
3953 skb->tc_index = TC_H_MIN(res.classid);
3956 #endif /* CONFIG_NET_CLS_ACT */
3960 static DEFINE_STATIC_KEY_FALSE(tcx_needed_key);
3964 static_branch_inc(&tcx_needed_key);
3969 static_branch_dec(&tcx_needed_key);
3972 static __always_inline enum tcx_action_base
3973 tcx_run(const struct bpf_mprog_entry *entry, struct sk_buff *skb,
3974 const bool needs_mac)
3976 const struct bpf_mprog_fp *fp;
3977 const struct bpf_prog *prog;
3981 __skb_push(skb, skb->mac_len);
3982 bpf_mprog_foreach_prog(entry, fp, prog) {
3983 bpf_compute_data_pointers(skb);
3984 ret = bpf_prog_run(prog, skb);
3985 if (ret != TCX_NEXT)
3989 __skb_pull(skb, skb->mac_len);
3990 return tcx_action_code(skb, ret);
3993 static __always_inline struct sk_buff *
3994 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
3995 struct net_device *orig_dev, bool *another)
3997 struct bpf_mprog_entry *entry = rcu_dereference_bh(skb->dev->tcx_ingress);
4003 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4007 qdisc_skb_cb(skb)->pkt_len = skb->len;
4008 tcx_set_ingress(skb, true);
4010 if (static_branch_unlikely(&tcx_needed_key)) {
4011 sch_ret = tcx_run(entry, skb, true);
4012 if (sch_ret != TC_ACT_UNSPEC)
4013 goto ingress_verdict;
4015 sch_ret = tc_run(tcx_entry(entry), skb);
4018 case TC_ACT_REDIRECT:
4019 /* skb_mac_header check was done by BPF, so we can safely
4020 * push the L2 header back before redirecting to another
4023 __skb_push(skb, skb->mac_len);
4024 if (skb_do_redirect(skb) == -EAGAIN) {
4025 __skb_pull(skb, skb->mac_len);
4029 *ret = NET_RX_SUCCESS;
4032 kfree_skb_reason(skb, SKB_DROP_REASON_TC_INGRESS);
4035 /* used by tc_run */
4041 case TC_ACT_CONSUMED:
4042 *ret = NET_RX_SUCCESS;
4049 static __always_inline struct sk_buff *
4050 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
4052 struct bpf_mprog_entry *entry = rcu_dereference_bh(dev->tcx_egress);
4058 /* qdisc_skb_cb(skb)->pkt_len & tcx_set_ingress() was
4059 * already set by the caller.
4061 if (static_branch_unlikely(&tcx_needed_key)) {
4062 sch_ret = tcx_run(entry, skb, false);
4063 if (sch_ret != TC_ACT_UNSPEC)
4064 goto egress_verdict;
4066 sch_ret = tc_run(tcx_entry(entry), skb);
4069 case TC_ACT_REDIRECT:
4070 /* No need to push/pop skb's mac_header here on egress! */
4071 skb_do_redirect(skb);
4072 *ret = NET_XMIT_SUCCESS;
4075 kfree_skb_reason(skb, SKB_DROP_REASON_TC_EGRESS);
4076 *ret = NET_XMIT_DROP;
4078 /* used by tc_run */
4084 case TC_ACT_CONSUMED:
4085 *ret = NET_XMIT_SUCCESS;
4092 static __always_inline struct sk_buff *
4093 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4094 struct net_device *orig_dev, bool *another)
4099 static __always_inline struct sk_buff *
4100 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
4104 #endif /* CONFIG_NET_XGRESS */
4107 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
4108 struct xps_dev_maps *dev_maps, unsigned int tci)
4110 int tc = netdev_get_prio_tc_map(dev, skb->priority);
4111 struct xps_map *map;
4112 int queue_index = -1;
4114 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids)
4117 tci *= dev_maps->num_tc;
4120 map = rcu_dereference(dev_maps->attr_map[tci]);
4123 queue_index = map->queues[0];
4125 queue_index = map->queues[reciprocal_scale(
4126 skb_get_hash(skb), map->len)];
4127 if (unlikely(queue_index >= dev->real_num_tx_queues))
4134 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
4135 struct sk_buff *skb)
4138 struct xps_dev_maps *dev_maps;
4139 struct sock *sk = skb->sk;
4140 int queue_index = -1;
4142 if (!static_key_false(&xps_needed))
4146 if (!static_key_false(&xps_rxqs_needed))
4149 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]);
4151 int tci = sk_rx_queue_get(sk);
4154 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4159 if (queue_index < 0) {
4160 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]);
4162 unsigned int tci = skb->sender_cpu - 1;
4164 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4176 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
4177 struct net_device *sb_dev)
4181 EXPORT_SYMBOL(dev_pick_tx_zero);
4183 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
4184 struct net_device *sb_dev)
4186 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
4188 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
4190 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4191 struct net_device *sb_dev)
4193 struct sock *sk = skb->sk;
4194 int queue_index = sk_tx_queue_get(sk);
4196 sb_dev = sb_dev ? : dev;
4198 if (queue_index < 0 || skb->ooo_okay ||
4199 queue_index >= dev->real_num_tx_queues) {
4200 int new_index = get_xps_queue(dev, sb_dev, skb);
4203 new_index = skb_tx_hash(dev, sb_dev, skb);
4205 if (queue_index != new_index && sk &&
4207 rcu_access_pointer(sk->sk_dst_cache))
4208 sk_tx_queue_set(sk, new_index);
4210 queue_index = new_index;
4215 EXPORT_SYMBOL(netdev_pick_tx);
4217 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4218 struct sk_buff *skb,
4219 struct net_device *sb_dev)
4221 int queue_index = 0;
4224 u32 sender_cpu = skb->sender_cpu - 1;
4226 if (sender_cpu >= (u32)NR_CPUS)
4227 skb->sender_cpu = raw_smp_processor_id() + 1;
4230 if (dev->real_num_tx_queues != 1) {
4231 const struct net_device_ops *ops = dev->netdev_ops;
4233 if (ops->ndo_select_queue)
4234 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4236 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4238 queue_index = netdev_cap_txqueue(dev, queue_index);
4241 skb_set_queue_mapping(skb, queue_index);
4242 return netdev_get_tx_queue(dev, queue_index);
4246 * __dev_queue_xmit() - transmit a buffer
4247 * @skb: buffer to transmit
4248 * @sb_dev: suboordinate device used for L2 forwarding offload
4250 * Queue a buffer for transmission to a network device. The caller must
4251 * have set the device and priority and built the buffer before calling
4252 * this function. The function can be called from an interrupt.
4254 * When calling this method, interrupts MUST be enabled. This is because
4255 * the BH enable code must have IRQs enabled so that it will not deadlock.
4257 * Regardless of the return value, the skb is consumed, so it is currently
4258 * difficult to retry a send to this method. (You can bump the ref count
4259 * before sending to hold a reference for retry if you are careful.)
4262 * * 0 - buffer successfully transmitted
4263 * * positive qdisc return code - NET_XMIT_DROP etc.
4264 * * negative errno - other errors
4266 int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4268 struct net_device *dev = skb->dev;
4269 struct netdev_queue *txq = NULL;
4274 skb_reset_mac_header(skb);
4275 skb_assert_len(skb);
4277 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4278 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED);
4280 /* Disable soft irqs for various locks below. Also
4281 * stops preemption for RCU.
4285 skb_update_prio(skb);
4287 qdisc_pkt_len_init(skb);
4288 tcx_set_ingress(skb, false);
4289 #ifdef CONFIG_NET_EGRESS
4290 if (static_branch_unlikely(&egress_needed_key)) {
4291 if (nf_hook_egress_active()) {
4292 skb = nf_hook_egress(skb, &rc, dev);
4297 netdev_xmit_skip_txqueue(false);
4299 nf_skip_egress(skb, true);
4300 skb = sch_handle_egress(skb, &rc, dev);
4303 nf_skip_egress(skb, false);
4305 if (netdev_xmit_txqueue_skipped())
4306 txq = netdev_tx_queue_mapping(dev, skb);
4309 /* If device/qdisc don't need skb->dst, release it right now while
4310 * its hot in this cpu cache.
4312 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4318 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4320 q = rcu_dereference_bh(txq->qdisc);
4322 trace_net_dev_queue(skb);
4324 rc = __dev_xmit_skb(skb, q, dev, txq);
4328 /* The device has no queue. Common case for software devices:
4329 * loopback, all the sorts of tunnels...
4331 * Really, it is unlikely that netif_tx_lock protection is necessary
4332 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4334 * However, it is possible, that they rely on protection
4337 * Check this and shot the lock. It is not prone from deadlocks.
4338 *Either shot noqueue qdisc, it is even simpler 8)
4340 if (dev->flags & IFF_UP) {
4341 int cpu = smp_processor_id(); /* ok because BHs are off */
4343 /* Other cpus might concurrently change txq->xmit_lock_owner
4344 * to -1 or to their cpu id, but not to our id.
4346 if (READ_ONCE(txq->xmit_lock_owner) != cpu) {
4347 if (dev_xmit_recursion())
4348 goto recursion_alert;
4350 skb = validate_xmit_skb(skb, dev, &again);
4354 HARD_TX_LOCK(dev, txq, cpu);
4356 if (!netif_xmit_stopped(txq)) {
4357 dev_xmit_recursion_inc();
4358 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4359 dev_xmit_recursion_dec();
4360 if (dev_xmit_complete(rc)) {
4361 HARD_TX_UNLOCK(dev, txq);
4365 HARD_TX_UNLOCK(dev, txq);
4366 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4369 /* Recursion is detected! It is possible,
4373 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4379 rcu_read_unlock_bh();
4381 dev_core_stats_tx_dropped_inc(dev);
4382 kfree_skb_list(skb);
4385 rcu_read_unlock_bh();
4388 EXPORT_SYMBOL(__dev_queue_xmit);
4390 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4392 struct net_device *dev = skb->dev;
4393 struct sk_buff *orig_skb = skb;
4394 struct netdev_queue *txq;
4395 int ret = NETDEV_TX_BUSY;
4398 if (unlikely(!netif_running(dev) ||
4399 !netif_carrier_ok(dev)))
4402 skb = validate_xmit_skb_list(skb, dev, &again);
4403 if (skb != orig_skb)
4406 skb_set_queue_mapping(skb, queue_id);
4407 txq = skb_get_tx_queue(dev, skb);
4411 dev_xmit_recursion_inc();
4412 HARD_TX_LOCK(dev, txq, smp_processor_id());
4413 if (!netif_xmit_frozen_or_drv_stopped(txq))
4414 ret = netdev_start_xmit(skb, dev, txq, false);
4415 HARD_TX_UNLOCK(dev, txq);
4416 dev_xmit_recursion_dec();
4421 dev_core_stats_tx_dropped_inc(dev);
4422 kfree_skb_list(skb);
4423 return NET_XMIT_DROP;
4425 EXPORT_SYMBOL(__dev_direct_xmit);
4427 /*************************************************************************
4429 *************************************************************************/
4431 int netdev_max_backlog __read_mostly = 1000;
4432 EXPORT_SYMBOL(netdev_max_backlog);
4434 int netdev_tstamp_prequeue __read_mostly = 1;
4435 unsigned int sysctl_skb_defer_max __read_mostly = 64;
4436 int netdev_budget __read_mostly = 300;
4437 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4438 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4439 int weight_p __read_mostly = 64; /* old backlog weight */
4440 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4441 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4442 int dev_rx_weight __read_mostly = 64;
4443 int dev_tx_weight __read_mostly = 64;
4445 /* Called with irq disabled */
4446 static inline void ____napi_schedule(struct softnet_data *sd,
4447 struct napi_struct *napi)
4449 struct task_struct *thread;
4451 lockdep_assert_irqs_disabled();
4453 if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
4454 /* Paired with smp_mb__before_atomic() in
4455 * napi_enable()/dev_set_threaded().
4456 * Use READ_ONCE() to guarantee a complete
4457 * read on napi->thread. Only call
4458 * wake_up_process() when it's not NULL.
4460 thread = READ_ONCE(napi->thread);
4462 /* Avoid doing set_bit() if the thread is in
4463 * INTERRUPTIBLE state, cause napi_thread_wait()
4464 * makes sure to proceed with napi polling
4465 * if the thread is explicitly woken from here.
4467 if (READ_ONCE(thread->__state) != TASK_INTERRUPTIBLE)
4468 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
4469 wake_up_process(thread);
4474 list_add_tail(&napi->poll_list, &sd->poll_list);
4475 WRITE_ONCE(napi->list_owner, smp_processor_id());
4476 /* If not called from net_rx_action()
4477 * we have to raise NET_RX_SOFTIRQ.
4479 if (!sd->in_net_rx_action)
4480 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4485 /* One global table that all flow-based protocols share. */
4486 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4487 EXPORT_SYMBOL(rps_sock_flow_table);
4488 u32 rps_cpu_mask __read_mostly;
4489 EXPORT_SYMBOL(rps_cpu_mask);
4491 struct static_key_false rps_needed __read_mostly;
4492 EXPORT_SYMBOL(rps_needed);
4493 struct static_key_false rfs_needed __read_mostly;
4494 EXPORT_SYMBOL(rfs_needed);
4496 static struct rps_dev_flow *
4497 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4498 struct rps_dev_flow *rflow, u16 next_cpu)
4500 if (next_cpu < nr_cpu_ids) {
4501 #ifdef CONFIG_RFS_ACCEL
4502 struct netdev_rx_queue *rxqueue;
4503 struct rps_dev_flow_table *flow_table;
4504 struct rps_dev_flow *old_rflow;
4509 /* Should we steer this flow to a different hardware queue? */
4510 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4511 !(dev->features & NETIF_F_NTUPLE))
4513 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4514 if (rxq_index == skb_get_rx_queue(skb))
4517 rxqueue = dev->_rx + rxq_index;
4518 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4521 flow_id = skb_get_hash(skb) & flow_table->mask;
4522 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4523 rxq_index, flow_id);
4527 rflow = &flow_table->flows[flow_id];
4529 if (old_rflow->filter == rflow->filter)
4530 old_rflow->filter = RPS_NO_FILTER;
4534 per_cpu(softnet_data, next_cpu).input_queue_head;
4537 rflow->cpu = next_cpu;
4542 * get_rps_cpu is called from netif_receive_skb and returns the target
4543 * CPU from the RPS map of the receiving queue for a given skb.
4544 * rcu_read_lock must be held on entry.
4546 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4547 struct rps_dev_flow **rflowp)
4549 const struct rps_sock_flow_table *sock_flow_table;
4550 struct netdev_rx_queue *rxqueue = dev->_rx;
4551 struct rps_dev_flow_table *flow_table;
4552 struct rps_map *map;
4557 if (skb_rx_queue_recorded(skb)) {
4558 u16 index = skb_get_rx_queue(skb);
4560 if (unlikely(index >= dev->real_num_rx_queues)) {
4561 WARN_ONCE(dev->real_num_rx_queues > 1,
4562 "%s received packet on queue %u, but number "
4563 "of RX queues is %u\n",
4564 dev->name, index, dev->real_num_rx_queues);
4570 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4572 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4573 map = rcu_dereference(rxqueue->rps_map);
4574 if (!flow_table && !map)
4577 skb_reset_network_header(skb);
4578 hash = skb_get_hash(skb);
4582 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4583 if (flow_table && sock_flow_table) {
4584 struct rps_dev_flow *rflow;
4588 /* First check into global flow table if there is a match.
4589 * This READ_ONCE() pairs with WRITE_ONCE() from rps_record_sock_flow().
4591 ident = READ_ONCE(sock_flow_table->ents[hash & sock_flow_table->mask]);
4592 if ((ident ^ hash) & ~rps_cpu_mask)
4595 next_cpu = ident & rps_cpu_mask;
4597 /* OK, now we know there is a match,
4598 * we can look at the local (per receive queue) flow table
4600 rflow = &flow_table->flows[hash & flow_table->mask];
4604 * If the desired CPU (where last recvmsg was done) is
4605 * different from current CPU (one in the rx-queue flow
4606 * table entry), switch if one of the following holds:
4607 * - Current CPU is unset (>= nr_cpu_ids).
4608 * - Current CPU is offline.
4609 * - The current CPU's queue tail has advanced beyond the
4610 * last packet that was enqueued using this table entry.
4611 * This guarantees that all previous packets for the flow
4612 * have been dequeued, thus preserving in order delivery.
4614 if (unlikely(tcpu != next_cpu) &&
4615 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4616 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4617 rflow->last_qtail)) >= 0)) {
4619 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4622 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4632 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4633 if (cpu_online(tcpu)) {
4643 #ifdef CONFIG_RFS_ACCEL
4646 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4647 * @dev: Device on which the filter was set
4648 * @rxq_index: RX queue index
4649 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4650 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4652 * Drivers that implement ndo_rx_flow_steer() should periodically call
4653 * this function for each installed filter and remove the filters for
4654 * which it returns %true.
4656 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4657 u32 flow_id, u16 filter_id)
4659 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4660 struct rps_dev_flow_table *flow_table;
4661 struct rps_dev_flow *rflow;
4666 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4667 if (flow_table && flow_id <= flow_table->mask) {
4668 rflow = &flow_table->flows[flow_id];
4669 cpu = READ_ONCE(rflow->cpu);
4670 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4671 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4672 rflow->last_qtail) <
4673 (int)(10 * flow_table->mask)))
4679 EXPORT_SYMBOL(rps_may_expire_flow);
4681 #endif /* CONFIG_RFS_ACCEL */
4683 /* Called from hardirq (IPI) context */
4684 static void rps_trigger_softirq(void *data)
4686 struct softnet_data *sd = data;
4688 ____napi_schedule(sd, &sd->backlog);
4692 #endif /* CONFIG_RPS */
4694 /* Called from hardirq (IPI) context */
4695 static void trigger_rx_softirq(void *data)
4697 struct softnet_data *sd = data;
4699 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4700 smp_store_release(&sd->defer_ipi_scheduled, 0);
4704 * After we queued a packet into sd->input_pkt_queue,
4705 * we need to make sure this queue is serviced soon.
4707 * - If this is another cpu queue, link it to our rps_ipi_list,
4708 * and make sure we will process rps_ipi_list from net_rx_action().
4710 * - If this is our own queue, NAPI schedule our backlog.
4711 * Note that this also raises NET_RX_SOFTIRQ.
4713 static void napi_schedule_rps(struct softnet_data *sd)
4715 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4719 sd->rps_ipi_next = mysd->rps_ipi_list;
4720 mysd->rps_ipi_list = sd;
4722 /* If not called from net_rx_action() or napi_threaded_poll()
4723 * we have to raise NET_RX_SOFTIRQ.
4725 if (!mysd->in_net_rx_action && !mysd->in_napi_threaded_poll)
4726 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4729 #endif /* CONFIG_RPS */
4730 __napi_schedule_irqoff(&mysd->backlog);
4733 #ifdef CONFIG_NET_FLOW_LIMIT
4734 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4737 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4739 #ifdef CONFIG_NET_FLOW_LIMIT
4740 struct sd_flow_limit *fl;
4741 struct softnet_data *sd;
4742 unsigned int old_flow, new_flow;
4744 if (qlen < (READ_ONCE(netdev_max_backlog) >> 1))
4747 sd = this_cpu_ptr(&softnet_data);
4750 fl = rcu_dereference(sd->flow_limit);
4752 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4753 old_flow = fl->history[fl->history_head];
4754 fl->history[fl->history_head] = new_flow;
4757 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4759 if (likely(fl->buckets[old_flow]))
4760 fl->buckets[old_flow]--;
4762 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4774 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4775 * queue (may be a remote CPU queue).
4777 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4778 unsigned int *qtail)
4780 enum skb_drop_reason reason;
4781 struct softnet_data *sd;
4782 unsigned long flags;
4785 reason = SKB_DROP_REASON_NOT_SPECIFIED;
4786 sd = &per_cpu(softnet_data, cpu);
4788 rps_lock_irqsave(sd, &flags);
4789 if (!netif_running(skb->dev))
4791 qlen = skb_queue_len(&sd->input_pkt_queue);
4792 if (qlen <= READ_ONCE(netdev_max_backlog) && !skb_flow_limit(skb, qlen)) {
4795 __skb_queue_tail(&sd->input_pkt_queue, skb);
4796 input_queue_tail_incr_save(sd, qtail);
4797 rps_unlock_irq_restore(sd, &flags);
4798 return NET_RX_SUCCESS;
4801 /* Schedule NAPI for backlog device
4802 * We can use non atomic operation since we own the queue lock
4804 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state))
4805 napi_schedule_rps(sd);
4808 reason = SKB_DROP_REASON_CPU_BACKLOG;
4812 rps_unlock_irq_restore(sd, &flags);
4814 dev_core_stats_rx_dropped_inc(skb->dev);
4815 kfree_skb_reason(skb, reason);
4819 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4821 struct net_device *dev = skb->dev;
4822 struct netdev_rx_queue *rxqueue;
4826 if (skb_rx_queue_recorded(skb)) {
4827 u16 index = skb_get_rx_queue(skb);
4829 if (unlikely(index >= dev->real_num_rx_queues)) {
4830 WARN_ONCE(dev->real_num_rx_queues > 1,
4831 "%s received packet on queue %u, but number "
4832 "of RX queues is %u\n",
4833 dev->name, index, dev->real_num_rx_queues);
4835 return rxqueue; /* Return first rxqueue */
4842 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp,
4843 struct bpf_prog *xdp_prog)
4845 void *orig_data, *orig_data_end, *hard_start;
4846 struct netdev_rx_queue *rxqueue;
4847 bool orig_bcast, orig_host;
4848 u32 mac_len, frame_sz;
4849 __be16 orig_eth_type;
4854 /* The XDP program wants to see the packet starting at the MAC
4857 mac_len = skb->data - skb_mac_header(skb);
4858 hard_start = skb->data - skb_headroom(skb);
4860 /* SKB "head" area always have tailroom for skb_shared_info */
4861 frame_sz = (void *)skb_end_pointer(skb) - hard_start;
4862 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4864 rxqueue = netif_get_rxqueue(skb);
4865 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq);
4866 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len,
4867 skb_headlen(skb) + mac_len, true);
4869 orig_data_end = xdp->data_end;
4870 orig_data = xdp->data;
4871 eth = (struct ethhdr *)xdp->data;
4872 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr);
4873 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4874 orig_eth_type = eth->h_proto;
4876 act = bpf_prog_run_xdp(xdp_prog, xdp);
4878 /* check if bpf_xdp_adjust_head was used */
4879 off = xdp->data - orig_data;
4882 __skb_pull(skb, off);
4884 __skb_push(skb, -off);
4886 skb->mac_header += off;
4887 skb_reset_network_header(skb);
4890 /* check if bpf_xdp_adjust_tail was used */
4891 off = xdp->data_end - orig_data_end;
4893 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4894 skb->len += off; /* positive on grow, negative on shrink */
4897 /* check if XDP changed eth hdr such SKB needs update */
4898 eth = (struct ethhdr *)xdp->data;
4899 if ((orig_eth_type != eth->h_proto) ||
4900 (orig_host != ether_addr_equal_64bits(eth->h_dest,
4901 skb->dev->dev_addr)) ||
4902 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4903 __skb_push(skb, ETH_HLEN);
4904 skb->pkt_type = PACKET_HOST;
4905 skb->protocol = eth_type_trans(skb, skb->dev);
4908 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull
4909 * before calling us again on redirect path. We do not call do_redirect
4910 * as we leave that up to the caller.
4912 * Caller is responsible for managing lifetime of skb (i.e. calling
4913 * kfree_skb in response to actions it cannot handle/XDP_DROP).
4918 __skb_push(skb, mac_len);
4921 metalen = xdp->data - xdp->data_meta;
4923 skb_metadata_set(skb, metalen);
4930 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4931 struct xdp_buff *xdp,
4932 struct bpf_prog *xdp_prog)
4936 /* Reinjected packets coming from act_mirred or similar should
4937 * not get XDP generic processing.
4939 if (skb_is_redirected(skb))
4942 /* XDP packets must be linear and must have sufficient headroom
4943 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4944 * native XDP provides, thus we need to do it here as well.
4946 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4947 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4948 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4949 int troom = skb->tail + skb->data_len - skb->end;
4951 /* In case we have to go down the path and also linearize,
4952 * then lets do the pskb_expand_head() work just once here.
4954 if (pskb_expand_head(skb,
4955 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4956 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4958 if (skb_linearize(skb))
4962 act = bpf_prog_run_generic_xdp(skb, xdp, xdp_prog);
4969 bpf_warn_invalid_xdp_action(skb->dev, xdp_prog, act);
4972 trace_xdp_exception(skb->dev, xdp_prog, act);
4983 /* When doing generic XDP we have to bypass the qdisc layer and the
4984 * network taps in order to match in-driver-XDP behavior. This also means
4985 * that XDP packets are able to starve other packets going through a qdisc,
4986 * and DDOS attacks will be more effective. In-driver-XDP use dedicated TX
4987 * queues, so they do not have this starvation issue.
4989 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4991 struct net_device *dev = skb->dev;
4992 struct netdev_queue *txq;
4993 bool free_skb = true;
4996 txq = netdev_core_pick_tx(dev, skb, NULL);
4997 cpu = smp_processor_id();
4998 HARD_TX_LOCK(dev, txq, cpu);
4999 if (!netif_xmit_frozen_or_drv_stopped(txq)) {
5000 rc = netdev_start_xmit(skb, dev, txq, 0);
5001 if (dev_xmit_complete(rc))
5004 HARD_TX_UNLOCK(dev, txq);
5006 trace_xdp_exception(dev, xdp_prog, XDP_TX);
5007 dev_core_stats_tx_dropped_inc(dev);
5012 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
5014 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
5017 struct xdp_buff xdp;
5021 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
5022 if (act != XDP_PASS) {
5025 err = xdp_do_generic_redirect(skb->dev, skb,
5031 generic_xdp_tx(skb, xdp_prog);
5039 kfree_skb_reason(skb, SKB_DROP_REASON_XDP);
5042 EXPORT_SYMBOL_GPL(do_xdp_generic);
5044 static int netif_rx_internal(struct sk_buff *skb)
5048 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5050 trace_netif_rx(skb);
5053 if (static_branch_unlikely(&rps_needed)) {
5054 struct rps_dev_flow voidflow, *rflow = &voidflow;
5059 cpu = get_rps_cpu(skb->dev, skb, &rflow);
5061 cpu = smp_processor_id();
5063 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5071 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail);
5077 * __netif_rx - Slightly optimized version of netif_rx
5078 * @skb: buffer to post
5080 * This behaves as netif_rx except that it does not disable bottom halves.
5081 * As a result this function may only be invoked from the interrupt context
5082 * (either hard or soft interrupt).
5084 int __netif_rx(struct sk_buff *skb)
5088 lockdep_assert_once(hardirq_count() | softirq_count());
5090 trace_netif_rx_entry(skb);
5091 ret = netif_rx_internal(skb);
5092 trace_netif_rx_exit(ret);
5095 EXPORT_SYMBOL(__netif_rx);
5098 * netif_rx - post buffer to the network code
5099 * @skb: buffer to post
5101 * This function receives a packet from a device driver and queues it for
5102 * the upper (protocol) levels to process via the backlog NAPI device. It
5103 * always succeeds. The buffer may be dropped during processing for
5104 * congestion control or by the protocol layers.
5105 * The network buffer is passed via the backlog NAPI device. Modern NIC
5106 * driver should use NAPI and GRO.
5107 * This function can used from interrupt and from process context. The
5108 * caller from process context must not disable interrupts before invoking
5112 * NET_RX_SUCCESS (no congestion)
5113 * NET_RX_DROP (packet was dropped)
5116 int netif_rx(struct sk_buff *skb)
5118 bool need_bh_off = !(hardirq_count() | softirq_count());
5123 trace_netif_rx_entry(skb);
5124 ret = netif_rx_internal(skb);
5125 trace_netif_rx_exit(ret);
5130 EXPORT_SYMBOL(netif_rx);
5132 static __latent_entropy void net_tx_action(struct softirq_action *h)
5134 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
5136 if (sd->completion_queue) {
5137 struct sk_buff *clist;
5139 local_irq_disable();
5140 clist = sd->completion_queue;
5141 sd->completion_queue = NULL;
5145 struct sk_buff *skb = clist;
5147 clist = clist->next;
5149 WARN_ON(refcount_read(&skb->users));
5150 if (likely(get_kfree_skb_cb(skb)->reason == SKB_CONSUMED))
5151 trace_consume_skb(skb, net_tx_action);
5153 trace_kfree_skb(skb, net_tx_action,
5154 get_kfree_skb_cb(skb)->reason);
5156 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
5159 __napi_kfree_skb(skb,
5160 get_kfree_skb_cb(skb)->reason);
5164 if (sd->output_queue) {
5167 local_irq_disable();
5168 head = sd->output_queue;
5169 sd->output_queue = NULL;
5170 sd->output_queue_tailp = &sd->output_queue;
5176 struct Qdisc *q = head;
5177 spinlock_t *root_lock = NULL;
5179 head = head->next_sched;
5181 /* We need to make sure head->next_sched is read
5182 * before clearing __QDISC_STATE_SCHED
5184 smp_mb__before_atomic();
5186 if (!(q->flags & TCQ_F_NOLOCK)) {
5187 root_lock = qdisc_lock(q);
5188 spin_lock(root_lock);
5189 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
5191 /* There is a synchronize_net() between
5192 * STATE_DEACTIVATED flag being set and
5193 * qdisc_reset()/some_qdisc_is_busy() in
5194 * dev_deactivate(), so we can safely bail out
5195 * early here to avoid data race between
5196 * qdisc_deactivate() and some_qdisc_is_busy()
5197 * for lockless qdisc.
5199 clear_bit(__QDISC_STATE_SCHED, &q->state);
5203 clear_bit(__QDISC_STATE_SCHED, &q->state);
5206 spin_unlock(root_lock);
5212 xfrm_dev_backlog(sd);
5215 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
5216 /* This hook is defined here for ATM LANE */
5217 int (*br_fdb_test_addr_hook)(struct net_device *dev,
5218 unsigned char *addr) __read_mostly;
5219 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
5223 * netdev_is_rx_handler_busy - check if receive handler is registered
5224 * @dev: device to check
5226 * Check if a receive handler is already registered for a given device.
5227 * Return true if there one.
5229 * The caller must hold the rtnl_mutex.
5231 bool netdev_is_rx_handler_busy(struct net_device *dev)
5234 return dev && rtnl_dereference(dev->rx_handler);
5236 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5239 * netdev_rx_handler_register - register receive handler
5240 * @dev: device to register a handler for
5241 * @rx_handler: receive handler to register
5242 * @rx_handler_data: data pointer that is used by rx handler
5244 * Register a receive handler for a device. This handler will then be
5245 * called from __netif_receive_skb. A negative errno code is returned
5248 * The caller must hold the rtnl_mutex.
5250 * For a general description of rx_handler, see enum rx_handler_result.
5252 int netdev_rx_handler_register(struct net_device *dev,
5253 rx_handler_func_t *rx_handler,
5254 void *rx_handler_data)
5256 if (netdev_is_rx_handler_busy(dev))
5259 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5262 /* Note: rx_handler_data must be set before rx_handler */
5263 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5264 rcu_assign_pointer(dev->rx_handler, rx_handler);
5268 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5271 * netdev_rx_handler_unregister - unregister receive handler
5272 * @dev: device to unregister a handler from
5274 * Unregister a receive handler from a device.
5276 * The caller must hold the rtnl_mutex.
5278 void netdev_rx_handler_unregister(struct net_device *dev)
5282 RCU_INIT_POINTER(dev->rx_handler, NULL);
5283 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5284 * section has a guarantee to see a non NULL rx_handler_data
5288 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5290 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5293 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5294 * the special handling of PFMEMALLOC skbs.
5296 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5298 switch (skb->protocol) {
5299 case htons(ETH_P_ARP):
5300 case htons(ETH_P_IP):
5301 case htons(ETH_P_IPV6):
5302 case htons(ETH_P_8021Q):
5303 case htons(ETH_P_8021AD):
5310 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5311 int *ret, struct net_device *orig_dev)
5313 if (nf_hook_ingress_active(skb)) {
5317 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5322 ingress_retval = nf_hook_ingress(skb);
5324 return ingress_retval;
5329 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5330 struct packet_type **ppt_prev)
5332 struct packet_type *ptype, *pt_prev;
5333 rx_handler_func_t *rx_handler;
5334 struct sk_buff *skb = *pskb;
5335 struct net_device *orig_dev;
5336 bool deliver_exact = false;
5337 int ret = NET_RX_DROP;
5340 net_timestamp_check(!READ_ONCE(netdev_tstamp_prequeue), skb);
5342 trace_netif_receive_skb(skb);
5344 orig_dev = skb->dev;
5346 skb_reset_network_header(skb);
5347 if (!skb_transport_header_was_set(skb))
5348 skb_reset_transport_header(skb);
5349 skb_reset_mac_len(skb);
5354 skb->skb_iif = skb->dev->ifindex;
5356 __this_cpu_inc(softnet_data.processed);
5358 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5362 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5365 if (ret2 != XDP_PASS) {
5371 if (eth_type_vlan(skb->protocol)) {
5372 skb = skb_vlan_untag(skb);
5377 if (skb_skip_tc_classify(skb))
5383 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5385 ret = deliver_skb(skb, pt_prev, orig_dev);
5389 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5391 ret = deliver_skb(skb, pt_prev, orig_dev);
5396 #ifdef CONFIG_NET_INGRESS
5397 if (static_branch_unlikely(&ingress_needed_key)) {
5398 bool another = false;
5400 nf_skip_egress(skb, true);
5401 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5408 nf_skip_egress(skb, false);
5409 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5413 skb_reset_redirect(skb);
5415 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5418 if (skb_vlan_tag_present(skb)) {
5420 ret = deliver_skb(skb, pt_prev, orig_dev);
5423 if (vlan_do_receive(&skb))
5425 else if (unlikely(!skb))
5429 rx_handler = rcu_dereference(skb->dev->rx_handler);
5432 ret = deliver_skb(skb, pt_prev, orig_dev);
5435 switch (rx_handler(&skb)) {
5436 case RX_HANDLER_CONSUMED:
5437 ret = NET_RX_SUCCESS;
5439 case RX_HANDLER_ANOTHER:
5441 case RX_HANDLER_EXACT:
5442 deliver_exact = true;
5444 case RX_HANDLER_PASS:
5451 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5453 if (skb_vlan_tag_get_id(skb)) {
5454 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5457 skb->pkt_type = PACKET_OTHERHOST;
5458 } else if (eth_type_vlan(skb->protocol)) {
5459 /* Outer header is 802.1P with vlan 0, inner header is
5460 * 802.1Q or 802.1AD and vlan_do_receive() above could
5461 * not find vlan dev for vlan id 0.
5463 __vlan_hwaccel_clear_tag(skb);
5464 skb = skb_vlan_untag(skb);
5467 if (vlan_do_receive(&skb))
5468 /* After stripping off 802.1P header with vlan 0
5469 * vlan dev is found for inner header.
5472 else if (unlikely(!skb))
5475 /* We have stripped outer 802.1P vlan 0 header.
5476 * But could not find vlan dev.
5477 * check again for vlan id to set OTHERHOST.
5481 /* Note: we might in the future use prio bits
5482 * and set skb->priority like in vlan_do_receive()
5483 * For the time being, just ignore Priority Code Point
5485 __vlan_hwaccel_clear_tag(skb);
5488 type = skb->protocol;
5490 /* deliver only exact match when indicated */
5491 if (likely(!deliver_exact)) {
5492 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5493 &ptype_base[ntohs(type) &
5497 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5498 &orig_dev->ptype_specific);
5500 if (unlikely(skb->dev != orig_dev)) {
5501 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5502 &skb->dev->ptype_specific);
5506 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5508 *ppt_prev = pt_prev;
5512 dev_core_stats_rx_dropped_inc(skb->dev);
5514 dev_core_stats_rx_nohandler_inc(skb->dev);
5515 kfree_skb_reason(skb, SKB_DROP_REASON_UNHANDLED_PROTO);
5516 /* Jamal, now you will not able to escape explaining
5517 * me how you were going to use this. :-)
5523 /* The invariant here is that if *ppt_prev is not NULL
5524 * then skb should also be non-NULL.
5526 * Apparently *ppt_prev assignment above holds this invariant due to
5527 * skb dereferencing near it.
5533 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5535 struct net_device *orig_dev = skb->dev;
5536 struct packet_type *pt_prev = NULL;
5539 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5541 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5542 skb->dev, pt_prev, orig_dev);
5547 * netif_receive_skb_core - special purpose version of netif_receive_skb
5548 * @skb: buffer to process
5550 * More direct receive version of netif_receive_skb(). It should
5551 * only be used by callers that have a need to skip RPS and Generic XDP.
5552 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5554 * This function may only be called from softirq context and interrupts
5555 * should be enabled.
5557 * Return values (usually ignored):
5558 * NET_RX_SUCCESS: no congestion
5559 * NET_RX_DROP: packet was dropped
5561 int netif_receive_skb_core(struct sk_buff *skb)
5566 ret = __netif_receive_skb_one_core(skb, false);
5571 EXPORT_SYMBOL(netif_receive_skb_core);
5573 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5574 struct packet_type *pt_prev,
5575 struct net_device *orig_dev)
5577 struct sk_buff *skb, *next;
5581 if (list_empty(head))
5583 if (pt_prev->list_func != NULL)
5584 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5585 ip_list_rcv, head, pt_prev, orig_dev);
5587 list_for_each_entry_safe(skb, next, head, list) {
5588 skb_list_del_init(skb);
5589 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5593 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5595 /* Fast-path assumptions:
5596 * - There is no RX handler.
5597 * - Only one packet_type matches.
5598 * If either of these fails, we will end up doing some per-packet
5599 * processing in-line, then handling the 'last ptype' for the whole
5600 * sublist. This can't cause out-of-order delivery to any single ptype,
5601 * because the 'last ptype' must be constant across the sublist, and all
5602 * other ptypes are handled per-packet.
5604 /* Current (common) ptype of sublist */
5605 struct packet_type *pt_curr = NULL;
5606 /* Current (common) orig_dev of sublist */
5607 struct net_device *od_curr = NULL;
5608 struct list_head sublist;
5609 struct sk_buff *skb, *next;
5611 INIT_LIST_HEAD(&sublist);
5612 list_for_each_entry_safe(skb, next, head, list) {
5613 struct net_device *orig_dev = skb->dev;
5614 struct packet_type *pt_prev = NULL;
5616 skb_list_del_init(skb);
5617 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5620 if (pt_curr != pt_prev || od_curr != orig_dev) {
5621 /* dispatch old sublist */
5622 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5623 /* start new sublist */
5624 INIT_LIST_HEAD(&sublist);
5628 list_add_tail(&skb->list, &sublist);
5631 /* dispatch final sublist */
5632 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5635 static int __netif_receive_skb(struct sk_buff *skb)
5639 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5640 unsigned int noreclaim_flag;
5643 * PFMEMALLOC skbs are special, they should
5644 * - be delivered to SOCK_MEMALLOC sockets only
5645 * - stay away from userspace
5646 * - have bounded memory usage
5648 * Use PF_MEMALLOC as this saves us from propagating the allocation
5649 * context down to all allocation sites.
5651 noreclaim_flag = memalloc_noreclaim_save();
5652 ret = __netif_receive_skb_one_core(skb, true);
5653 memalloc_noreclaim_restore(noreclaim_flag);
5655 ret = __netif_receive_skb_one_core(skb, false);
5660 static void __netif_receive_skb_list(struct list_head *head)
5662 unsigned long noreclaim_flag = 0;
5663 struct sk_buff *skb, *next;
5664 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5666 list_for_each_entry_safe(skb, next, head, list) {
5667 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5668 struct list_head sublist;
5670 /* Handle the previous sublist */
5671 list_cut_before(&sublist, head, &skb->list);
5672 if (!list_empty(&sublist))
5673 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5674 pfmemalloc = !pfmemalloc;
5675 /* See comments in __netif_receive_skb */
5677 noreclaim_flag = memalloc_noreclaim_save();
5679 memalloc_noreclaim_restore(noreclaim_flag);
5682 /* Handle the remaining sublist */
5683 if (!list_empty(head))
5684 __netif_receive_skb_list_core(head, pfmemalloc);
5685 /* Restore pflags */
5687 memalloc_noreclaim_restore(noreclaim_flag);
5690 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5692 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5693 struct bpf_prog *new = xdp->prog;
5696 switch (xdp->command) {
5697 case XDP_SETUP_PROG:
5698 rcu_assign_pointer(dev->xdp_prog, new);
5703 static_branch_dec(&generic_xdp_needed_key);
5704 } else if (new && !old) {
5705 static_branch_inc(&generic_xdp_needed_key);
5706 dev_disable_lro(dev);
5707 dev_disable_gro_hw(dev);
5719 static int netif_receive_skb_internal(struct sk_buff *skb)
5723 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5725 if (skb_defer_rx_timestamp(skb))
5726 return NET_RX_SUCCESS;
5730 if (static_branch_unlikely(&rps_needed)) {
5731 struct rps_dev_flow voidflow, *rflow = &voidflow;
5732 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5735 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5741 ret = __netif_receive_skb(skb);
5746 void netif_receive_skb_list_internal(struct list_head *head)
5748 struct sk_buff *skb, *next;
5749 struct list_head sublist;
5751 INIT_LIST_HEAD(&sublist);
5752 list_for_each_entry_safe(skb, next, head, list) {
5753 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5754 skb_list_del_init(skb);
5755 if (!skb_defer_rx_timestamp(skb))
5756 list_add_tail(&skb->list, &sublist);
5758 list_splice_init(&sublist, head);
5762 if (static_branch_unlikely(&rps_needed)) {
5763 list_for_each_entry_safe(skb, next, head, list) {
5764 struct rps_dev_flow voidflow, *rflow = &voidflow;
5765 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5768 /* Will be handled, remove from list */
5769 skb_list_del_init(skb);
5770 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5775 __netif_receive_skb_list(head);
5780 * netif_receive_skb - process receive buffer from network
5781 * @skb: buffer to process
5783 * netif_receive_skb() is the main receive data processing function.
5784 * It always succeeds. The buffer may be dropped during processing
5785 * for congestion control or by the protocol layers.
5787 * This function may only be called from softirq context and interrupts
5788 * should be enabled.
5790 * Return values (usually ignored):
5791 * NET_RX_SUCCESS: no congestion
5792 * NET_RX_DROP: packet was dropped
5794 int netif_receive_skb(struct sk_buff *skb)
5798 trace_netif_receive_skb_entry(skb);
5800 ret = netif_receive_skb_internal(skb);
5801 trace_netif_receive_skb_exit(ret);
5805 EXPORT_SYMBOL(netif_receive_skb);
5808 * netif_receive_skb_list - process many receive buffers from network
5809 * @head: list of skbs to process.
5811 * Since return value of netif_receive_skb() is normally ignored, and
5812 * wouldn't be meaningful for a list, this function returns void.
5814 * This function may only be called from softirq context and interrupts
5815 * should be enabled.
5817 void netif_receive_skb_list(struct list_head *head)
5819 struct sk_buff *skb;
5821 if (list_empty(head))
5823 if (trace_netif_receive_skb_list_entry_enabled()) {
5824 list_for_each_entry(skb, head, list)
5825 trace_netif_receive_skb_list_entry(skb);
5827 netif_receive_skb_list_internal(head);
5828 trace_netif_receive_skb_list_exit(0);
5830 EXPORT_SYMBOL(netif_receive_skb_list);
5832 static DEFINE_PER_CPU(struct work_struct, flush_works);
5834 /* Network device is going away, flush any packets still pending */
5835 static void flush_backlog(struct work_struct *work)
5837 struct sk_buff *skb, *tmp;
5838 struct softnet_data *sd;
5841 sd = this_cpu_ptr(&softnet_data);
5843 rps_lock_irq_disable(sd);
5844 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5845 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5846 __skb_unlink(skb, &sd->input_pkt_queue);
5847 dev_kfree_skb_irq(skb);
5848 input_queue_head_incr(sd);
5851 rps_unlock_irq_enable(sd);
5853 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5854 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5855 __skb_unlink(skb, &sd->process_queue);
5857 input_queue_head_incr(sd);
5863 static bool flush_required(int cpu)
5865 #if IS_ENABLED(CONFIG_RPS)
5866 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5869 rps_lock_irq_disable(sd);
5871 /* as insertion into process_queue happens with the rps lock held,
5872 * process_queue access may race only with dequeue
5874 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5875 !skb_queue_empty_lockless(&sd->process_queue);
5876 rps_unlock_irq_enable(sd);
5880 /* without RPS we can't safely check input_pkt_queue: during a
5881 * concurrent remote skb_queue_splice() we can detect as empty both
5882 * input_pkt_queue and process_queue even if the latter could end-up
5883 * containing a lot of packets.
5888 static void flush_all_backlogs(void)
5890 static cpumask_t flush_cpus;
5893 /* since we are under rtnl lock protection we can use static data
5894 * for the cpumask and avoid allocating on stack the possibly
5901 cpumask_clear(&flush_cpus);
5902 for_each_online_cpu(cpu) {
5903 if (flush_required(cpu)) {
5904 queue_work_on(cpu, system_highpri_wq,
5905 per_cpu_ptr(&flush_works, cpu));
5906 cpumask_set_cpu(cpu, &flush_cpus);
5910 /* we can have in flight packet[s] on the cpus we are not flushing,
5911 * synchronize_net() in unregister_netdevice_many() will take care of
5914 for_each_cpu(cpu, &flush_cpus)
5915 flush_work(per_cpu_ptr(&flush_works, cpu));
5920 static void net_rps_send_ipi(struct softnet_data *remsd)
5924 struct softnet_data *next = remsd->rps_ipi_next;
5926 if (cpu_online(remsd->cpu))
5927 smp_call_function_single_async(remsd->cpu, &remsd->csd);
5934 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
5935 * Note: called with local irq disabled, but exits with local irq enabled.
5937 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
5940 struct softnet_data *remsd = sd->rps_ipi_list;
5943 sd->rps_ipi_list = NULL;
5947 /* Send pending IPI's to kick RPS processing on remote cpus. */
5948 net_rps_send_ipi(remsd);
5954 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
5957 return sd->rps_ipi_list != NULL;
5963 static int process_backlog(struct napi_struct *napi, int quota)
5965 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
5969 /* Check if we have pending ipi, its better to send them now,
5970 * not waiting net_rx_action() end.
5972 if (sd_has_rps_ipi_waiting(sd)) {
5973 local_irq_disable();
5974 net_rps_action_and_irq_enable(sd);
5977 napi->weight = READ_ONCE(dev_rx_weight);
5979 struct sk_buff *skb;
5981 while ((skb = __skb_dequeue(&sd->process_queue))) {
5983 __netif_receive_skb(skb);
5985 input_queue_head_incr(sd);
5986 if (++work >= quota)
5991 rps_lock_irq_disable(sd);
5992 if (skb_queue_empty(&sd->input_pkt_queue)) {
5994 * Inline a custom version of __napi_complete().
5995 * only current cpu owns and manipulates this napi,
5996 * and NAPI_STATE_SCHED is the only possible flag set
5998 * We can use a plain write instead of clear_bit(),
5999 * and we dont need an smp_mb() memory barrier.
6004 skb_queue_splice_tail_init(&sd->input_pkt_queue,
6005 &sd->process_queue);
6007 rps_unlock_irq_enable(sd);
6014 * __napi_schedule - schedule for receive
6015 * @n: entry to schedule
6017 * The entry's receive function will be scheduled to run.
6018 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6020 void __napi_schedule(struct napi_struct *n)
6022 unsigned long flags;
6024 local_irq_save(flags);
6025 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6026 local_irq_restore(flags);
6028 EXPORT_SYMBOL(__napi_schedule);
6031 * napi_schedule_prep - check if napi can be scheduled
6034 * Test if NAPI routine is already running, and if not mark
6035 * it as running. This is used as a condition variable to
6036 * insure only one NAPI poll instance runs. We also make
6037 * sure there is no pending NAPI disable.
6039 bool napi_schedule_prep(struct napi_struct *n)
6041 unsigned long new, val = READ_ONCE(n->state);
6044 if (unlikely(val & NAPIF_STATE_DISABLE))
6046 new = val | NAPIF_STATE_SCHED;
6048 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6049 * This was suggested by Alexander Duyck, as compiler
6050 * emits better code than :
6051 * if (val & NAPIF_STATE_SCHED)
6052 * new |= NAPIF_STATE_MISSED;
6054 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6056 } while (!try_cmpxchg(&n->state, &val, new));
6058 return !(val & NAPIF_STATE_SCHED);
6060 EXPORT_SYMBOL(napi_schedule_prep);
6063 * __napi_schedule_irqoff - schedule for receive
6064 * @n: entry to schedule
6066 * Variant of __napi_schedule() assuming hard irqs are masked.
6068 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
6069 * because the interrupt disabled assumption might not be true
6070 * due to force-threaded interrupts and spinlock substitution.
6072 void __napi_schedule_irqoff(struct napi_struct *n)
6074 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6075 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6079 EXPORT_SYMBOL(__napi_schedule_irqoff);
6081 bool napi_complete_done(struct napi_struct *n, int work_done)
6083 unsigned long flags, val, new, timeout = 0;
6087 * 1) Don't let napi dequeue from the cpu poll list
6088 * just in case its running on a different cpu.
6089 * 2) If we are busy polling, do nothing here, we have
6090 * the guarantee we will be called later.
6092 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6093 NAPIF_STATE_IN_BUSY_POLL)))
6098 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6099 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
6101 if (n->defer_hard_irqs_count > 0) {
6102 n->defer_hard_irqs_count--;
6103 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6107 if (n->gro_bitmask) {
6108 /* When the NAPI instance uses a timeout and keeps postponing
6109 * it, we need to bound somehow the time packets are kept in
6112 napi_gro_flush(n, !!timeout);
6117 if (unlikely(!list_empty(&n->poll_list))) {
6118 /* If n->poll_list is not empty, we need to mask irqs */
6119 local_irq_save(flags);
6120 list_del_init(&n->poll_list);
6121 local_irq_restore(flags);
6123 WRITE_ONCE(n->list_owner, -1);
6125 val = READ_ONCE(n->state);
6127 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6129 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
6130 NAPIF_STATE_SCHED_THREADED |
6131 NAPIF_STATE_PREFER_BUSY_POLL);
6133 /* If STATE_MISSED was set, leave STATE_SCHED set,
6134 * because we will call napi->poll() one more time.
6135 * This C code was suggested by Alexander Duyck to help gcc.
6137 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6139 } while (!try_cmpxchg(&n->state, &val, new));
6141 if (unlikely(val & NAPIF_STATE_MISSED)) {
6147 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6148 HRTIMER_MODE_REL_PINNED);
6151 EXPORT_SYMBOL(napi_complete_done);
6153 /* must be called under rcu_read_lock(), as we dont take a reference */
6154 static struct napi_struct *napi_by_id(unsigned int napi_id)
6156 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6157 struct napi_struct *napi;
6159 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6160 if (napi->napi_id == napi_id)
6166 #if defined(CONFIG_NET_RX_BUSY_POLL)
6168 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
6170 if (!skip_schedule) {
6171 gro_normal_list(napi);
6172 __napi_schedule(napi);
6176 if (napi->gro_bitmask) {
6177 /* flush too old packets
6178 * If HZ < 1000, flush all packets.
6180 napi_gro_flush(napi, HZ >= 1000);
6183 gro_normal_list(napi);
6184 clear_bit(NAPI_STATE_SCHED, &napi->state);
6187 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, bool prefer_busy_poll,
6190 bool skip_schedule = false;
6191 unsigned long timeout;
6194 /* Busy polling means there is a high chance device driver hard irq
6195 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6196 * set in napi_schedule_prep().
6197 * Since we are about to call napi->poll() once more, we can safely
6198 * clear NAPI_STATE_MISSED.
6200 * Note: x86 could use a single "lock and ..." instruction
6201 * to perform these two clear_bit()
6203 clear_bit(NAPI_STATE_MISSED, &napi->state);
6204 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6208 if (prefer_busy_poll) {
6209 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
6210 timeout = READ_ONCE(napi->dev->gro_flush_timeout);
6211 if (napi->defer_hard_irqs_count && timeout) {
6212 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
6213 skip_schedule = true;
6217 /* All we really want here is to re-enable device interrupts.
6218 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6220 rc = napi->poll(napi, budget);
6221 /* We can't gro_normal_list() here, because napi->poll() might have
6222 * rearmed the napi (napi_complete_done()) in which case it could
6223 * already be running on another CPU.
6225 trace_napi_poll(napi, rc, budget);
6226 netpoll_poll_unlock(have_poll_lock);
6228 __busy_poll_stop(napi, skip_schedule);
6232 void napi_busy_loop(unsigned int napi_id,
6233 bool (*loop_end)(void *, unsigned long),
6234 void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6236 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6237 int (*napi_poll)(struct napi_struct *napi, int budget);
6238 void *have_poll_lock = NULL;
6239 struct napi_struct *napi;
6246 napi = napi_by_id(napi_id);
6250 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6257 unsigned long val = READ_ONCE(napi->state);
6259 /* If multiple threads are competing for this napi,
6260 * we avoid dirtying napi->state as much as we can.
6262 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6263 NAPIF_STATE_IN_BUSY_POLL)) {
6264 if (prefer_busy_poll)
6265 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6268 if (cmpxchg(&napi->state, val,
6269 val | NAPIF_STATE_IN_BUSY_POLL |
6270 NAPIF_STATE_SCHED) != val) {
6271 if (prefer_busy_poll)
6272 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6275 have_poll_lock = netpoll_poll_lock(napi);
6276 napi_poll = napi->poll;
6278 work = napi_poll(napi, budget);
6279 trace_napi_poll(napi, work, budget);
6280 gro_normal_list(napi);
6283 __NET_ADD_STATS(dev_net(napi->dev),
6284 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6287 if (!loop_end || loop_end(loop_end_arg, start_time))
6290 if (unlikely(need_resched())) {
6292 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6293 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6297 if (loop_end(loop_end_arg, start_time))
6304 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6305 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6310 EXPORT_SYMBOL(napi_busy_loop);
6312 #endif /* CONFIG_NET_RX_BUSY_POLL */
6314 static void napi_hash_add(struct napi_struct *napi)
6316 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6319 spin_lock(&napi_hash_lock);
6321 /* 0..NR_CPUS range is reserved for sender_cpu use */
6323 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6324 napi_gen_id = MIN_NAPI_ID;
6325 } while (napi_by_id(napi_gen_id));
6326 napi->napi_id = napi_gen_id;
6328 hlist_add_head_rcu(&napi->napi_hash_node,
6329 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6331 spin_unlock(&napi_hash_lock);
6334 /* Warning : caller is responsible to make sure rcu grace period
6335 * is respected before freeing memory containing @napi
6337 static void napi_hash_del(struct napi_struct *napi)
6339 spin_lock(&napi_hash_lock);
6341 hlist_del_init_rcu(&napi->napi_hash_node);
6343 spin_unlock(&napi_hash_lock);
6346 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6348 struct napi_struct *napi;
6350 napi = container_of(timer, struct napi_struct, timer);
6352 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6353 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6355 if (!napi_disable_pending(napi) &&
6356 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
6357 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6358 __napi_schedule_irqoff(napi);
6361 return HRTIMER_NORESTART;
6364 static void init_gro_hash(struct napi_struct *napi)
6368 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6369 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6370 napi->gro_hash[i].count = 0;
6372 napi->gro_bitmask = 0;
6375 int dev_set_threaded(struct net_device *dev, bool threaded)
6377 struct napi_struct *napi;
6380 if (dev->threaded == threaded)
6384 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6385 if (!napi->thread) {
6386 err = napi_kthread_create(napi);
6395 dev->threaded = threaded;
6397 /* Make sure kthread is created before THREADED bit
6400 smp_mb__before_atomic();
6402 /* Setting/unsetting threaded mode on a napi might not immediately
6403 * take effect, if the current napi instance is actively being
6404 * polled. In this case, the switch between threaded mode and
6405 * softirq mode will happen in the next round of napi_schedule().
6406 * This should not cause hiccups/stalls to the live traffic.
6408 list_for_each_entry(napi, &dev->napi_list, dev_list)
6409 assign_bit(NAPI_STATE_THREADED, &napi->state, threaded);
6413 EXPORT_SYMBOL(dev_set_threaded);
6415 void netif_napi_add_weight(struct net_device *dev, struct napi_struct *napi,
6416 int (*poll)(struct napi_struct *, int), int weight)
6418 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6421 INIT_LIST_HEAD(&napi->poll_list);
6422 INIT_HLIST_NODE(&napi->napi_hash_node);
6423 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6424 napi->timer.function = napi_watchdog;
6425 init_gro_hash(napi);
6427 INIT_LIST_HEAD(&napi->rx_list);
6430 if (weight > NAPI_POLL_WEIGHT)
6431 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6433 napi->weight = weight;
6435 #ifdef CONFIG_NETPOLL
6436 napi->poll_owner = -1;
6438 napi->list_owner = -1;
6439 set_bit(NAPI_STATE_SCHED, &napi->state);
6440 set_bit(NAPI_STATE_NPSVC, &napi->state);
6441 list_add_rcu(&napi->dev_list, &dev->napi_list);
6442 napi_hash_add(napi);
6443 napi_get_frags_check(napi);
6444 /* Create kthread for this napi if dev->threaded is set.
6445 * Clear dev->threaded if kthread creation failed so that
6446 * threaded mode will not be enabled in napi_enable().
6448 if (dev->threaded && napi_kthread_create(napi))
6451 EXPORT_SYMBOL(netif_napi_add_weight);
6453 void napi_disable(struct napi_struct *n)
6455 unsigned long val, new;
6458 set_bit(NAPI_STATE_DISABLE, &n->state);
6460 val = READ_ONCE(n->state);
6462 while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
6463 usleep_range(20, 200);
6464 val = READ_ONCE(n->state);
6467 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
6468 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
6469 } while (!try_cmpxchg(&n->state, &val, new));
6471 hrtimer_cancel(&n->timer);
6473 clear_bit(NAPI_STATE_DISABLE, &n->state);
6475 EXPORT_SYMBOL(napi_disable);
6478 * napi_enable - enable NAPI scheduling
6481 * Resume NAPI from being scheduled on this context.
6482 * Must be paired with napi_disable.
6484 void napi_enable(struct napi_struct *n)
6486 unsigned long new, val = READ_ONCE(n->state);
6489 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
6491 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
6492 if (n->dev->threaded && n->thread)
6493 new |= NAPIF_STATE_THREADED;
6494 } while (!try_cmpxchg(&n->state, &val, new));
6496 EXPORT_SYMBOL(napi_enable);
6498 static void flush_gro_hash(struct napi_struct *napi)
6502 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6503 struct sk_buff *skb, *n;
6505 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6507 napi->gro_hash[i].count = 0;
6511 /* Must be called in process context */
6512 void __netif_napi_del(struct napi_struct *napi)
6514 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6517 napi_hash_del(napi);
6518 list_del_rcu(&napi->dev_list);
6519 napi_free_frags(napi);
6521 flush_gro_hash(napi);
6522 napi->gro_bitmask = 0;
6525 kthread_stop(napi->thread);
6526 napi->thread = NULL;
6529 EXPORT_SYMBOL(__netif_napi_del);
6531 static int __napi_poll(struct napi_struct *n, bool *repoll)
6537 /* This NAPI_STATE_SCHED test is for avoiding a race
6538 * with netpoll's poll_napi(). Only the entity which
6539 * obtains the lock and sees NAPI_STATE_SCHED set will
6540 * actually make the ->poll() call. Therefore we avoid
6541 * accidentally calling ->poll() when NAPI is not scheduled.
6544 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6545 work = n->poll(n, weight);
6546 trace_napi_poll(n, work, weight);
6549 if (unlikely(work > weight))
6550 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6551 n->poll, work, weight);
6553 if (likely(work < weight))
6556 /* Drivers must not modify the NAPI state if they
6557 * consume the entire weight. In such cases this code
6558 * still "owns" the NAPI instance and therefore can
6559 * move the instance around on the list at-will.
6561 if (unlikely(napi_disable_pending(n))) {
6566 /* The NAPI context has more processing work, but busy-polling
6567 * is preferred. Exit early.
6569 if (napi_prefer_busy_poll(n)) {
6570 if (napi_complete_done(n, work)) {
6571 /* If timeout is not set, we need to make sure
6572 * that the NAPI is re-scheduled.
6579 if (n->gro_bitmask) {
6580 /* flush too old packets
6581 * If HZ < 1000, flush all packets.
6583 napi_gro_flush(n, HZ >= 1000);
6588 /* Some drivers may have called napi_schedule
6589 * prior to exhausting their budget.
6591 if (unlikely(!list_empty(&n->poll_list))) {
6592 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6593 n->dev ? n->dev->name : "backlog");
6602 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6604 bool do_repoll = false;
6608 list_del_init(&n->poll_list);
6610 have = netpoll_poll_lock(n);
6612 work = __napi_poll(n, &do_repoll);
6615 list_add_tail(&n->poll_list, repoll);
6617 netpoll_poll_unlock(have);
6622 static int napi_thread_wait(struct napi_struct *napi)
6626 set_current_state(TASK_INTERRUPTIBLE);
6628 while (!kthread_should_stop()) {
6629 /* Testing SCHED_THREADED bit here to make sure the current
6630 * kthread owns this napi and could poll on this napi.
6631 * Testing SCHED bit is not enough because SCHED bit might be
6632 * set by some other busy poll thread or by napi_disable().
6634 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state) || woken) {
6635 WARN_ON(!list_empty(&napi->poll_list));
6636 __set_current_state(TASK_RUNNING);
6641 /* woken being true indicates this thread owns this napi. */
6643 set_current_state(TASK_INTERRUPTIBLE);
6645 __set_current_state(TASK_RUNNING);
6650 static void skb_defer_free_flush(struct softnet_data *sd)
6652 struct sk_buff *skb, *next;
6654 /* Paired with WRITE_ONCE() in skb_attempt_defer_free() */
6655 if (!READ_ONCE(sd->defer_list))
6658 spin_lock(&sd->defer_lock);
6659 skb = sd->defer_list;
6660 sd->defer_list = NULL;
6661 sd->defer_count = 0;
6662 spin_unlock(&sd->defer_lock);
6664 while (skb != NULL) {
6666 napi_consume_skb(skb, 1);
6671 static int napi_threaded_poll(void *data)
6673 struct napi_struct *napi = data;
6674 struct softnet_data *sd;
6677 while (!napi_thread_wait(napi)) {
6679 bool repoll = false;
6682 sd = this_cpu_ptr(&softnet_data);
6683 sd->in_napi_threaded_poll = true;
6685 have = netpoll_poll_lock(napi);
6686 __napi_poll(napi, &repoll);
6687 netpoll_poll_unlock(have);
6689 sd->in_napi_threaded_poll = false;
6692 if (sd_has_rps_ipi_waiting(sd)) {
6693 local_irq_disable();
6694 net_rps_action_and_irq_enable(sd);
6696 skb_defer_free_flush(sd);
6708 static __latent_entropy void net_rx_action(struct softirq_action *h)
6710 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6711 unsigned long time_limit = jiffies +
6712 usecs_to_jiffies(READ_ONCE(netdev_budget_usecs));
6713 int budget = READ_ONCE(netdev_budget);
6718 sd->in_net_rx_action = true;
6719 local_irq_disable();
6720 list_splice_init(&sd->poll_list, &list);
6724 struct napi_struct *n;
6726 skb_defer_free_flush(sd);
6728 if (list_empty(&list)) {
6729 if (list_empty(&repoll)) {
6730 sd->in_net_rx_action = false;
6732 /* We need to check if ____napi_schedule()
6733 * had refilled poll_list while
6734 * sd->in_net_rx_action was true.
6736 if (!list_empty(&sd->poll_list))
6738 if (!sd_has_rps_ipi_waiting(sd))
6744 n = list_first_entry(&list, struct napi_struct, poll_list);
6745 budget -= napi_poll(n, &repoll);
6747 /* If softirq window is exhausted then punt.
6748 * Allow this to run for 2 jiffies since which will allow
6749 * an average latency of 1.5/HZ.
6751 if (unlikely(budget <= 0 ||
6752 time_after_eq(jiffies, time_limit))) {
6758 local_irq_disable();
6760 list_splice_tail_init(&sd->poll_list, &list);
6761 list_splice_tail(&repoll, &list);
6762 list_splice(&list, &sd->poll_list);
6763 if (!list_empty(&sd->poll_list))
6764 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6766 sd->in_net_rx_action = false;
6768 net_rps_action_and_irq_enable(sd);
6772 struct netdev_adjacent {
6773 struct net_device *dev;
6774 netdevice_tracker dev_tracker;
6776 /* upper master flag, there can only be one master device per list */
6779 /* lookup ignore flag */
6782 /* counter for the number of times this device was added to us */
6785 /* private field for the users */
6788 struct list_head list;
6789 struct rcu_head rcu;
6792 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6793 struct list_head *adj_list)
6795 struct netdev_adjacent *adj;
6797 list_for_each_entry(adj, adj_list, list) {
6798 if (adj->dev == adj_dev)
6804 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6805 struct netdev_nested_priv *priv)
6807 struct net_device *dev = (struct net_device *)priv->data;
6809 return upper_dev == dev;
6813 * netdev_has_upper_dev - Check if device is linked to an upper device
6815 * @upper_dev: upper device to check
6817 * Find out if a device is linked to specified upper device and return true
6818 * in case it is. Note that this checks only immediate upper device,
6819 * not through a complete stack of devices. The caller must hold the RTNL lock.
6821 bool netdev_has_upper_dev(struct net_device *dev,
6822 struct net_device *upper_dev)
6824 struct netdev_nested_priv priv = {
6825 .data = (void *)upper_dev,
6830 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6833 EXPORT_SYMBOL(netdev_has_upper_dev);
6836 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
6838 * @upper_dev: upper device to check
6840 * Find out if a device is linked to specified upper device and return true
6841 * in case it is. Note that this checks the entire upper device chain.
6842 * The caller must hold rcu lock.
6845 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6846 struct net_device *upper_dev)
6848 struct netdev_nested_priv priv = {
6849 .data = (void *)upper_dev,
6852 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6855 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6858 * netdev_has_any_upper_dev - Check if device is linked to some device
6861 * Find out if a device is linked to an upper device and return true in case
6862 * it is. The caller must hold the RTNL lock.
6864 bool netdev_has_any_upper_dev(struct net_device *dev)
6868 return !list_empty(&dev->adj_list.upper);
6870 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6873 * netdev_master_upper_dev_get - Get master upper device
6876 * Find a master upper device and return pointer to it or NULL in case
6877 * it's not there. The caller must hold the RTNL lock.
6879 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6881 struct netdev_adjacent *upper;
6885 if (list_empty(&dev->adj_list.upper))
6888 upper = list_first_entry(&dev->adj_list.upper,
6889 struct netdev_adjacent, list);
6890 if (likely(upper->master))
6894 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6896 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
6898 struct netdev_adjacent *upper;
6902 if (list_empty(&dev->adj_list.upper))
6905 upper = list_first_entry(&dev->adj_list.upper,
6906 struct netdev_adjacent, list);
6907 if (likely(upper->master) && !upper->ignore)
6913 * netdev_has_any_lower_dev - Check if device is linked to some device
6916 * Find out if a device is linked to a lower device and return true in case
6917 * it is. The caller must hold the RTNL lock.
6919 static bool netdev_has_any_lower_dev(struct net_device *dev)
6923 return !list_empty(&dev->adj_list.lower);
6926 void *netdev_adjacent_get_private(struct list_head *adj_list)
6928 struct netdev_adjacent *adj;
6930 adj = list_entry(adj_list, struct netdev_adjacent, list);
6932 return adj->private;
6934 EXPORT_SYMBOL(netdev_adjacent_get_private);
6937 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
6939 * @iter: list_head ** of the current position
6941 * Gets the next device from the dev's upper list, starting from iter
6942 * position. The caller must hold RCU read lock.
6944 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
6945 struct list_head **iter)
6947 struct netdev_adjacent *upper;
6949 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6951 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6953 if (&upper->list == &dev->adj_list.upper)
6956 *iter = &upper->list;
6960 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
6962 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
6963 struct list_head **iter,
6966 struct netdev_adjacent *upper;
6968 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
6970 if (&upper->list == &dev->adj_list.upper)
6973 *iter = &upper->list;
6974 *ignore = upper->ignore;
6979 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
6980 struct list_head **iter)
6982 struct netdev_adjacent *upper;
6984 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6986 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6988 if (&upper->list == &dev->adj_list.upper)
6991 *iter = &upper->list;
6996 static int __netdev_walk_all_upper_dev(struct net_device *dev,
6997 int (*fn)(struct net_device *dev,
6998 struct netdev_nested_priv *priv),
6999 struct netdev_nested_priv *priv)
7001 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7002 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7007 iter = &dev->adj_list.upper;
7011 ret = fn(now, priv);
7018 udev = __netdev_next_upper_dev(now, &iter, &ignore);
7025 niter = &udev->adj_list.upper;
7026 dev_stack[cur] = now;
7027 iter_stack[cur++] = iter;
7034 next = dev_stack[--cur];
7035 niter = iter_stack[cur];
7045 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
7046 int (*fn)(struct net_device *dev,
7047 struct netdev_nested_priv *priv),
7048 struct netdev_nested_priv *priv)
7050 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7051 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7055 iter = &dev->adj_list.upper;
7059 ret = fn(now, priv);
7066 udev = netdev_next_upper_dev_rcu(now, &iter);
7071 niter = &udev->adj_list.upper;
7072 dev_stack[cur] = now;
7073 iter_stack[cur++] = iter;
7080 next = dev_stack[--cur];
7081 niter = iter_stack[cur];
7090 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7092 static bool __netdev_has_upper_dev(struct net_device *dev,
7093 struct net_device *upper_dev)
7095 struct netdev_nested_priv priv = {
7097 .data = (void *)upper_dev,
7102 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7107 * netdev_lower_get_next_private - Get the next ->private from the
7108 * lower neighbour list
7110 * @iter: list_head ** of the current position
7112 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7113 * list, starting from iter position. The caller must hold either hold the
7114 * RTNL lock or its own locking that guarantees that the neighbour lower
7115 * list will remain unchanged.
7117 void *netdev_lower_get_next_private(struct net_device *dev,
7118 struct list_head **iter)
7120 struct netdev_adjacent *lower;
7122 lower = list_entry(*iter, struct netdev_adjacent, list);
7124 if (&lower->list == &dev->adj_list.lower)
7127 *iter = lower->list.next;
7129 return lower->private;
7131 EXPORT_SYMBOL(netdev_lower_get_next_private);
7134 * netdev_lower_get_next_private_rcu - Get the next ->private from the
7135 * lower neighbour list, RCU
7138 * @iter: list_head ** of the current position
7140 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7141 * list, starting from iter position. The caller must hold RCU read lock.
7143 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
7144 struct list_head **iter)
7146 struct netdev_adjacent *lower;
7148 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
7150 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7152 if (&lower->list == &dev->adj_list.lower)
7155 *iter = &lower->list;
7157 return lower->private;
7159 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7162 * netdev_lower_get_next - Get the next device from the lower neighbour
7165 * @iter: list_head ** of the current position
7167 * Gets the next netdev_adjacent from the dev's lower neighbour
7168 * list, starting from iter position. The caller must hold RTNL lock or
7169 * its own locking that guarantees that the neighbour lower
7170 * list will remain unchanged.
7172 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7174 struct netdev_adjacent *lower;
7176 lower = list_entry(*iter, struct netdev_adjacent, list);
7178 if (&lower->list == &dev->adj_list.lower)
7181 *iter = lower->list.next;
7185 EXPORT_SYMBOL(netdev_lower_get_next);
7187 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7188 struct list_head **iter)
7190 struct netdev_adjacent *lower;
7192 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7194 if (&lower->list == &dev->adj_list.lower)
7197 *iter = &lower->list;
7202 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7203 struct list_head **iter,
7206 struct netdev_adjacent *lower;
7208 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7210 if (&lower->list == &dev->adj_list.lower)
7213 *iter = &lower->list;
7214 *ignore = lower->ignore;
7219 int netdev_walk_all_lower_dev(struct net_device *dev,
7220 int (*fn)(struct net_device *dev,
7221 struct netdev_nested_priv *priv),
7222 struct netdev_nested_priv *priv)
7224 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7225 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7229 iter = &dev->adj_list.lower;
7233 ret = fn(now, priv);
7240 ldev = netdev_next_lower_dev(now, &iter);
7245 niter = &ldev->adj_list.lower;
7246 dev_stack[cur] = now;
7247 iter_stack[cur++] = iter;
7254 next = dev_stack[--cur];
7255 niter = iter_stack[cur];
7264 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7266 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7267 int (*fn)(struct net_device *dev,
7268 struct netdev_nested_priv *priv),
7269 struct netdev_nested_priv *priv)
7271 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7272 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7277 iter = &dev->adj_list.lower;
7281 ret = fn(now, priv);
7288 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7295 niter = &ldev->adj_list.lower;
7296 dev_stack[cur] = now;
7297 iter_stack[cur++] = iter;
7304 next = dev_stack[--cur];
7305 niter = iter_stack[cur];
7315 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7316 struct list_head **iter)
7318 struct netdev_adjacent *lower;
7320 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7321 if (&lower->list == &dev->adj_list.lower)
7324 *iter = &lower->list;
7328 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7330 static u8 __netdev_upper_depth(struct net_device *dev)
7332 struct net_device *udev;
7333 struct list_head *iter;
7337 for (iter = &dev->adj_list.upper,
7338 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7340 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7343 if (max_depth < udev->upper_level)
7344 max_depth = udev->upper_level;
7350 static u8 __netdev_lower_depth(struct net_device *dev)
7352 struct net_device *ldev;
7353 struct list_head *iter;
7357 for (iter = &dev->adj_list.lower,
7358 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7360 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7363 if (max_depth < ldev->lower_level)
7364 max_depth = ldev->lower_level;
7370 static int __netdev_update_upper_level(struct net_device *dev,
7371 struct netdev_nested_priv *__unused)
7373 dev->upper_level = __netdev_upper_depth(dev) + 1;
7377 #ifdef CONFIG_LOCKDEP
7378 static LIST_HEAD(net_unlink_list);
7380 static void net_unlink_todo(struct net_device *dev)
7382 if (list_empty(&dev->unlink_list))
7383 list_add_tail(&dev->unlink_list, &net_unlink_list);
7387 static int __netdev_update_lower_level(struct net_device *dev,
7388 struct netdev_nested_priv *priv)
7390 dev->lower_level = __netdev_lower_depth(dev) + 1;
7392 #ifdef CONFIG_LOCKDEP
7396 if (priv->flags & NESTED_SYNC_IMM)
7397 dev->nested_level = dev->lower_level - 1;
7398 if (priv->flags & NESTED_SYNC_TODO)
7399 net_unlink_todo(dev);
7404 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7405 int (*fn)(struct net_device *dev,
7406 struct netdev_nested_priv *priv),
7407 struct netdev_nested_priv *priv)
7409 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7410 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7414 iter = &dev->adj_list.lower;
7418 ret = fn(now, priv);
7425 ldev = netdev_next_lower_dev_rcu(now, &iter);
7430 niter = &ldev->adj_list.lower;
7431 dev_stack[cur] = now;
7432 iter_stack[cur++] = iter;
7439 next = dev_stack[--cur];
7440 niter = iter_stack[cur];
7449 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7452 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7453 * lower neighbour list, RCU
7457 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7458 * list. The caller must hold RCU read lock.
7460 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7462 struct netdev_adjacent *lower;
7464 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7465 struct netdev_adjacent, list);
7467 return lower->private;
7470 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7473 * netdev_master_upper_dev_get_rcu - Get master upper device
7476 * Find a master upper device and return pointer to it or NULL in case
7477 * it's not there. The caller must hold the RCU read lock.
7479 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7481 struct netdev_adjacent *upper;
7483 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7484 struct netdev_adjacent, list);
7485 if (upper && likely(upper->master))
7489 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7491 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7492 struct net_device *adj_dev,
7493 struct list_head *dev_list)
7495 char linkname[IFNAMSIZ+7];
7497 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7498 "upper_%s" : "lower_%s", adj_dev->name);
7499 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7502 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7504 struct list_head *dev_list)
7506 char linkname[IFNAMSIZ+7];
7508 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7509 "upper_%s" : "lower_%s", name);
7510 sysfs_remove_link(&(dev->dev.kobj), linkname);
7513 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7514 struct net_device *adj_dev,
7515 struct list_head *dev_list)
7517 return (dev_list == &dev->adj_list.upper ||
7518 dev_list == &dev->adj_list.lower) &&
7519 net_eq(dev_net(dev), dev_net(adj_dev));
7522 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7523 struct net_device *adj_dev,
7524 struct list_head *dev_list,
7525 void *private, bool master)
7527 struct netdev_adjacent *adj;
7530 adj = __netdev_find_adj(adj_dev, dev_list);
7534 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7535 dev->name, adj_dev->name, adj->ref_nr);
7540 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7545 adj->master = master;
7547 adj->private = private;
7548 adj->ignore = false;
7549 netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL);
7551 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7552 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7554 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7555 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7560 /* Ensure that master link is always the first item in list. */
7562 ret = sysfs_create_link(&(dev->dev.kobj),
7563 &(adj_dev->dev.kobj), "master");
7565 goto remove_symlinks;
7567 list_add_rcu(&adj->list, dev_list);
7569 list_add_tail_rcu(&adj->list, dev_list);
7575 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7576 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7578 netdev_put(adj_dev, &adj->dev_tracker);
7584 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7585 struct net_device *adj_dev,
7587 struct list_head *dev_list)
7589 struct netdev_adjacent *adj;
7591 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7592 dev->name, adj_dev->name, ref_nr);
7594 adj = __netdev_find_adj(adj_dev, dev_list);
7597 pr_err("Adjacency does not exist for device %s from %s\n",
7598 dev->name, adj_dev->name);
7603 if (adj->ref_nr > ref_nr) {
7604 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7605 dev->name, adj_dev->name, ref_nr,
7606 adj->ref_nr - ref_nr);
7607 adj->ref_nr -= ref_nr;
7612 sysfs_remove_link(&(dev->dev.kobj), "master");
7614 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7615 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7617 list_del_rcu(&adj->list);
7618 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7619 adj_dev->name, dev->name, adj_dev->name);
7620 netdev_put(adj_dev, &adj->dev_tracker);
7621 kfree_rcu(adj, rcu);
7624 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7625 struct net_device *upper_dev,
7626 struct list_head *up_list,
7627 struct list_head *down_list,
7628 void *private, bool master)
7632 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7637 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7640 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7647 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7648 struct net_device *upper_dev,
7650 struct list_head *up_list,
7651 struct list_head *down_list)
7653 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7654 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7657 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7658 struct net_device *upper_dev,
7659 void *private, bool master)
7661 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7662 &dev->adj_list.upper,
7663 &upper_dev->adj_list.lower,
7667 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7668 struct net_device *upper_dev)
7670 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7671 &dev->adj_list.upper,
7672 &upper_dev->adj_list.lower);
7675 static int __netdev_upper_dev_link(struct net_device *dev,
7676 struct net_device *upper_dev, bool master,
7677 void *upper_priv, void *upper_info,
7678 struct netdev_nested_priv *priv,
7679 struct netlink_ext_ack *extack)
7681 struct netdev_notifier_changeupper_info changeupper_info = {
7686 .upper_dev = upper_dev,
7689 .upper_info = upper_info,
7691 struct net_device *master_dev;
7696 if (dev == upper_dev)
7699 /* To prevent loops, check if dev is not upper device to upper_dev. */
7700 if (__netdev_has_upper_dev(upper_dev, dev))
7703 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7707 if (__netdev_has_upper_dev(dev, upper_dev))
7710 master_dev = __netdev_master_upper_dev_get(dev);
7712 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7715 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7716 &changeupper_info.info);
7717 ret = notifier_to_errno(ret);
7721 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7726 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7727 &changeupper_info.info);
7728 ret = notifier_to_errno(ret);
7732 __netdev_update_upper_level(dev, NULL);
7733 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7735 __netdev_update_lower_level(upper_dev, priv);
7736 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7742 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7748 * netdev_upper_dev_link - Add a link to the upper device
7750 * @upper_dev: new upper device
7751 * @extack: netlink extended ack
7753 * Adds a link to device which is upper to this one. The caller must hold
7754 * the RTNL lock. On a failure a negative errno code is returned.
7755 * On success the reference counts are adjusted and the function
7758 int netdev_upper_dev_link(struct net_device *dev,
7759 struct net_device *upper_dev,
7760 struct netlink_ext_ack *extack)
7762 struct netdev_nested_priv priv = {
7763 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7767 return __netdev_upper_dev_link(dev, upper_dev, false,
7768 NULL, NULL, &priv, extack);
7770 EXPORT_SYMBOL(netdev_upper_dev_link);
7773 * netdev_master_upper_dev_link - Add a master link to the upper device
7775 * @upper_dev: new upper device
7776 * @upper_priv: upper device private
7777 * @upper_info: upper info to be passed down via notifier
7778 * @extack: netlink extended ack
7780 * Adds a link to device which is upper to this one. In this case, only
7781 * one master upper device can be linked, although other non-master devices
7782 * might be linked as well. The caller must hold the RTNL lock.
7783 * On a failure a negative errno code is returned. On success the reference
7784 * counts are adjusted and the function returns zero.
7786 int netdev_master_upper_dev_link(struct net_device *dev,
7787 struct net_device *upper_dev,
7788 void *upper_priv, void *upper_info,
7789 struct netlink_ext_ack *extack)
7791 struct netdev_nested_priv priv = {
7792 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7796 return __netdev_upper_dev_link(dev, upper_dev, true,
7797 upper_priv, upper_info, &priv, extack);
7799 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7801 static void __netdev_upper_dev_unlink(struct net_device *dev,
7802 struct net_device *upper_dev,
7803 struct netdev_nested_priv *priv)
7805 struct netdev_notifier_changeupper_info changeupper_info = {
7809 .upper_dev = upper_dev,
7815 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7817 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7818 &changeupper_info.info);
7820 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7822 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7823 &changeupper_info.info);
7825 __netdev_update_upper_level(dev, NULL);
7826 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7828 __netdev_update_lower_level(upper_dev, priv);
7829 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7834 * netdev_upper_dev_unlink - Removes a link to upper device
7836 * @upper_dev: new upper device
7838 * Removes a link to device which is upper to this one. The caller must hold
7841 void netdev_upper_dev_unlink(struct net_device *dev,
7842 struct net_device *upper_dev)
7844 struct netdev_nested_priv priv = {
7845 .flags = NESTED_SYNC_TODO,
7849 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
7851 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7853 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7854 struct net_device *lower_dev,
7857 struct netdev_adjacent *adj;
7859 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
7863 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
7868 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
7869 struct net_device *lower_dev)
7871 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
7874 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
7875 struct net_device *lower_dev)
7877 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
7880 int netdev_adjacent_change_prepare(struct net_device *old_dev,
7881 struct net_device *new_dev,
7882 struct net_device *dev,
7883 struct netlink_ext_ack *extack)
7885 struct netdev_nested_priv priv = {
7894 if (old_dev && new_dev != old_dev)
7895 netdev_adjacent_dev_disable(dev, old_dev);
7896 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
7899 if (old_dev && new_dev != old_dev)
7900 netdev_adjacent_dev_enable(dev, old_dev);
7906 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
7908 void netdev_adjacent_change_commit(struct net_device *old_dev,
7909 struct net_device *new_dev,
7910 struct net_device *dev)
7912 struct netdev_nested_priv priv = {
7913 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7917 if (!new_dev || !old_dev)
7920 if (new_dev == old_dev)
7923 netdev_adjacent_dev_enable(dev, old_dev);
7924 __netdev_upper_dev_unlink(old_dev, dev, &priv);
7926 EXPORT_SYMBOL(netdev_adjacent_change_commit);
7928 void netdev_adjacent_change_abort(struct net_device *old_dev,
7929 struct net_device *new_dev,
7930 struct net_device *dev)
7932 struct netdev_nested_priv priv = {
7940 if (old_dev && new_dev != old_dev)
7941 netdev_adjacent_dev_enable(dev, old_dev);
7943 __netdev_upper_dev_unlink(new_dev, dev, &priv);
7945 EXPORT_SYMBOL(netdev_adjacent_change_abort);
7948 * netdev_bonding_info_change - Dispatch event about slave change
7950 * @bonding_info: info to dispatch
7952 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
7953 * The caller must hold the RTNL lock.
7955 void netdev_bonding_info_change(struct net_device *dev,
7956 struct netdev_bonding_info *bonding_info)
7958 struct netdev_notifier_bonding_info info = {
7962 memcpy(&info.bonding_info, bonding_info,
7963 sizeof(struct netdev_bonding_info));
7964 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
7967 EXPORT_SYMBOL(netdev_bonding_info_change);
7969 static int netdev_offload_xstats_enable_l3(struct net_device *dev,
7970 struct netlink_ext_ack *extack)
7972 struct netdev_notifier_offload_xstats_info info = {
7974 .info.extack = extack,
7975 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
7980 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
7982 if (!dev->offload_xstats_l3)
7985 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
7986 NETDEV_OFFLOAD_XSTATS_DISABLE,
7988 err = notifier_to_errno(rc);
7995 kfree(dev->offload_xstats_l3);
7996 dev->offload_xstats_l3 = NULL;
8000 int netdev_offload_xstats_enable(struct net_device *dev,
8001 enum netdev_offload_xstats_type type,
8002 struct netlink_ext_ack *extack)
8006 if (netdev_offload_xstats_enabled(dev, type))
8010 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8011 return netdev_offload_xstats_enable_l3(dev, extack);
8017 EXPORT_SYMBOL(netdev_offload_xstats_enable);
8019 static void netdev_offload_xstats_disable_l3(struct net_device *dev)
8021 struct netdev_notifier_offload_xstats_info info = {
8023 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
8026 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
8028 kfree(dev->offload_xstats_l3);
8029 dev->offload_xstats_l3 = NULL;
8032 int netdev_offload_xstats_disable(struct net_device *dev,
8033 enum netdev_offload_xstats_type type)
8037 if (!netdev_offload_xstats_enabled(dev, type))
8041 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8042 netdev_offload_xstats_disable_l3(dev);
8049 EXPORT_SYMBOL(netdev_offload_xstats_disable);
8051 static void netdev_offload_xstats_disable_all(struct net_device *dev)
8053 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
8056 static struct rtnl_hw_stats64 *
8057 netdev_offload_xstats_get_ptr(const struct net_device *dev,
8058 enum netdev_offload_xstats_type type)
8061 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8062 return dev->offload_xstats_l3;
8069 bool netdev_offload_xstats_enabled(const struct net_device *dev,
8070 enum netdev_offload_xstats_type type)
8074 return netdev_offload_xstats_get_ptr(dev, type);
8076 EXPORT_SYMBOL(netdev_offload_xstats_enabled);
8078 struct netdev_notifier_offload_xstats_ru {
8082 struct netdev_notifier_offload_xstats_rd {
8083 struct rtnl_hw_stats64 stats;
8087 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
8088 const struct rtnl_hw_stats64 *src)
8090 dest->rx_packets += src->rx_packets;
8091 dest->tx_packets += src->tx_packets;
8092 dest->rx_bytes += src->rx_bytes;
8093 dest->tx_bytes += src->tx_bytes;
8094 dest->rx_errors += src->rx_errors;
8095 dest->tx_errors += src->tx_errors;
8096 dest->rx_dropped += src->rx_dropped;
8097 dest->tx_dropped += src->tx_dropped;
8098 dest->multicast += src->multicast;
8101 static int netdev_offload_xstats_get_used(struct net_device *dev,
8102 enum netdev_offload_xstats_type type,
8104 struct netlink_ext_ack *extack)
8106 struct netdev_notifier_offload_xstats_ru report_used = {};
8107 struct netdev_notifier_offload_xstats_info info = {
8109 .info.extack = extack,
8111 .report_used = &report_used,
8115 WARN_ON(!netdev_offload_xstats_enabled(dev, type));
8116 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
8118 *p_used = report_used.used;
8119 return notifier_to_errno(rc);
8122 static int netdev_offload_xstats_get_stats(struct net_device *dev,
8123 enum netdev_offload_xstats_type type,
8124 struct rtnl_hw_stats64 *p_stats,
8126 struct netlink_ext_ack *extack)
8128 struct netdev_notifier_offload_xstats_rd report_delta = {};
8129 struct netdev_notifier_offload_xstats_info info = {
8131 .info.extack = extack,
8133 .report_delta = &report_delta,
8135 struct rtnl_hw_stats64 *stats;
8138 stats = netdev_offload_xstats_get_ptr(dev, type);
8139 if (WARN_ON(!stats))
8142 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
8145 /* Cache whatever we got, even if there was an error, otherwise the
8146 * successful stats retrievals would get lost.
8148 netdev_hw_stats64_add(stats, &report_delta.stats);
8152 *p_used = report_delta.used;
8154 return notifier_to_errno(rc);
8157 int netdev_offload_xstats_get(struct net_device *dev,
8158 enum netdev_offload_xstats_type type,
8159 struct rtnl_hw_stats64 *p_stats, bool *p_used,
8160 struct netlink_ext_ack *extack)
8165 return netdev_offload_xstats_get_stats(dev, type, p_stats,
8168 return netdev_offload_xstats_get_used(dev, type, p_used,
8171 EXPORT_SYMBOL(netdev_offload_xstats_get);
8174 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
8175 const struct rtnl_hw_stats64 *stats)
8177 report_delta->used = true;
8178 netdev_hw_stats64_add(&report_delta->stats, stats);
8180 EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
8183 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
8185 report_used->used = true;
8187 EXPORT_SYMBOL(netdev_offload_xstats_report_used);
8189 void netdev_offload_xstats_push_delta(struct net_device *dev,
8190 enum netdev_offload_xstats_type type,
8191 const struct rtnl_hw_stats64 *p_stats)
8193 struct rtnl_hw_stats64 *stats;
8197 stats = netdev_offload_xstats_get_ptr(dev, type);
8198 if (WARN_ON(!stats))
8201 netdev_hw_stats64_add(stats, p_stats);
8203 EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
8206 * netdev_get_xmit_slave - Get the xmit slave of master device
8209 * @all_slaves: assume all the slaves are active
8211 * The reference counters are not incremented so the caller must be
8212 * careful with locks. The caller must hold RCU lock.
8213 * %NULL is returned if no slave is found.
8216 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8217 struct sk_buff *skb,
8220 const struct net_device_ops *ops = dev->netdev_ops;
8222 if (!ops->ndo_get_xmit_slave)
8224 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8226 EXPORT_SYMBOL(netdev_get_xmit_slave);
8228 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
8231 const struct net_device_ops *ops = dev->netdev_ops;
8233 if (!ops->ndo_sk_get_lower_dev)
8235 return ops->ndo_sk_get_lower_dev(dev, sk);
8239 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
8243 * %NULL is returned if no lower device is found.
8246 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
8249 struct net_device *lower;
8251 lower = netdev_sk_get_lower_dev(dev, sk);
8254 lower = netdev_sk_get_lower_dev(dev, sk);
8259 EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
8261 static void netdev_adjacent_add_links(struct net_device *dev)
8263 struct netdev_adjacent *iter;
8265 struct net *net = dev_net(dev);
8267 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8268 if (!net_eq(net, dev_net(iter->dev)))
8270 netdev_adjacent_sysfs_add(iter->dev, dev,
8271 &iter->dev->adj_list.lower);
8272 netdev_adjacent_sysfs_add(dev, iter->dev,
8273 &dev->adj_list.upper);
8276 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8277 if (!net_eq(net, dev_net(iter->dev)))
8279 netdev_adjacent_sysfs_add(iter->dev, dev,
8280 &iter->dev->adj_list.upper);
8281 netdev_adjacent_sysfs_add(dev, iter->dev,
8282 &dev->adj_list.lower);
8286 static void netdev_adjacent_del_links(struct net_device *dev)
8288 struct netdev_adjacent *iter;
8290 struct net *net = dev_net(dev);
8292 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8293 if (!net_eq(net, dev_net(iter->dev)))
8295 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8296 &iter->dev->adj_list.lower);
8297 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8298 &dev->adj_list.upper);
8301 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8302 if (!net_eq(net, dev_net(iter->dev)))
8304 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8305 &iter->dev->adj_list.upper);
8306 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8307 &dev->adj_list.lower);
8311 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8313 struct netdev_adjacent *iter;
8315 struct net *net = dev_net(dev);
8317 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8318 if (!net_eq(net, dev_net(iter->dev)))
8320 netdev_adjacent_sysfs_del(iter->dev, oldname,
8321 &iter->dev->adj_list.lower);
8322 netdev_adjacent_sysfs_add(iter->dev, dev,
8323 &iter->dev->adj_list.lower);
8326 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8327 if (!net_eq(net, dev_net(iter->dev)))
8329 netdev_adjacent_sysfs_del(iter->dev, oldname,
8330 &iter->dev->adj_list.upper);
8331 netdev_adjacent_sysfs_add(iter->dev, dev,
8332 &iter->dev->adj_list.upper);
8336 void *netdev_lower_dev_get_private(struct net_device *dev,
8337 struct net_device *lower_dev)
8339 struct netdev_adjacent *lower;
8343 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8347 return lower->private;
8349 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8353 * netdev_lower_state_changed - Dispatch event about lower device state change
8354 * @lower_dev: device
8355 * @lower_state_info: state to dispatch
8357 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8358 * The caller must hold the RTNL lock.
8360 void netdev_lower_state_changed(struct net_device *lower_dev,
8361 void *lower_state_info)
8363 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8364 .info.dev = lower_dev,
8368 changelowerstate_info.lower_state_info = lower_state_info;
8369 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8370 &changelowerstate_info.info);
8372 EXPORT_SYMBOL(netdev_lower_state_changed);
8374 static void dev_change_rx_flags(struct net_device *dev, int flags)
8376 const struct net_device_ops *ops = dev->netdev_ops;
8378 if (ops->ndo_change_rx_flags)
8379 ops->ndo_change_rx_flags(dev, flags);
8382 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8384 unsigned int old_flags = dev->flags;
8390 dev->flags |= IFF_PROMISC;
8391 dev->promiscuity += inc;
8392 if (dev->promiscuity == 0) {
8395 * If inc causes overflow, untouch promisc and return error.
8398 dev->flags &= ~IFF_PROMISC;
8400 dev->promiscuity -= inc;
8401 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
8405 if (dev->flags != old_flags) {
8406 netdev_info(dev, "%s promiscuous mode\n",
8407 dev->flags & IFF_PROMISC ? "entered" : "left");
8408 if (audit_enabled) {
8409 current_uid_gid(&uid, &gid);
8410 audit_log(audit_context(), GFP_ATOMIC,
8411 AUDIT_ANOM_PROMISCUOUS,
8412 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8413 dev->name, (dev->flags & IFF_PROMISC),
8414 (old_flags & IFF_PROMISC),
8415 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8416 from_kuid(&init_user_ns, uid),
8417 from_kgid(&init_user_ns, gid),
8418 audit_get_sessionid(current));
8421 dev_change_rx_flags(dev, IFF_PROMISC);
8424 __dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL);
8429 * dev_set_promiscuity - update promiscuity count on a device
8433 * Add or remove promiscuity from a device. While the count in the device
8434 * remains above zero the interface remains promiscuous. Once it hits zero
8435 * the device reverts back to normal filtering operation. A negative inc
8436 * value is used to drop promiscuity on the device.
8437 * Return 0 if successful or a negative errno code on error.
8439 int dev_set_promiscuity(struct net_device *dev, int inc)
8441 unsigned int old_flags = dev->flags;
8444 err = __dev_set_promiscuity(dev, inc, true);
8447 if (dev->flags != old_flags)
8448 dev_set_rx_mode(dev);
8451 EXPORT_SYMBOL(dev_set_promiscuity);
8453 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8455 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8459 dev->flags |= IFF_ALLMULTI;
8460 dev->allmulti += inc;
8461 if (dev->allmulti == 0) {
8464 * If inc causes overflow, untouch allmulti and return error.
8467 dev->flags &= ~IFF_ALLMULTI;
8469 dev->allmulti -= inc;
8470 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
8474 if (dev->flags ^ old_flags) {
8475 netdev_info(dev, "%s allmulticast mode\n",
8476 dev->flags & IFF_ALLMULTI ? "entered" : "left");
8477 dev_change_rx_flags(dev, IFF_ALLMULTI);
8478 dev_set_rx_mode(dev);
8480 __dev_notify_flags(dev, old_flags,
8481 dev->gflags ^ old_gflags, 0, NULL);
8487 * dev_set_allmulti - update allmulti count on a device
8491 * Add or remove reception of all multicast frames to a device. While the
8492 * count in the device remains above zero the interface remains listening
8493 * to all interfaces. Once it hits zero the device reverts back to normal
8494 * filtering operation. A negative @inc value is used to drop the counter
8495 * when releasing a resource needing all multicasts.
8496 * Return 0 if successful or a negative errno code on error.
8499 int dev_set_allmulti(struct net_device *dev, int inc)
8501 return __dev_set_allmulti(dev, inc, true);
8503 EXPORT_SYMBOL(dev_set_allmulti);
8506 * Upload unicast and multicast address lists to device and
8507 * configure RX filtering. When the device doesn't support unicast
8508 * filtering it is put in promiscuous mode while unicast addresses
8511 void __dev_set_rx_mode(struct net_device *dev)
8513 const struct net_device_ops *ops = dev->netdev_ops;
8515 /* dev_open will call this function so the list will stay sane. */
8516 if (!(dev->flags&IFF_UP))
8519 if (!netif_device_present(dev))
8522 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8523 /* Unicast addresses changes may only happen under the rtnl,
8524 * therefore calling __dev_set_promiscuity here is safe.
8526 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8527 __dev_set_promiscuity(dev, 1, false);
8528 dev->uc_promisc = true;
8529 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8530 __dev_set_promiscuity(dev, -1, false);
8531 dev->uc_promisc = false;
8535 if (ops->ndo_set_rx_mode)
8536 ops->ndo_set_rx_mode(dev);
8539 void dev_set_rx_mode(struct net_device *dev)
8541 netif_addr_lock_bh(dev);
8542 __dev_set_rx_mode(dev);
8543 netif_addr_unlock_bh(dev);
8547 * dev_get_flags - get flags reported to userspace
8550 * Get the combination of flag bits exported through APIs to userspace.
8552 unsigned int dev_get_flags(const struct net_device *dev)
8556 flags = (dev->flags & ~(IFF_PROMISC |
8561 (dev->gflags & (IFF_PROMISC |
8564 if (netif_running(dev)) {
8565 if (netif_oper_up(dev))
8566 flags |= IFF_RUNNING;
8567 if (netif_carrier_ok(dev))
8568 flags |= IFF_LOWER_UP;
8569 if (netif_dormant(dev))
8570 flags |= IFF_DORMANT;
8575 EXPORT_SYMBOL(dev_get_flags);
8577 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8578 struct netlink_ext_ack *extack)
8580 unsigned int old_flags = dev->flags;
8586 * Set the flags on our device.
8589 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8590 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8592 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8596 * Load in the correct multicast list now the flags have changed.
8599 if ((old_flags ^ flags) & IFF_MULTICAST)
8600 dev_change_rx_flags(dev, IFF_MULTICAST);
8602 dev_set_rx_mode(dev);
8605 * Have we downed the interface. We handle IFF_UP ourselves
8606 * according to user attempts to set it, rather than blindly
8611 if ((old_flags ^ flags) & IFF_UP) {
8612 if (old_flags & IFF_UP)
8615 ret = __dev_open(dev, extack);
8618 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8619 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8620 unsigned int old_flags = dev->flags;
8622 dev->gflags ^= IFF_PROMISC;
8624 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8625 if (dev->flags != old_flags)
8626 dev_set_rx_mode(dev);
8629 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8630 * is important. Some (broken) drivers set IFF_PROMISC, when
8631 * IFF_ALLMULTI is requested not asking us and not reporting.
8633 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8634 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8636 dev->gflags ^= IFF_ALLMULTI;
8637 __dev_set_allmulti(dev, inc, false);
8643 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8644 unsigned int gchanges, u32 portid,
8645 const struct nlmsghdr *nlh)
8647 unsigned int changes = dev->flags ^ old_flags;
8650 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh);
8652 if (changes & IFF_UP) {
8653 if (dev->flags & IFF_UP)
8654 call_netdevice_notifiers(NETDEV_UP, dev);
8656 call_netdevice_notifiers(NETDEV_DOWN, dev);
8659 if (dev->flags & IFF_UP &&
8660 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8661 struct netdev_notifier_change_info change_info = {
8665 .flags_changed = changes,
8668 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8673 * dev_change_flags - change device settings
8675 * @flags: device state flags
8676 * @extack: netlink extended ack
8678 * Change settings on device based state flags. The flags are
8679 * in the userspace exported format.
8681 int dev_change_flags(struct net_device *dev, unsigned int flags,
8682 struct netlink_ext_ack *extack)
8685 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8687 ret = __dev_change_flags(dev, flags, extack);
8691 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8692 __dev_notify_flags(dev, old_flags, changes, 0, NULL);
8695 EXPORT_SYMBOL(dev_change_flags);
8697 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8699 const struct net_device_ops *ops = dev->netdev_ops;
8701 if (ops->ndo_change_mtu)
8702 return ops->ndo_change_mtu(dev, new_mtu);
8704 /* Pairs with all the lockless reads of dev->mtu in the stack */
8705 WRITE_ONCE(dev->mtu, new_mtu);
8708 EXPORT_SYMBOL(__dev_set_mtu);
8710 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8711 struct netlink_ext_ack *extack)
8713 /* MTU must be positive, and in range */
8714 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8715 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8719 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8720 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8727 * dev_set_mtu_ext - Change maximum transfer unit
8729 * @new_mtu: new transfer unit
8730 * @extack: netlink extended ack
8732 * Change the maximum transfer size of the network device.
8734 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8735 struct netlink_ext_ack *extack)
8739 if (new_mtu == dev->mtu)
8742 err = dev_validate_mtu(dev, new_mtu, extack);
8746 if (!netif_device_present(dev))
8749 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8750 err = notifier_to_errno(err);
8754 orig_mtu = dev->mtu;
8755 err = __dev_set_mtu(dev, new_mtu);
8758 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8760 err = notifier_to_errno(err);
8762 /* setting mtu back and notifying everyone again,
8763 * so that they have a chance to revert changes.
8765 __dev_set_mtu(dev, orig_mtu);
8766 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8773 int dev_set_mtu(struct net_device *dev, int new_mtu)
8775 struct netlink_ext_ack extack;
8778 memset(&extack, 0, sizeof(extack));
8779 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8780 if (err && extack._msg)
8781 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8784 EXPORT_SYMBOL(dev_set_mtu);
8787 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8789 * @new_len: new tx queue length
8791 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8793 unsigned int orig_len = dev->tx_queue_len;
8796 if (new_len != (unsigned int)new_len)
8799 if (new_len != orig_len) {
8800 dev->tx_queue_len = new_len;
8801 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8802 res = notifier_to_errno(res);
8805 res = dev_qdisc_change_tx_queue_len(dev);
8813 netdev_err(dev, "refused to change device tx_queue_len\n");
8814 dev->tx_queue_len = orig_len;
8819 * dev_set_group - Change group this device belongs to
8821 * @new_group: group this device should belong to
8823 void dev_set_group(struct net_device *dev, int new_group)
8825 dev->group = new_group;
8829 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8831 * @addr: new address
8832 * @extack: netlink extended ack
8834 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8835 struct netlink_ext_ack *extack)
8837 struct netdev_notifier_pre_changeaddr_info info = {
8839 .info.extack = extack,
8844 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8845 return notifier_to_errno(rc);
8847 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8850 * dev_set_mac_address - Change Media Access Control Address
8853 * @extack: netlink extended ack
8855 * Change the hardware (MAC) address of the device
8857 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8858 struct netlink_ext_ack *extack)
8860 const struct net_device_ops *ops = dev->netdev_ops;
8863 if (!ops->ndo_set_mac_address)
8865 if (sa->sa_family != dev->type)
8867 if (!netif_device_present(dev))
8869 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8872 if (memcmp(dev->dev_addr, sa->sa_data, dev->addr_len)) {
8873 err = ops->ndo_set_mac_address(dev, sa);
8877 dev->addr_assign_type = NET_ADDR_SET;
8878 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8879 add_device_randomness(dev->dev_addr, dev->addr_len);
8882 EXPORT_SYMBOL(dev_set_mac_address);
8884 static DECLARE_RWSEM(dev_addr_sem);
8886 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
8887 struct netlink_ext_ack *extack)
8891 down_write(&dev_addr_sem);
8892 ret = dev_set_mac_address(dev, sa, extack);
8893 up_write(&dev_addr_sem);
8896 EXPORT_SYMBOL(dev_set_mac_address_user);
8898 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
8900 size_t size = sizeof(sa->sa_data_min);
8901 struct net_device *dev;
8904 down_read(&dev_addr_sem);
8907 dev = dev_get_by_name_rcu(net, dev_name);
8913 memset(sa->sa_data, 0, size);
8915 memcpy(sa->sa_data, dev->dev_addr,
8916 min_t(size_t, size, dev->addr_len));
8917 sa->sa_family = dev->type;
8921 up_read(&dev_addr_sem);
8924 EXPORT_SYMBOL(dev_get_mac_address);
8927 * dev_change_carrier - Change device carrier
8929 * @new_carrier: new value
8931 * Change device carrier
8933 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8935 const struct net_device_ops *ops = dev->netdev_ops;
8937 if (!ops->ndo_change_carrier)
8939 if (!netif_device_present(dev))
8941 return ops->ndo_change_carrier(dev, new_carrier);
8945 * dev_get_phys_port_id - Get device physical port ID
8949 * Get device physical port ID
8951 int dev_get_phys_port_id(struct net_device *dev,
8952 struct netdev_phys_item_id *ppid)
8954 const struct net_device_ops *ops = dev->netdev_ops;
8956 if (!ops->ndo_get_phys_port_id)
8958 return ops->ndo_get_phys_port_id(dev, ppid);
8962 * dev_get_phys_port_name - Get device physical port name
8965 * @len: limit of bytes to copy to name
8967 * Get device physical port name
8969 int dev_get_phys_port_name(struct net_device *dev,
8970 char *name, size_t len)
8972 const struct net_device_ops *ops = dev->netdev_ops;
8975 if (ops->ndo_get_phys_port_name) {
8976 err = ops->ndo_get_phys_port_name(dev, name, len);
8977 if (err != -EOPNOTSUPP)
8980 return devlink_compat_phys_port_name_get(dev, name, len);
8984 * dev_get_port_parent_id - Get the device's port parent identifier
8985 * @dev: network device
8986 * @ppid: pointer to a storage for the port's parent identifier
8987 * @recurse: allow/disallow recursion to lower devices
8989 * Get the devices's port parent identifier
8991 int dev_get_port_parent_id(struct net_device *dev,
8992 struct netdev_phys_item_id *ppid,
8995 const struct net_device_ops *ops = dev->netdev_ops;
8996 struct netdev_phys_item_id first = { };
8997 struct net_device *lower_dev;
8998 struct list_head *iter;
9001 if (ops->ndo_get_port_parent_id) {
9002 err = ops->ndo_get_port_parent_id(dev, ppid);
9003 if (err != -EOPNOTSUPP)
9007 err = devlink_compat_switch_id_get(dev, ppid);
9008 if (!recurse || err != -EOPNOTSUPP)
9011 netdev_for_each_lower_dev(dev, lower_dev, iter) {
9012 err = dev_get_port_parent_id(lower_dev, ppid, true);
9017 else if (memcmp(&first, ppid, sizeof(*ppid)))
9023 EXPORT_SYMBOL(dev_get_port_parent_id);
9026 * netdev_port_same_parent_id - Indicate if two network devices have
9027 * the same port parent identifier
9028 * @a: first network device
9029 * @b: second network device
9031 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
9033 struct netdev_phys_item_id a_id = { };
9034 struct netdev_phys_item_id b_id = { };
9036 if (dev_get_port_parent_id(a, &a_id, true) ||
9037 dev_get_port_parent_id(b, &b_id, true))
9040 return netdev_phys_item_id_same(&a_id, &b_id);
9042 EXPORT_SYMBOL(netdev_port_same_parent_id);
9045 * dev_change_proto_down - set carrier according to proto_down.
9048 * @proto_down: new value
9050 int dev_change_proto_down(struct net_device *dev, bool proto_down)
9052 if (!(dev->priv_flags & IFF_CHANGE_PROTO_DOWN))
9054 if (!netif_device_present(dev))
9057 netif_carrier_off(dev);
9059 netif_carrier_on(dev);
9060 dev->proto_down = proto_down;
9065 * dev_change_proto_down_reason - proto down reason
9068 * @mask: proto down mask
9069 * @value: proto down value
9071 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
9077 dev->proto_down_reason = value;
9079 for_each_set_bit(b, &mask, 32) {
9080 if (value & (1 << b))
9081 dev->proto_down_reason |= BIT(b);
9083 dev->proto_down_reason &= ~BIT(b);
9088 struct bpf_xdp_link {
9089 struct bpf_link link;
9090 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
9094 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
9096 if (flags & XDP_FLAGS_HW_MODE)
9098 if (flags & XDP_FLAGS_DRV_MODE)
9099 return XDP_MODE_DRV;
9100 if (flags & XDP_FLAGS_SKB_MODE)
9101 return XDP_MODE_SKB;
9102 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
9105 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
9109 return generic_xdp_install;
9112 return dev->netdev_ops->ndo_bpf;
9118 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
9119 enum bpf_xdp_mode mode)
9121 return dev->xdp_state[mode].link;
9124 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
9125 enum bpf_xdp_mode mode)
9127 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
9130 return link->link.prog;
9131 return dev->xdp_state[mode].prog;
9134 u8 dev_xdp_prog_count(struct net_device *dev)
9139 for (i = 0; i < __MAX_XDP_MODE; i++)
9140 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
9144 EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
9146 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
9148 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
9150 return prog ? prog->aux->id : 0;
9153 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
9154 struct bpf_xdp_link *link)
9156 dev->xdp_state[mode].link = link;
9157 dev->xdp_state[mode].prog = NULL;
9160 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
9161 struct bpf_prog *prog)
9163 dev->xdp_state[mode].link = NULL;
9164 dev->xdp_state[mode].prog = prog;
9167 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
9168 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
9169 u32 flags, struct bpf_prog *prog)
9171 struct netdev_bpf xdp;
9174 memset(&xdp, 0, sizeof(xdp));
9175 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
9176 xdp.extack = extack;
9180 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
9181 * "moved" into driver), so they don't increment it on their own, but
9182 * they do decrement refcnt when program is detached or replaced.
9183 * Given net_device also owns link/prog, we need to bump refcnt here
9184 * to prevent drivers from underflowing it.
9188 err = bpf_op(dev, &xdp);
9195 if (mode != XDP_MODE_HW)
9196 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9201 static void dev_xdp_uninstall(struct net_device *dev)
9203 struct bpf_xdp_link *link;
9204 struct bpf_prog *prog;
9205 enum bpf_xdp_mode mode;
9210 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9211 prog = dev_xdp_prog(dev, mode);
9215 bpf_op = dev_xdp_bpf_op(dev, mode);
9219 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9221 /* auto-detach link from net device */
9222 link = dev_xdp_link(dev, mode);
9228 dev_xdp_set_link(dev, mode, NULL);
9232 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9233 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9234 struct bpf_prog *old_prog, u32 flags)
9236 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9237 struct bpf_prog *cur_prog;
9238 struct net_device *upper;
9239 struct list_head *iter;
9240 enum bpf_xdp_mode mode;
9246 /* either link or prog attachment, never both */
9247 if (link && (new_prog || old_prog))
9249 /* link supports only XDP mode flags */
9250 if (link && (flags & ~XDP_FLAGS_MODES)) {
9251 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9254 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9255 if (num_modes > 1) {
9256 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9259 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9260 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9261 NL_SET_ERR_MSG(extack,
9262 "More than one program loaded, unset mode is ambiguous");
9265 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9266 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9267 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9271 mode = dev_xdp_mode(dev, flags);
9272 /* can't replace attached link */
9273 if (dev_xdp_link(dev, mode)) {
9274 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9278 /* don't allow if an upper device already has a program */
9279 netdev_for_each_upper_dev_rcu(dev, upper, iter) {
9280 if (dev_xdp_prog_count(upper) > 0) {
9281 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
9286 cur_prog = dev_xdp_prog(dev, mode);
9287 /* can't replace attached prog with link */
9288 if (link && cur_prog) {
9289 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9292 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9293 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9297 /* put effective new program into new_prog */
9299 new_prog = link->link.prog;
9302 bool offload = mode == XDP_MODE_HW;
9303 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9304 ? XDP_MODE_DRV : XDP_MODE_SKB;
9306 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9307 NL_SET_ERR_MSG(extack, "XDP program already attached");
9310 if (!offload && dev_xdp_prog(dev, other_mode)) {
9311 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9314 if (!offload && bpf_prog_is_offloaded(new_prog->aux)) {
9315 NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
9318 if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) {
9319 NL_SET_ERR_MSG(extack, "Program bound to different device");
9322 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9323 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9326 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9327 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9332 /* don't call drivers if the effective program didn't change */
9333 if (new_prog != cur_prog) {
9334 bpf_op = dev_xdp_bpf_op(dev, mode);
9336 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9340 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9346 dev_xdp_set_link(dev, mode, link);
9348 dev_xdp_set_prog(dev, mode, new_prog);
9350 bpf_prog_put(cur_prog);
9355 static int dev_xdp_attach_link(struct net_device *dev,
9356 struct netlink_ext_ack *extack,
9357 struct bpf_xdp_link *link)
9359 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9362 static int dev_xdp_detach_link(struct net_device *dev,
9363 struct netlink_ext_ack *extack,
9364 struct bpf_xdp_link *link)
9366 enum bpf_xdp_mode mode;
9371 mode = dev_xdp_mode(dev, link->flags);
9372 if (dev_xdp_link(dev, mode) != link)
9375 bpf_op = dev_xdp_bpf_op(dev, mode);
9376 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9377 dev_xdp_set_link(dev, mode, NULL);
9381 static void bpf_xdp_link_release(struct bpf_link *link)
9383 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9387 /* if racing with net_device's tear down, xdp_link->dev might be
9388 * already NULL, in which case link was already auto-detached
9390 if (xdp_link->dev) {
9391 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9392 xdp_link->dev = NULL;
9398 static int bpf_xdp_link_detach(struct bpf_link *link)
9400 bpf_xdp_link_release(link);
9404 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9406 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9411 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9412 struct seq_file *seq)
9414 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9419 ifindex = xdp_link->dev->ifindex;
9422 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9425 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9426 struct bpf_link_info *info)
9428 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9433 ifindex = xdp_link->dev->ifindex;
9436 info->xdp.ifindex = ifindex;
9440 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9441 struct bpf_prog *old_prog)
9443 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9444 enum bpf_xdp_mode mode;
9450 /* link might have been auto-released already, so fail */
9451 if (!xdp_link->dev) {
9456 if (old_prog && link->prog != old_prog) {
9460 old_prog = link->prog;
9461 if (old_prog->type != new_prog->type ||
9462 old_prog->expected_attach_type != new_prog->expected_attach_type) {
9467 if (old_prog == new_prog) {
9468 /* no-op, don't disturb drivers */
9469 bpf_prog_put(new_prog);
9473 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9474 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9475 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9476 xdp_link->flags, new_prog);
9480 old_prog = xchg(&link->prog, new_prog);
9481 bpf_prog_put(old_prog);
9488 static const struct bpf_link_ops bpf_xdp_link_lops = {
9489 .release = bpf_xdp_link_release,
9490 .dealloc = bpf_xdp_link_dealloc,
9491 .detach = bpf_xdp_link_detach,
9492 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9493 .fill_link_info = bpf_xdp_link_fill_link_info,
9494 .update_prog = bpf_xdp_link_update,
9497 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9499 struct net *net = current->nsproxy->net_ns;
9500 struct bpf_link_primer link_primer;
9501 struct netlink_ext_ack extack = {};
9502 struct bpf_xdp_link *link;
9503 struct net_device *dev;
9507 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9513 link = kzalloc(sizeof(*link), GFP_USER);
9519 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9521 link->flags = attr->link_create.flags;
9523 err = bpf_link_prime(&link->link, &link_primer);
9529 err = dev_xdp_attach_link(dev, &extack, link);
9534 bpf_link_cleanup(&link_primer);
9535 trace_bpf_xdp_link_attach_failed(extack._msg);
9539 fd = bpf_link_settle(&link_primer);
9540 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9553 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9555 * @extack: netlink extended ack
9556 * @fd: new program fd or negative value to clear
9557 * @expected_fd: old program fd that userspace expects to replace or clear
9558 * @flags: xdp-related flags
9560 * Set or clear a bpf program for a device
9562 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9563 int fd, int expected_fd, u32 flags)
9565 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9566 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9572 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9573 mode != XDP_MODE_SKB);
9574 if (IS_ERR(new_prog))
9575 return PTR_ERR(new_prog);
9578 if (expected_fd >= 0) {
9579 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9580 mode != XDP_MODE_SKB);
9581 if (IS_ERR(old_prog)) {
9582 err = PTR_ERR(old_prog);
9588 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9591 if (err && new_prog)
9592 bpf_prog_put(new_prog);
9594 bpf_prog_put(old_prog);
9599 * dev_index_reserve() - allocate an ifindex in a namespace
9600 * @net: the applicable net namespace
9601 * @ifindex: requested ifindex, pass %0 to get one allocated
9603 * Allocate a ifindex for a new device. Caller must either use the ifindex
9604 * to store the device (via list_netdevice()) or call dev_index_release()
9605 * to give the index up.
9607 * Return: a suitable unique value for a new device interface number or -errno.
9609 static int dev_index_reserve(struct net *net, u32 ifindex)
9613 if (ifindex > INT_MAX) {
9614 DEBUG_NET_WARN_ON_ONCE(1);
9619 err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL,
9620 xa_limit_31b, &net->ifindex, GFP_KERNEL);
9622 err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL);
9629 static void dev_index_release(struct net *net, int ifindex)
9631 /* Expect only unused indexes, unlist_netdevice() removes the used */
9632 WARN_ON(xa_erase(&net->dev_by_index, ifindex));
9635 /* Delayed registration/unregisteration */
9636 LIST_HEAD(net_todo_list);
9637 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9639 static void net_set_todo(struct net_device *dev)
9641 list_add_tail(&dev->todo_list, &net_todo_list);
9642 atomic_inc(&dev_net(dev)->dev_unreg_count);
9645 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9646 struct net_device *upper, netdev_features_t features)
9648 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9649 netdev_features_t feature;
9652 for_each_netdev_feature(upper_disables, feature_bit) {
9653 feature = __NETIF_F_BIT(feature_bit);
9654 if (!(upper->wanted_features & feature)
9655 && (features & feature)) {
9656 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9657 &feature, upper->name);
9658 features &= ~feature;
9665 static void netdev_sync_lower_features(struct net_device *upper,
9666 struct net_device *lower, netdev_features_t features)
9668 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9669 netdev_features_t feature;
9672 for_each_netdev_feature(upper_disables, feature_bit) {
9673 feature = __NETIF_F_BIT(feature_bit);
9674 if (!(features & feature) && (lower->features & feature)) {
9675 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9676 &feature, lower->name);
9677 lower->wanted_features &= ~feature;
9678 __netdev_update_features(lower);
9680 if (unlikely(lower->features & feature))
9681 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9682 &feature, lower->name);
9684 netdev_features_change(lower);
9689 static netdev_features_t netdev_fix_features(struct net_device *dev,
9690 netdev_features_t features)
9692 /* Fix illegal checksum combinations */
9693 if ((features & NETIF_F_HW_CSUM) &&
9694 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9695 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9696 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9699 /* TSO requires that SG is present as well. */
9700 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9701 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9702 features &= ~NETIF_F_ALL_TSO;
9705 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9706 !(features & NETIF_F_IP_CSUM)) {
9707 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9708 features &= ~NETIF_F_TSO;
9709 features &= ~NETIF_F_TSO_ECN;
9712 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9713 !(features & NETIF_F_IPV6_CSUM)) {
9714 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9715 features &= ~NETIF_F_TSO6;
9718 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9719 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9720 features &= ~NETIF_F_TSO_MANGLEID;
9722 /* TSO ECN requires that TSO is present as well. */
9723 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9724 features &= ~NETIF_F_TSO_ECN;
9726 /* Software GSO depends on SG. */
9727 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9728 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9729 features &= ~NETIF_F_GSO;
9732 /* GSO partial features require GSO partial be set */
9733 if ((features & dev->gso_partial_features) &&
9734 !(features & NETIF_F_GSO_PARTIAL)) {
9736 "Dropping partially supported GSO features since no GSO partial.\n");
9737 features &= ~dev->gso_partial_features;
9740 if (!(features & NETIF_F_RXCSUM)) {
9741 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9742 * successfully merged by hardware must also have the
9743 * checksum verified by hardware. If the user does not
9744 * want to enable RXCSUM, logically, we should disable GRO_HW.
9746 if (features & NETIF_F_GRO_HW) {
9747 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9748 features &= ~NETIF_F_GRO_HW;
9752 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9753 if (features & NETIF_F_RXFCS) {
9754 if (features & NETIF_F_LRO) {
9755 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9756 features &= ~NETIF_F_LRO;
9759 if (features & NETIF_F_GRO_HW) {
9760 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9761 features &= ~NETIF_F_GRO_HW;
9765 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
9766 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
9767 features &= ~NETIF_F_LRO;
9770 if (features & NETIF_F_HW_TLS_TX) {
9771 bool ip_csum = (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) ==
9772 (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
9773 bool hw_csum = features & NETIF_F_HW_CSUM;
9775 if (!ip_csum && !hw_csum) {
9776 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
9777 features &= ~NETIF_F_HW_TLS_TX;
9781 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
9782 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
9783 features &= ~NETIF_F_HW_TLS_RX;
9789 int __netdev_update_features(struct net_device *dev)
9791 struct net_device *upper, *lower;
9792 netdev_features_t features;
9793 struct list_head *iter;
9798 features = netdev_get_wanted_features(dev);
9800 if (dev->netdev_ops->ndo_fix_features)
9801 features = dev->netdev_ops->ndo_fix_features(dev, features);
9803 /* driver might be less strict about feature dependencies */
9804 features = netdev_fix_features(dev, features);
9806 /* some features can't be enabled if they're off on an upper device */
9807 netdev_for_each_upper_dev_rcu(dev, upper, iter)
9808 features = netdev_sync_upper_features(dev, upper, features);
9810 if (dev->features == features)
9813 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9814 &dev->features, &features);
9816 if (dev->netdev_ops->ndo_set_features)
9817 err = dev->netdev_ops->ndo_set_features(dev, features);
9821 if (unlikely(err < 0)) {
9823 "set_features() failed (%d); wanted %pNF, left %pNF\n",
9824 err, &features, &dev->features);
9825 /* return non-0 since some features might have changed and
9826 * it's better to fire a spurious notification than miss it
9832 /* some features must be disabled on lower devices when disabled
9833 * on an upper device (think: bonding master or bridge)
9835 netdev_for_each_lower_dev(dev, lower, iter)
9836 netdev_sync_lower_features(dev, lower, features);
9839 netdev_features_t diff = features ^ dev->features;
9841 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9842 /* udp_tunnel_{get,drop}_rx_info both need
9843 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9844 * device, or they won't do anything.
9845 * Thus we need to update dev->features
9846 * *before* calling udp_tunnel_get_rx_info,
9847 * but *after* calling udp_tunnel_drop_rx_info.
9849 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9850 dev->features = features;
9851 udp_tunnel_get_rx_info(dev);
9853 udp_tunnel_drop_rx_info(dev);
9857 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9858 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9859 dev->features = features;
9860 err |= vlan_get_rx_ctag_filter_info(dev);
9862 vlan_drop_rx_ctag_filter_info(dev);
9866 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9867 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9868 dev->features = features;
9869 err |= vlan_get_rx_stag_filter_info(dev);
9871 vlan_drop_rx_stag_filter_info(dev);
9875 dev->features = features;
9878 return err < 0 ? 0 : 1;
9882 * netdev_update_features - recalculate device features
9883 * @dev: the device to check
9885 * Recalculate dev->features set and send notifications if it
9886 * has changed. Should be called after driver or hardware dependent
9887 * conditions might have changed that influence the features.
9889 void netdev_update_features(struct net_device *dev)
9891 if (__netdev_update_features(dev))
9892 netdev_features_change(dev);
9894 EXPORT_SYMBOL(netdev_update_features);
9897 * netdev_change_features - recalculate device features
9898 * @dev: the device to check
9900 * Recalculate dev->features set and send notifications even
9901 * if they have not changed. Should be called instead of
9902 * netdev_update_features() if also dev->vlan_features might
9903 * have changed to allow the changes to be propagated to stacked
9906 void netdev_change_features(struct net_device *dev)
9908 __netdev_update_features(dev);
9909 netdev_features_change(dev);
9911 EXPORT_SYMBOL(netdev_change_features);
9914 * netif_stacked_transfer_operstate - transfer operstate
9915 * @rootdev: the root or lower level device to transfer state from
9916 * @dev: the device to transfer operstate to
9918 * Transfer operational state from root to device. This is normally
9919 * called when a stacking relationship exists between the root
9920 * device and the device(a leaf device).
9922 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9923 struct net_device *dev)
9925 if (rootdev->operstate == IF_OPER_DORMANT)
9926 netif_dormant_on(dev);
9928 netif_dormant_off(dev);
9930 if (rootdev->operstate == IF_OPER_TESTING)
9931 netif_testing_on(dev);
9933 netif_testing_off(dev);
9935 if (netif_carrier_ok(rootdev))
9936 netif_carrier_on(dev);
9938 netif_carrier_off(dev);
9940 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9942 static int netif_alloc_rx_queues(struct net_device *dev)
9944 unsigned int i, count = dev->num_rx_queues;
9945 struct netdev_rx_queue *rx;
9946 size_t sz = count * sizeof(*rx);
9951 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9957 for (i = 0; i < count; i++) {
9960 /* XDP RX-queue setup */
9961 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
9968 /* Rollback successful reg's and free other resources */
9970 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9976 static void netif_free_rx_queues(struct net_device *dev)
9978 unsigned int i, count = dev->num_rx_queues;
9980 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9984 for (i = 0; i < count; i++)
9985 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9990 static void netdev_init_one_queue(struct net_device *dev,
9991 struct netdev_queue *queue, void *_unused)
9993 /* Initialize queue lock */
9994 spin_lock_init(&queue->_xmit_lock);
9995 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
9996 queue->xmit_lock_owner = -1;
9997 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
10000 dql_init(&queue->dql, HZ);
10004 static void netif_free_tx_queues(struct net_device *dev)
10009 static int netif_alloc_netdev_queues(struct net_device *dev)
10011 unsigned int count = dev->num_tx_queues;
10012 struct netdev_queue *tx;
10013 size_t sz = count * sizeof(*tx);
10015 if (count < 1 || count > 0xffff)
10018 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10024 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
10025 spin_lock_init(&dev->tx_global_lock);
10030 void netif_tx_stop_all_queues(struct net_device *dev)
10034 for (i = 0; i < dev->num_tx_queues; i++) {
10035 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
10037 netif_tx_stop_queue(txq);
10040 EXPORT_SYMBOL(netif_tx_stop_all_queues);
10043 * register_netdevice() - register a network device
10044 * @dev: device to register
10046 * Take a prepared network device structure and make it externally accessible.
10047 * A %NETDEV_REGISTER message is sent to the netdev notifier chain.
10048 * Callers must hold the rtnl lock - you may want register_netdev()
10051 int register_netdevice(struct net_device *dev)
10054 struct net *net = dev_net(dev);
10056 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
10057 NETDEV_FEATURE_COUNT);
10058 BUG_ON(dev_boot_phase);
10063 /* When net_device's are persistent, this will be fatal. */
10064 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
10067 ret = ethtool_check_ops(dev->ethtool_ops);
10071 spin_lock_init(&dev->addr_list_lock);
10072 netdev_set_addr_lockdep_class(dev);
10074 ret = dev_get_valid_name(net, dev, dev->name);
10079 dev->name_node = netdev_name_node_head_alloc(dev);
10080 if (!dev->name_node)
10083 /* Init, if this function is available */
10084 if (dev->netdev_ops->ndo_init) {
10085 ret = dev->netdev_ops->ndo_init(dev);
10089 goto err_free_name;
10093 if (((dev->hw_features | dev->features) &
10094 NETIF_F_HW_VLAN_CTAG_FILTER) &&
10095 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
10096 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
10097 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
10102 ret = dev_index_reserve(net, dev->ifindex);
10105 dev->ifindex = ret;
10107 /* Transfer changeable features to wanted_features and enable
10108 * software offloads (GSO and GRO).
10110 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
10111 dev->features |= NETIF_F_SOFT_FEATURES;
10113 if (dev->udp_tunnel_nic_info) {
10114 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10115 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10118 dev->wanted_features = dev->features & dev->hw_features;
10120 if (!(dev->flags & IFF_LOOPBACK))
10121 dev->hw_features |= NETIF_F_NOCACHE_COPY;
10123 /* If IPv4 TCP segmentation offload is supported we should also
10124 * allow the device to enable segmenting the frame with the option
10125 * of ignoring a static IP ID value. This doesn't enable the
10126 * feature itself but allows the user to enable it later.
10128 if (dev->hw_features & NETIF_F_TSO)
10129 dev->hw_features |= NETIF_F_TSO_MANGLEID;
10130 if (dev->vlan_features & NETIF_F_TSO)
10131 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
10132 if (dev->mpls_features & NETIF_F_TSO)
10133 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
10134 if (dev->hw_enc_features & NETIF_F_TSO)
10135 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
10137 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
10139 dev->vlan_features |= NETIF_F_HIGHDMA;
10141 /* Make NETIF_F_SG inheritable to tunnel devices.
10143 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
10145 /* Make NETIF_F_SG inheritable to MPLS.
10147 dev->mpls_features |= NETIF_F_SG;
10149 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
10150 ret = notifier_to_errno(ret);
10152 goto err_ifindex_release;
10154 ret = netdev_register_kobject(dev);
10155 write_lock(&dev_base_lock);
10156 dev->reg_state = ret ? NETREG_UNREGISTERED : NETREG_REGISTERED;
10157 write_unlock(&dev_base_lock);
10159 goto err_uninit_notify;
10161 __netdev_update_features(dev);
10164 * Default initial state at registry is that the
10165 * device is present.
10168 set_bit(__LINK_STATE_PRESENT, &dev->state);
10170 linkwatch_init_dev(dev);
10172 dev_init_scheduler(dev);
10174 netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL);
10175 list_netdevice(dev);
10177 add_device_randomness(dev->dev_addr, dev->addr_len);
10179 /* If the device has permanent device address, driver should
10180 * set dev_addr and also addr_assign_type should be set to
10181 * NET_ADDR_PERM (default value).
10183 if (dev->addr_assign_type == NET_ADDR_PERM)
10184 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
10186 /* Notify protocols, that a new device appeared. */
10187 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
10188 ret = notifier_to_errno(ret);
10190 /* Expect explicit free_netdev() on failure */
10191 dev->needs_free_netdev = false;
10192 unregister_netdevice_queue(dev, NULL);
10196 * Prevent userspace races by waiting until the network
10197 * device is fully setup before sending notifications.
10199 if (!dev->rtnl_link_ops ||
10200 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10201 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
10207 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
10208 err_ifindex_release:
10209 dev_index_release(net, dev->ifindex);
10211 if (dev->netdev_ops->ndo_uninit)
10212 dev->netdev_ops->ndo_uninit(dev);
10213 if (dev->priv_destructor)
10214 dev->priv_destructor(dev);
10216 netdev_name_node_free(dev->name_node);
10219 EXPORT_SYMBOL(register_netdevice);
10222 * init_dummy_netdev - init a dummy network device for NAPI
10223 * @dev: device to init
10225 * This takes a network device structure and initialize the minimum
10226 * amount of fields so it can be used to schedule NAPI polls without
10227 * registering a full blown interface. This is to be used by drivers
10228 * that need to tie several hardware interfaces to a single NAPI
10229 * poll scheduler due to HW limitations.
10231 int init_dummy_netdev(struct net_device *dev)
10233 /* Clear everything. Note we don't initialize spinlocks
10234 * are they aren't supposed to be taken by any of the
10235 * NAPI code and this dummy netdev is supposed to be
10236 * only ever used for NAPI polls
10238 memset(dev, 0, sizeof(struct net_device));
10240 /* make sure we BUG if trying to hit standard
10241 * register/unregister code path
10243 dev->reg_state = NETREG_DUMMY;
10245 /* NAPI wants this */
10246 INIT_LIST_HEAD(&dev->napi_list);
10248 /* a dummy interface is started by default */
10249 set_bit(__LINK_STATE_PRESENT, &dev->state);
10250 set_bit(__LINK_STATE_START, &dev->state);
10252 /* napi_busy_loop stats accounting wants this */
10253 dev_net_set(dev, &init_net);
10255 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10256 * because users of this 'device' dont need to change
10262 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10266 * register_netdev - register a network device
10267 * @dev: device to register
10269 * Take a completed network device structure and add it to the kernel
10270 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10271 * chain. 0 is returned on success. A negative errno code is returned
10272 * on a failure to set up the device, or if the name is a duplicate.
10274 * This is a wrapper around register_netdevice that takes the rtnl semaphore
10275 * and expands the device name if you passed a format string to
10278 int register_netdev(struct net_device *dev)
10282 if (rtnl_lock_killable())
10284 err = register_netdevice(dev);
10288 EXPORT_SYMBOL(register_netdev);
10290 int netdev_refcnt_read(const struct net_device *dev)
10292 #ifdef CONFIG_PCPU_DEV_REFCNT
10295 for_each_possible_cpu(i)
10296 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10299 return refcount_read(&dev->dev_refcnt);
10302 EXPORT_SYMBOL(netdev_refcnt_read);
10304 int netdev_unregister_timeout_secs __read_mostly = 10;
10306 #define WAIT_REFS_MIN_MSECS 1
10307 #define WAIT_REFS_MAX_MSECS 250
10309 * netdev_wait_allrefs_any - wait until all references are gone.
10310 * @list: list of net_devices to wait on
10312 * This is called when unregistering network devices.
10314 * Any protocol or device that holds a reference should register
10315 * for netdevice notification, and cleanup and put back the
10316 * reference if they receive an UNREGISTER event.
10317 * We can get stuck here if buggy protocols don't correctly
10320 static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
10322 unsigned long rebroadcast_time, warning_time;
10323 struct net_device *dev;
10326 rebroadcast_time = warning_time = jiffies;
10328 list_for_each_entry(dev, list, todo_list)
10329 if (netdev_refcnt_read(dev) == 1)
10333 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10336 /* Rebroadcast unregister notification */
10337 list_for_each_entry(dev, list, todo_list)
10338 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10344 list_for_each_entry(dev, list, todo_list)
10345 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10347 /* We must not have linkwatch events
10348 * pending on unregister. If this
10349 * happens, we simply run the queue
10350 * unscheduled, resulting in a noop
10353 linkwatch_run_queue();
10359 rebroadcast_time = jiffies;
10364 wait = WAIT_REFS_MIN_MSECS;
10367 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10370 list_for_each_entry(dev, list, todo_list)
10371 if (netdev_refcnt_read(dev) == 1)
10374 if (time_after(jiffies, warning_time +
10375 READ_ONCE(netdev_unregister_timeout_secs) * HZ)) {
10376 list_for_each_entry(dev, list, todo_list) {
10377 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10378 dev->name, netdev_refcnt_read(dev));
10379 ref_tracker_dir_print(&dev->refcnt_tracker, 10);
10382 warning_time = jiffies;
10387 /* The sequence is:
10391 * register_netdevice(x1);
10392 * register_netdevice(x2);
10394 * unregister_netdevice(y1);
10395 * unregister_netdevice(y2);
10401 * We are invoked by rtnl_unlock().
10402 * This allows us to deal with problems:
10403 * 1) We can delete sysfs objects which invoke hotplug
10404 * without deadlocking with linkwatch via keventd.
10405 * 2) Since we run with the RTNL semaphore not held, we can sleep
10406 * safely in order to wait for the netdev refcnt to drop to zero.
10408 * We must not return until all unregister events added during
10409 * the interval the lock was held have been completed.
10411 void netdev_run_todo(void)
10413 struct net_device *dev, *tmp;
10414 struct list_head list;
10415 #ifdef CONFIG_LOCKDEP
10416 struct list_head unlink_list;
10418 list_replace_init(&net_unlink_list, &unlink_list);
10420 while (!list_empty(&unlink_list)) {
10421 struct net_device *dev = list_first_entry(&unlink_list,
10424 list_del_init(&dev->unlink_list);
10425 dev->nested_level = dev->lower_level - 1;
10429 /* Snapshot list, allow later requests */
10430 list_replace_init(&net_todo_list, &list);
10434 /* Wait for rcu callbacks to finish before next phase */
10435 if (!list_empty(&list))
10438 list_for_each_entry_safe(dev, tmp, &list, todo_list) {
10439 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10440 netdev_WARN(dev, "run_todo but not unregistering\n");
10441 list_del(&dev->todo_list);
10445 write_lock(&dev_base_lock);
10446 dev->reg_state = NETREG_UNREGISTERED;
10447 write_unlock(&dev_base_lock);
10448 linkwatch_forget_dev(dev);
10451 while (!list_empty(&list)) {
10452 dev = netdev_wait_allrefs_any(&list);
10453 list_del(&dev->todo_list);
10456 BUG_ON(netdev_refcnt_read(dev) != 1);
10457 BUG_ON(!list_empty(&dev->ptype_all));
10458 BUG_ON(!list_empty(&dev->ptype_specific));
10459 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10460 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10462 if (dev->priv_destructor)
10463 dev->priv_destructor(dev);
10464 if (dev->needs_free_netdev)
10467 if (atomic_dec_and_test(&dev_net(dev)->dev_unreg_count))
10468 wake_up(&netdev_unregistering_wq);
10470 /* Free network device */
10471 kobject_put(&dev->dev.kobj);
10475 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10476 * all the same fields in the same order as net_device_stats, with only
10477 * the type differing, but rtnl_link_stats64 may have additional fields
10478 * at the end for newer counters.
10480 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10481 const struct net_device_stats *netdev_stats)
10483 size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t);
10484 const atomic_long_t *src = (atomic_long_t *)netdev_stats;
10485 u64 *dst = (u64 *)stats64;
10487 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10488 for (i = 0; i < n; i++)
10489 dst[i] = (unsigned long)atomic_long_read(&src[i]);
10490 /* zero out counters that only exist in rtnl_link_stats64 */
10491 memset((char *)stats64 + n * sizeof(u64), 0,
10492 sizeof(*stats64) - n * sizeof(u64));
10494 EXPORT_SYMBOL(netdev_stats_to_stats64);
10496 struct net_device_core_stats __percpu *netdev_core_stats_alloc(struct net_device *dev)
10498 struct net_device_core_stats __percpu *p;
10500 p = alloc_percpu_gfp(struct net_device_core_stats,
10501 GFP_ATOMIC | __GFP_NOWARN);
10503 if (p && cmpxchg(&dev->core_stats, NULL, p))
10506 /* This READ_ONCE() pairs with the cmpxchg() above */
10507 return READ_ONCE(dev->core_stats);
10509 EXPORT_SYMBOL(netdev_core_stats_alloc);
10512 * dev_get_stats - get network device statistics
10513 * @dev: device to get statistics from
10514 * @storage: place to store stats
10516 * Get network statistics from device. Return @storage.
10517 * The device driver may provide its own method by setting
10518 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10519 * otherwise the internal statistics structure is used.
10521 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10522 struct rtnl_link_stats64 *storage)
10524 const struct net_device_ops *ops = dev->netdev_ops;
10525 const struct net_device_core_stats __percpu *p;
10527 if (ops->ndo_get_stats64) {
10528 memset(storage, 0, sizeof(*storage));
10529 ops->ndo_get_stats64(dev, storage);
10530 } else if (ops->ndo_get_stats) {
10531 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10533 netdev_stats_to_stats64(storage, &dev->stats);
10536 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10537 p = READ_ONCE(dev->core_stats);
10539 const struct net_device_core_stats *core_stats;
10542 for_each_possible_cpu(i) {
10543 core_stats = per_cpu_ptr(p, i);
10544 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
10545 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
10546 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
10547 storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped);
10552 EXPORT_SYMBOL(dev_get_stats);
10555 * dev_fetch_sw_netstats - get per-cpu network device statistics
10556 * @s: place to store stats
10557 * @netstats: per-cpu network stats to read from
10559 * Read per-cpu network statistics and populate the related fields in @s.
10561 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10562 const struct pcpu_sw_netstats __percpu *netstats)
10566 for_each_possible_cpu(cpu) {
10567 u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
10568 const struct pcpu_sw_netstats *stats;
10569 unsigned int start;
10571 stats = per_cpu_ptr(netstats, cpu);
10573 start = u64_stats_fetch_begin(&stats->syncp);
10574 rx_packets = u64_stats_read(&stats->rx_packets);
10575 rx_bytes = u64_stats_read(&stats->rx_bytes);
10576 tx_packets = u64_stats_read(&stats->tx_packets);
10577 tx_bytes = u64_stats_read(&stats->tx_bytes);
10578 } while (u64_stats_fetch_retry(&stats->syncp, start));
10580 s->rx_packets += rx_packets;
10581 s->rx_bytes += rx_bytes;
10582 s->tx_packets += tx_packets;
10583 s->tx_bytes += tx_bytes;
10586 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10589 * dev_get_tstats64 - ndo_get_stats64 implementation
10590 * @dev: device to get statistics from
10591 * @s: place to store stats
10593 * Populate @s from dev->stats and dev->tstats. Can be used as
10594 * ndo_get_stats64() callback.
10596 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
10598 netdev_stats_to_stats64(s, &dev->stats);
10599 dev_fetch_sw_netstats(s, dev->tstats);
10601 EXPORT_SYMBOL_GPL(dev_get_tstats64);
10603 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10605 struct netdev_queue *queue = dev_ingress_queue(dev);
10607 #ifdef CONFIG_NET_CLS_ACT
10610 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10613 netdev_init_one_queue(dev, queue, NULL);
10614 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10615 RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc);
10616 rcu_assign_pointer(dev->ingress_queue, queue);
10621 static const struct ethtool_ops default_ethtool_ops;
10623 void netdev_set_default_ethtool_ops(struct net_device *dev,
10624 const struct ethtool_ops *ops)
10626 if (dev->ethtool_ops == &default_ethtool_ops)
10627 dev->ethtool_ops = ops;
10629 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10632 * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default
10633 * @dev: netdev to enable the IRQ coalescing on
10635 * Sets a conservative default for SW IRQ coalescing. Users can use
10636 * sysfs attributes to override the default values.
10638 void netdev_sw_irq_coalesce_default_on(struct net_device *dev)
10640 WARN_ON(dev->reg_state == NETREG_REGISTERED);
10642 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
10643 dev->gro_flush_timeout = 20000;
10644 dev->napi_defer_hard_irqs = 1;
10647 EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on);
10649 void netdev_freemem(struct net_device *dev)
10651 char *addr = (char *)dev - dev->padded;
10657 * alloc_netdev_mqs - allocate network device
10658 * @sizeof_priv: size of private data to allocate space for
10659 * @name: device name format string
10660 * @name_assign_type: origin of device name
10661 * @setup: callback to initialize device
10662 * @txqs: the number of TX subqueues to allocate
10663 * @rxqs: the number of RX subqueues to allocate
10665 * Allocates a struct net_device with private data area for driver use
10666 * and performs basic initialization. Also allocates subqueue structs
10667 * for each queue on the device.
10669 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10670 unsigned char name_assign_type,
10671 void (*setup)(struct net_device *),
10672 unsigned int txqs, unsigned int rxqs)
10674 struct net_device *dev;
10675 unsigned int alloc_size;
10676 struct net_device *p;
10678 BUG_ON(strlen(name) >= sizeof(dev->name));
10681 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10686 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10690 alloc_size = sizeof(struct net_device);
10692 /* ensure 32-byte alignment of private area */
10693 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10694 alloc_size += sizeof_priv;
10696 /* ensure 32-byte alignment of whole construct */
10697 alloc_size += NETDEV_ALIGN - 1;
10699 p = kvzalloc(alloc_size, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10703 dev = PTR_ALIGN(p, NETDEV_ALIGN);
10704 dev->padded = (char *)dev - (char *)p;
10706 ref_tracker_dir_init(&dev->refcnt_tracker, 128, name);
10707 #ifdef CONFIG_PCPU_DEV_REFCNT
10708 dev->pcpu_refcnt = alloc_percpu(int);
10709 if (!dev->pcpu_refcnt)
10713 refcount_set(&dev->dev_refcnt, 1);
10716 if (dev_addr_init(dev))
10722 dev_net_set(dev, &init_net);
10724 dev->gso_max_size = GSO_LEGACY_MAX_SIZE;
10725 dev->xdp_zc_max_segs = 1;
10726 dev->gso_max_segs = GSO_MAX_SEGS;
10727 dev->gro_max_size = GRO_LEGACY_MAX_SIZE;
10728 dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE;
10729 dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE;
10730 dev->tso_max_size = TSO_LEGACY_MAX_SIZE;
10731 dev->tso_max_segs = TSO_MAX_SEGS;
10732 dev->upper_level = 1;
10733 dev->lower_level = 1;
10734 #ifdef CONFIG_LOCKDEP
10735 dev->nested_level = 0;
10736 INIT_LIST_HEAD(&dev->unlink_list);
10739 INIT_LIST_HEAD(&dev->napi_list);
10740 INIT_LIST_HEAD(&dev->unreg_list);
10741 INIT_LIST_HEAD(&dev->close_list);
10742 INIT_LIST_HEAD(&dev->link_watch_list);
10743 INIT_LIST_HEAD(&dev->adj_list.upper);
10744 INIT_LIST_HEAD(&dev->adj_list.lower);
10745 INIT_LIST_HEAD(&dev->ptype_all);
10746 INIT_LIST_HEAD(&dev->ptype_specific);
10747 INIT_LIST_HEAD(&dev->net_notifier_list);
10748 #ifdef CONFIG_NET_SCHED
10749 hash_init(dev->qdisc_hash);
10751 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10754 if (!dev->tx_queue_len) {
10755 dev->priv_flags |= IFF_NO_QUEUE;
10756 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10759 dev->num_tx_queues = txqs;
10760 dev->real_num_tx_queues = txqs;
10761 if (netif_alloc_netdev_queues(dev))
10764 dev->num_rx_queues = rxqs;
10765 dev->real_num_rx_queues = rxqs;
10766 if (netif_alloc_rx_queues(dev))
10769 strcpy(dev->name, name);
10770 dev->name_assign_type = name_assign_type;
10771 dev->group = INIT_NETDEV_GROUP;
10772 if (!dev->ethtool_ops)
10773 dev->ethtool_ops = &default_ethtool_ops;
10775 nf_hook_netdev_init(dev);
10784 #ifdef CONFIG_PCPU_DEV_REFCNT
10785 free_percpu(dev->pcpu_refcnt);
10788 netdev_freemem(dev);
10791 EXPORT_SYMBOL(alloc_netdev_mqs);
10794 * free_netdev - free network device
10797 * This function does the last stage of destroying an allocated device
10798 * interface. The reference to the device object is released. If this
10799 * is the last reference then it will be freed.Must be called in process
10802 void free_netdev(struct net_device *dev)
10804 struct napi_struct *p, *n;
10808 /* When called immediately after register_netdevice() failed the unwind
10809 * handling may still be dismantling the device. Handle that case by
10810 * deferring the free.
10812 if (dev->reg_state == NETREG_UNREGISTERING) {
10814 dev->needs_free_netdev = true;
10818 netif_free_tx_queues(dev);
10819 netif_free_rx_queues(dev);
10821 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10823 /* Flush device addresses */
10824 dev_addr_flush(dev);
10826 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10829 ref_tracker_dir_exit(&dev->refcnt_tracker);
10830 #ifdef CONFIG_PCPU_DEV_REFCNT
10831 free_percpu(dev->pcpu_refcnt);
10832 dev->pcpu_refcnt = NULL;
10834 free_percpu(dev->core_stats);
10835 dev->core_stats = NULL;
10836 free_percpu(dev->xdp_bulkq);
10837 dev->xdp_bulkq = NULL;
10839 /* Compatibility with error handling in drivers */
10840 if (dev->reg_state == NETREG_UNINITIALIZED) {
10841 netdev_freemem(dev);
10845 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
10846 dev->reg_state = NETREG_RELEASED;
10848 /* will free via device release */
10849 put_device(&dev->dev);
10851 EXPORT_SYMBOL(free_netdev);
10854 * synchronize_net - Synchronize with packet receive processing
10856 * Wait for packets currently being received to be done.
10857 * Does not block later packets from starting.
10859 void synchronize_net(void)
10862 if (rtnl_is_locked())
10863 synchronize_rcu_expedited();
10867 EXPORT_SYMBOL(synchronize_net);
10870 * unregister_netdevice_queue - remove device from the kernel
10874 * This function shuts down a device interface and removes it
10875 * from the kernel tables.
10876 * If head not NULL, device is queued to be unregistered later.
10878 * Callers must hold the rtnl semaphore. You may want
10879 * unregister_netdev() instead of this.
10882 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
10887 list_move_tail(&dev->unreg_list, head);
10891 list_add(&dev->unreg_list, &single);
10892 unregister_netdevice_many(&single);
10895 EXPORT_SYMBOL(unregister_netdevice_queue);
10897 void unregister_netdevice_many_notify(struct list_head *head,
10898 u32 portid, const struct nlmsghdr *nlh)
10900 struct net_device *dev, *tmp;
10901 LIST_HEAD(close_head);
10903 BUG_ON(dev_boot_phase);
10906 if (list_empty(head))
10909 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
10910 /* Some devices call without registering
10911 * for initialization unwind. Remove those
10912 * devices and proceed with the remaining.
10914 if (dev->reg_state == NETREG_UNINITIALIZED) {
10915 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
10919 list_del(&dev->unreg_list);
10922 dev->dismantle = true;
10923 BUG_ON(dev->reg_state != NETREG_REGISTERED);
10926 /* If device is running, close it first. */
10927 list_for_each_entry(dev, head, unreg_list)
10928 list_add_tail(&dev->close_list, &close_head);
10929 dev_close_many(&close_head, true);
10931 list_for_each_entry(dev, head, unreg_list) {
10932 /* And unlink it from device chain. */
10933 write_lock(&dev_base_lock);
10934 unlist_netdevice(dev, false);
10935 dev->reg_state = NETREG_UNREGISTERING;
10936 write_unlock(&dev_base_lock);
10938 flush_all_backlogs();
10942 list_for_each_entry(dev, head, unreg_list) {
10943 struct sk_buff *skb = NULL;
10945 /* Shutdown queueing discipline. */
10947 dev_tcx_uninstall(dev);
10948 dev_xdp_uninstall(dev);
10949 bpf_dev_bound_netdev_unregister(dev);
10951 netdev_offload_xstats_disable_all(dev);
10953 /* Notify protocols, that we are about to destroy
10954 * this device. They should clean all the things.
10956 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10958 if (!dev->rtnl_link_ops ||
10959 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10960 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
10961 GFP_KERNEL, NULL, 0,
10965 * Flush the unicast and multicast chains
10970 netdev_name_node_alt_flush(dev);
10971 netdev_name_node_free(dev->name_node);
10973 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
10975 if (dev->netdev_ops->ndo_uninit)
10976 dev->netdev_ops->ndo_uninit(dev);
10979 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh);
10981 /* Notifier chain MUST detach us all upper devices. */
10982 WARN_ON(netdev_has_any_upper_dev(dev));
10983 WARN_ON(netdev_has_any_lower_dev(dev));
10985 /* Remove entries from kobject tree */
10986 netdev_unregister_kobject(dev);
10988 /* Remove XPS queueing entries */
10989 netif_reset_xps_queues_gt(dev, 0);
10995 list_for_each_entry(dev, head, unreg_list) {
10996 netdev_put(dev, &dev->dev_registered_tracker);
11004 * unregister_netdevice_many - unregister many devices
11005 * @head: list of devices
11007 * Note: As most callers use a stack allocated list_head,
11008 * we force a list_del() to make sure stack wont be corrupted later.
11010 void unregister_netdevice_many(struct list_head *head)
11012 unregister_netdevice_many_notify(head, 0, NULL);
11014 EXPORT_SYMBOL(unregister_netdevice_many);
11017 * unregister_netdev - remove device from the kernel
11020 * This function shuts down a device interface and removes it
11021 * from the kernel tables.
11023 * This is just a wrapper for unregister_netdevice that takes
11024 * the rtnl semaphore. In general you want to use this and not
11025 * unregister_netdevice.
11027 void unregister_netdev(struct net_device *dev)
11030 unregister_netdevice(dev);
11033 EXPORT_SYMBOL(unregister_netdev);
11036 * __dev_change_net_namespace - move device to different nethost namespace
11038 * @net: network namespace
11039 * @pat: If not NULL name pattern to try if the current device name
11040 * is already taken in the destination network namespace.
11041 * @new_ifindex: If not zero, specifies device index in the target
11044 * This function shuts down a device interface and moves it
11045 * to a new network namespace. On success 0 is returned, on
11046 * a failure a netagive errno code is returned.
11048 * Callers must hold the rtnl semaphore.
11051 int __dev_change_net_namespace(struct net_device *dev, struct net *net,
11052 const char *pat, int new_ifindex)
11054 struct net *net_old = dev_net(dev);
11055 char new_name[IFNAMSIZ] = {};
11060 /* Don't allow namespace local devices to be moved. */
11062 if (dev->features & NETIF_F_NETNS_LOCAL)
11065 /* Ensure the device has been registrered */
11066 if (dev->reg_state != NETREG_REGISTERED)
11069 /* Get out if there is nothing todo */
11071 if (net_eq(net_old, net))
11074 /* Pick the destination device name, and ensure
11075 * we can use it in the destination network namespace.
11078 if (netdev_name_in_use(net, dev->name)) {
11079 /* We get here if we can't use the current device name */
11082 err = dev_prep_valid_name(net, dev, pat, new_name);
11087 /* Check that new_ifindex isn't used yet. */
11089 err = dev_index_reserve(net, new_ifindex);
11093 /* If there is an ifindex conflict assign a new one */
11094 err = dev_index_reserve(net, dev->ifindex);
11096 err = dev_index_reserve(net, 0);
11103 * And now a mini version of register_netdevice unregister_netdevice.
11106 /* If device is running close it first. */
11109 /* And unlink it from device chain */
11110 unlist_netdevice(dev, true);
11114 /* Shutdown queueing discipline. */
11117 /* Notify protocols, that we are about to destroy
11118 * this device. They should clean all the things.
11120 * Note that dev->reg_state stays at NETREG_REGISTERED.
11121 * This is wanted because this way 8021q and macvlan know
11122 * the device is just moving and can keep their slaves up.
11124 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11127 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
11129 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
11133 * Flush the unicast and multicast chains
11138 /* Send a netdev-removed uevent to the old namespace */
11139 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
11140 netdev_adjacent_del_links(dev);
11142 /* Move per-net netdevice notifiers that are following the netdevice */
11143 move_netdevice_notifiers_dev_net(dev, net);
11145 /* Actually switch the network namespace */
11146 dev_net_set(dev, net);
11147 dev->ifindex = new_ifindex;
11149 /* Send a netdev-add uevent to the new namespace */
11150 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
11151 netdev_adjacent_add_links(dev);
11153 if (new_name[0]) /* Rename the netdev to prepared name */
11154 strscpy(dev->name, new_name, IFNAMSIZ);
11156 /* Fixup kobjects */
11157 err = device_rename(&dev->dev, dev->name);
11160 /* Adapt owner in case owning user namespace of target network
11161 * namespace is different from the original one.
11163 err = netdev_change_owner(dev, net_old, net);
11166 /* Add the device back in the hashes */
11167 list_netdevice(dev);
11169 /* Notify protocols, that a new device appeared. */
11170 call_netdevice_notifiers(NETDEV_REGISTER, dev);
11173 * Prevent userspace races by waiting until the network
11174 * device is fully setup before sending notifications.
11176 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
11183 EXPORT_SYMBOL_GPL(__dev_change_net_namespace);
11185 static int dev_cpu_dead(unsigned int oldcpu)
11187 struct sk_buff **list_skb;
11188 struct sk_buff *skb;
11190 struct softnet_data *sd, *oldsd, *remsd = NULL;
11192 local_irq_disable();
11193 cpu = smp_processor_id();
11194 sd = &per_cpu(softnet_data, cpu);
11195 oldsd = &per_cpu(softnet_data, oldcpu);
11197 /* Find end of our completion_queue. */
11198 list_skb = &sd->completion_queue;
11200 list_skb = &(*list_skb)->next;
11201 /* Append completion queue from offline CPU. */
11202 *list_skb = oldsd->completion_queue;
11203 oldsd->completion_queue = NULL;
11205 /* Append output queue from offline CPU. */
11206 if (oldsd->output_queue) {
11207 *sd->output_queue_tailp = oldsd->output_queue;
11208 sd->output_queue_tailp = oldsd->output_queue_tailp;
11209 oldsd->output_queue = NULL;
11210 oldsd->output_queue_tailp = &oldsd->output_queue;
11212 /* Append NAPI poll list from offline CPU, with one exception :
11213 * process_backlog() must be called by cpu owning percpu backlog.
11214 * We properly handle process_queue & input_pkt_queue later.
11216 while (!list_empty(&oldsd->poll_list)) {
11217 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
11218 struct napi_struct,
11221 list_del_init(&napi->poll_list);
11222 if (napi->poll == process_backlog)
11225 ____napi_schedule(sd, napi);
11228 raise_softirq_irqoff(NET_TX_SOFTIRQ);
11229 local_irq_enable();
11232 remsd = oldsd->rps_ipi_list;
11233 oldsd->rps_ipi_list = NULL;
11235 /* send out pending IPI's on offline CPU */
11236 net_rps_send_ipi(remsd);
11238 /* Process offline CPU's input_pkt_queue */
11239 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
11241 input_queue_head_incr(oldsd);
11243 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
11245 input_queue_head_incr(oldsd);
11252 * netdev_increment_features - increment feature set by one
11253 * @all: current feature set
11254 * @one: new feature set
11255 * @mask: mask feature set
11257 * Computes a new feature set after adding a device with feature set
11258 * @one to the master device with current feature set @all. Will not
11259 * enable anything that is off in @mask. Returns the new feature set.
11261 netdev_features_t netdev_increment_features(netdev_features_t all,
11262 netdev_features_t one, netdev_features_t mask)
11264 if (mask & NETIF_F_HW_CSUM)
11265 mask |= NETIF_F_CSUM_MASK;
11266 mask |= NETIF_F_VLAN_CHALLENGED;
11268 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11269 all &= one | ~NETIF_F_ALL_FOR_ALL;
11271 /* If one device supports hw checksumming, set for all. */
11272 if (all & NETIF_F_HW_CSUM)
11273 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11277 EXPORT_SYMBOL(netdev_increment_features);
11279 static struct hlist_head * __net_init netdev_create_hash(void)
11282 struct hlist_head *hash;
11284 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11286 for (i = 0; i < NETDEV_HASHENTRIES; i++)
11287 INIT_HLIST_HEAD(&hash[i]);
11292 /* Initialize per network namespace state */
11293 static int __net_init netdev_init(struct net *net)
11295 BUILD_BUG_ON(GRO_HASH_BUCKETS >
11296 8 * sizeof_field(struct napi_struct, gro_bitmask));
11298 INIT_LIST_HEAD(&net->dev_base_head);
11300 net->dev_name_head = netdev_create_hash();
11301 if (net->dev_name_head == NULL)
11304 net->dev_index_head = netdev_create_hash();
11305 if (net->dev_index_head == NULL)
11308 xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1);
11310 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11315 kfree(net->dev_name_head);
11321 * netdev_drivername - network driver for the device
11322 * @dev: network device
11324 * Determine network driver for device.
11326 const char *netdev_drivername(const struct net_device *dev)
11328 const struct device_driver *driver;
11329 const struct device *parent;
11330 const char *empty = "";
11332 parent = dev->dev.parent;
11336 driver = parent->driver;
11337 if (driver && driver->name)
11338 return driver->name;
11342 static void __netdev_printk(const char *level, const struct net_device *dev,
11343 struct va_format *vaf)
11345 if (dev && dev->dev.parent) {
11346 dev_printk_emit(level[1] - '0',
11349 dev_driver_string(dev->dev.parent),
11350 dev_name(dev->dev.parent),
11351 netdev_name(dev), netdev_reg_state(dev),
11354 printk("%s%s%s: %pV",
11355 level, netdev_name(dev), netdev_reg_state(dev), vaf);
11357 printk("%s(NULL net_device): %pV", level, vaf);
11361 void netdev_printk(const char *level, const struct net_device *dev,
11362 const char *format, ...)
11364 struct va_format vaf;
11367 va_start(args, format);
11372 __netdev_printk(level, dev, &vaf);
11376 EXPORT_SYMBOL(netdev_printk);
11378 #define define_netdev_printk_level(func, level) \
11379 void func(const struct net_device *dev, const char *fmt, ...) \
11381 struct va_format vaf; \
11384 va_start(args, fmt); \
11389 __netdev_printk(level, dev, &vaf); \
11393 EXPORT_SYMBOL(func);
11395 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11396 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11397 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11398 define_netdev_printk_level(netdev_err, KERN_ERR);
11399 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11400 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11401 define_netdev_printk_level(netdev_info, KERN_INFO);
11403 static void __net_exit netdev_exit(struct net *net)
11405 kfree(net->dev_name_head);
11406 kfree(net->dev_index_head);
11407 xa_destroy(&net->dev_by_index);
11408 if (net != &init_net)
11409 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11412 static struct pernet_operations __net_initdata netdev_net_ops = {
11413 .init = netdev_init,
11414 .exit = netdev_exit,
11417 static void __net_exit default_device_exit_net(struct net *net)
11419 struct net_device *dev, *aux;
11421 * Push all migratable network devices back to the
11422 * initial network namespace
11425 for_each_netdev_safe(net, dev, aux) {
11427 char fb_name[IFNAMSIZ];
11429 /* Ignore unmoveable devices (i.e. loopback) */
11430 if (dev->features & NETIF_F_NETNS_LOCAL)
11433 /* Leave virtual devices for the generic cleanup */
11434 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11437 /* Push remaining network devices to init_net */
11438 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11439 if (netdev_name_in_use(&init_net, fb_name))
11440 snprintf(fb_name, IFNAMSIZ, "dev%%d");
11441 err = dev_change_net_namespace(dev, &init_net, fb_name);
11443 pr_emerg("%s: failed to move %s to init_net: %d\n",
11444 __func__, dev->name, err);
11450 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11452 /* At exit all network devices most be removed from a network
11453 * namespace. Do this in the reverse order of registration.
11454 * Do this across as many network namespaces as possible to
11455 * improve batching efficiency.
11457 struct net_device *dev;
11459 LIST_HEAD(dev_kill_list);
11462 list_for_each_entry(net, net_list, exit_list) {
11463 default_device_exit_net(net);
11467 list_for_each_entry(net, net_list, exit_list) {
11468 for_each_netdev_reverse(net, dev) {
11469 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11470 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11472 unregister_netdevice_queue(dev, &dev_kill_list);
11475 unregister_netdevice_many(&dev_kill_list);
11479 static struct pernet_operations __net_initdata default_device_ops = {
11480 .exit_batch = default_device_exit_batch,
11484 * Initialize the DEV module. At boot time this walks the device list and
11485 * unhooks any devices that fail to initialise (normally hardware not
11486 * present) and leaves us with a valid list of present and active devices.
11491 * This is called single threaded during boot, so no need
11492 * to take the rtnl semaphore.
11494 static int __init net_dev_init(void)
11496 int i, rc = -ENOMEM;
11498 BUG_ON(!dev_boot_phase);
11500 if (dev_proc_init())
11503 if (netdev_kobject_init())
11506 INIT_LIST_HEAD(&ptype_all);
11507 for (i = 0; i < PTYPE_HASH_SIZE; i++)
11508 INIT_LIST_HEAD(&ptype_base[i]);
11510 if (register_pernet_subsys(&netdev_net_ops))
11514 * Initialise the packet receive queues.
11517 for_each_possible_cpu(i) {
11518 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
11519 struct softnet_data *sd = &per_cpu(softnet_data, i);
11521 INIT_WORK(flush, flush_backlog);
11523 skb_queue_head_init(&sd->input_pkt_queue);
11524 skb_queue_head_init(&sd->process_queue);
11525 #ifdef CONFIG_XFRM_OFFLOAD
11526 skb_queue_head_init(&sd->xfrm_backlog);
11528 INIT_LIST_HEAD(&sd->poll_list);
11529 sd->output_queue_tailp = &sd->output_queue;
11531 INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
11534 INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd);
11535 spin_lock_init(&sd->defer_lock);
11537 init_gro_hash(&sd->backlog);
11538 sd->backlog.poll = process_backlog;
11539 sd->backlog.weight = weight_p;
11542 dev_boot_phase = 0;
11544 /* The loopback device is special if any other network devices
11545 * is present in a network namespace the loopback device must
11546 * be present. Since we now dynamically allocate and free the
11547 * loopback device ensure this invariant is maintained by
11548 * keeping the loopback device as the first device on the
11549 * list of network devices. Ensuring the loopback devices
11550 * is the first device that appears and the last network device
11553 if (register_pernet_device(&loopback_net_ops))
11556 if (register_pernet_device(&default_device_ops))
11559 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11560 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11562 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11563 NULL, dev_cpu_dead);
11570 subsys_initcall(net_dev_init);