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/bitops.h>
73 #include <linux/capability.h>
74 #include <linux/cpu.h>
75 #include <linux/types.h>
76 #include <linux/kernel.h>
77 #include <linux/hash.h>
78 #include <linux/slab.h>
79 #include <linux/sched.h>
80 #include <linux/sched/mm.h>
81 #include <linux/mutex.h>
82 #include <linux/rwsem.h>
83 #include <linux/string.h>
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>
157 #include "net-sysfs.h"
159 static DEFINE_SPINLOCK(ptype_lock);
160 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
161 struct list_head ptype_all __read_mostly; /* Taps */
163 static int netif_rx_internal(struct sk_buff *skb);
164 static int call_netdevice_notifiers_extack(unsigned long val,
165 struct net_device *dev,
166 struct netlink_ext_ack *extack);
167 static struct napi_struct *napi_by_id(unsigned int napi_id);
170 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
173 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
175 * Writers must hold the rtnl semaphore while they loop through the
176 * dev_base_head list, and hold dev_base_lock for writing when they do the
177 * actual updates. This allows pure readers to access the list even
178 * while a writer is preparing to update it.
180 * To put it another way, dev_base_lock is held for writing only to
181 * protect against pure readers; the rtnl semaphore provides the
182 * protection against other writers.
184 * See, for example usages, register_netdevice() and
185 * unregister_netdevice(), which must be called with the rtnl
188 DEFINE_RWLOCK(dev_base_lock);
189 EXPORT_SYMBOL(dev_base_lock);
191 static DEFINE_MUTEX(ifalias_mutex);
193 /* protects napi_hash addition/deletion and napi_gen_id */
194 static DEFINE_SPINLOCK(napi_hash_lock);
196 static unsigned int napi_gen_id = NR_CPUS;
197 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
199 static DECLARE_RWSEM(devnet_rename_sem);
201 static inline void dev_base_seq_inc(struct net *net)
203 while (++net->dev_base_seq == 0)
207 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
209 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
211 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
214 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
216 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
219 static inline void rps_lock_irqsave(struct softnet_data *sd,
220 unsigned long *flags)
222 if (IS_ENABLED(CONFIG_RPS))
223 spin_lock_irqsave(&sd->input_pkt_queue.lock, *flags);
224 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
225 local_irq_save(*flags);
228 static inline void rps_lock_irq_disable(struct softnet_data *sd)
230 if (IS_ENABLED(CONFIG_RPS))
231 spin_lock_irq(&sd->input_pkt_queue.lock);
232 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
236 static inline void rps_unlock_irq_restore(struct softnet_data *sd,
237 unsigned long *flags)
239 if (IS_ENABLED(CONFIG_RPS))
240 spin_unlock_irqrestore(&sd->input_pkt_queue.lock, *flags);
241 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
242 local_irq_restore(*flags);
245 static inline void rps_unlock_irq_enable(struct softnet_data *sd)
247 if (IS_ENABLED(CONFIG_RPS))
248 spin_unlock_irq(&sd->input_pkt_queue.lock);
249 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
253 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
256 struct netdev_name_node *name_node;
258 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
261 INIT_HLIST_NODE(&name_node->hlist);
262 name_node->dev = dev;
263 name_node->name = name;
267 static struct netdev_name_node *
268 netdev_name_node_head_alloc(struct net_device *dev)
270 struct netdev_name_node *name_node;
272 name_node = netdev_name_node_alloc(dev, dev->name);
275 INIT_LIST_HEAD(&name_node->list);
279 static void netdev_name_node_free(struct netdev_name_node *name_node)
284 static void netdev_name_node_add(struct net *net,
285 struct netdev_name_node *name_node)
287 hlist_add_head_rcu(&name_node->hlist,
288 dev_name_hash(net, name_node->name));
291 static void netdev_name_node_del(struct netdev_name_node *name_node)
293 hlist_del_rcu(&name_node->hlist);
296 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
299 struct hlist_head *head = dev_name_hash(net, name);
300 struct netdev_name_node *name_node;
302 hlist_for_each_entry(name_node, head, hlist)
303 if (!strcmp(name_node->name, name))
308 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
311 struct hlist_head *head = dev_name_hash(net, name);
312 struct netdev_name_node *name_node;
314 hlist_for_each_entry_rcu(name_node, head, hlist)
315 if (!strcmp(name_node->name, name))
320 bool netdev_name_in_use(struct net *net, const char *name)
322 return netdev_name_node_lookup(net, name);
324 EXPORT_SYMBOL(netdev_name_in_use);
326 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
328 struct netdev_name_node *name_node;
329 struct net *net = dev_net(dev);
331 name_node = netdev_name_node_lookup(net, name);
334 name_node = netdev_name_node_alloc(dev, name);
337 netdev_name_node_add(net, name_node);
338 /* The node that holds dev->name acts as a head of per-device list. */
339 list_add_tail(&name_node->list, &dev->name_node->list);
344 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
346 list_del(&name_node->list);
347 netdev_name_node_del(name_node);
348 kfree(name_node->name);
349 netdev_name_node_free(name_node);
352 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
354 struct netdev_name_node *name_node;
355 struct net *net = dev_net(dev);
357 name_node = netdev_name_node_lookup(net, name);
360 /* lookup might have found our primary name or a name belonging
363 if (name_node == dev->name_node || name_node->dev != dev)
366 __netdev_name_node_alt_destroy(name_node);
371 static void netdev_name_node_alt_flush(struct net_device *dev)
373 struct netdev_name_node *name_node, *tmp;
375 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list)
376 __netdev_name_node_alt_destroy(name_node);
379 /* Device list insertion */
380 static void list_netdevice(struct net_device *dev)
382 struct net *net = dev_net(dev);
386 write_lock(&dev_base_lock);
387 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
388 netdev_name_node_add(net, dev->name_node);
389 hlist_add_head_rcu(&dev->index_hlist,
390 dev_index_hash(net, dev->ifindex));
391 write_unlock(&dev_base_lock);
393 dev_base_seq_inc(net);
396 /* Device list removal
397 * caller must respect a RCU grace period before freeing/reusing dev
399 static void unlist_netdevice(struct net_device *dev, bool lock)
403 /* Unlink dev from the device chain */
405 write_lock(&dev_base_lock);
406 list_del_rcu(&dev->dev_list);
407 netdev_name_node_del(dev->name_node);
408 hlist_del_rcu(&dev->index_hlist);
410 write_unlock(&dev_base_lock);
412 dev_base_seq_inc(dev_net(dev));
419 static RAW_NOTIFIER_HEAD(netdev_chain);
422 * Device drivers call our routines to queue packets here. We empty the
423 * queue in the local softnet handler.
426 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
427 EXPORT_PER_CPU_SYMBOL(softnet_data);
429 #ifdef CONFIG_LOCKDEP
431 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
432 * according to dev->type
434 static const unsigned short netdev_lock_type[] = {
435 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
436 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
437 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
438 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
439 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
440 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
441 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
442 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
443 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
444 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
445 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
446 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
447 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
448 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
449 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
451 static const char *const netdev_lock_name[] = {
452 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
453 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
454 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
455 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
456 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
457 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
458 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
459 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
460 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
461 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
462 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
463 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
464 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
465 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
466 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
468 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
469 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
471 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
475 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
476 if (netdev_lock_type[i] == dev_type)
478 /* the last key is used by default */
479 return ARRAY_SIZE(netdev_lock_type) - 1;
482 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
483 unsigned short dev_type)
487 i = netdev_lock_pos(dev_type);
488 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
489 netdev_lock_name[i]);
492 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
496 i = netdev_lock_pos(dev->type);
497 lockdep_set_class_and_name(&dev->addr_list_lock,
498 &netdev_addr_lock_key[i],
499 netdev_lock_name[i]);
502 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
503 unsigned short dev_type)
507 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
512 /*******************************************************************************
514 * Protocol management and registration routines
516 *******************************************************************************/
520 * Add a protocol ID to the list. Now that the input handler is
521 * smarter we can dispense with all the messy stuff that used to be
524 * BEWARE!!! Protocol handlers, mangling input packets,
525 * MUST BE last in hash buckets and checking protocol handlers
526 * MUST start from promiscuous ptype_all chain in net_bh.
527 * It is true now, do not change it.
528 * Explanation follows: if protocol handler, mangling packet, will
529 * be the first on list, it is not able to sense, that packet
530 * is cloned and should be copied-on-write, so that it will
531 * change it and subsequent readers will get broken packet.
535 static inline struct list_head *ptype_head(const struct packet_type *pt)
537 if (pt->type == htons(ETH_P_ALL))
538 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
540 return pt->dev ? &pt->dev->ptype_specific :
541 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
545 * dev_add_pack - add packet handler
546 * @pt: packet type declaration
548 * Add a protocol handler to the networking stack. The passed &packet_type
549 * is linked into kernel lists and may not be freed until it has been
550 * removed from the kernel lists.
552 * This call does not sleep therefore it can not
553 * guarantee all CPU's that are in middle of receiving packets
554 * will see the new packet type (until the next received packet).
557 void dev_add_pack(struct packet_type *pt)
559 struct list_head *head = ptype_head(pt);
561 spin_lock(&ptype_lock);
562 list_add_rcu(&pt->list, head);
563 spin_unlock(&ptype_lock);
565 EXPORT_SYMBOL(dev_add_pack);
568 * __dev_remove_pack - remove packet handler
569 * @pt: packet type declaration
571 * Remove a protocol handler that was previously added to the kernel
572 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
573 * from the kernel lists and can be freed or reused once this function
576 * The packet type might still be in use by receivers
577 * and must not be freed until after all the CPU's have gone
578 * through a quiescent state.
580 void __dev_remove_pack(struct packet_type *pt)
582 struct list_head *head = ptype_head(pt);
583 struct packet_type *pt1;
585 spin_lock(&ptype_lock);
587 list_for_each_entry(pt1, head, list) {
589 list_del_rcu(&pt->list);
594 pr_warn("dev_remove_pack: %p not found\n", pt);
596 spin_unlock(&ptype_lock);
598 EXPORT_SYMBOL(__dev_remove_pack);
601 * dev_remove_pack - remove packet handler
602 * @pt: packet type declaration
604 * Remove a protocol handler that was previously added to the kernel
605 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
606 * from the kernel lists and can be freed or reused once this function
609 * This call sleeps to guarantee that no CPU is looking at the packet
612 void dev_remove_pack(struct packet_type *pt)
614 __dev_remove_pack(pt);
618 EXPORT_SYMBOL(dev_remove_pack);
621 /*******************************************************************************
623 * Device Interface Subroutines
625 *******************************************************************************/
628 * dev_get_iflink - get 'iflink' value of a interface
629 * @dev: targeted interface
631 * Indicates the ifindex the interface is linked to.
632 * Physical interfaces have the same 'ifindex' and 'iflink' values.
635 int dev_get_iflink(const struct net_device *dev)
637 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
638 return dev->netdev_ops->ndo_get_iflink(dev);
642 EXPORT_SYMBOL(dev_get_iflink);
645 * dev_fill_metadata_dst - Retrieve tunnel egress information.
646 * @dev: targeted interface
649 * For better visibility of tunnel traffic OVS needs to retrieve
650 * egress tunnel information for a packet. Following API allows
651 * user to get this info.
653 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
655 struct ip_tunnel_info *info;
657 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
660 info = skb_tunnel_info_unclone(skb);
663 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
666 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
668 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
670 static struct net_device_path *dev_fwd_path(struct net_device_path_stack *stack)
672 int k = stack->num_paths++;
674 if (WARN_ON_ONCE(k >= NET_DEVICE_PATH_STACK_MAX))
677 return &stack->path[k];
680 int dev_fill_forward_path(const struct net_device *dev, const u8 *daddr,
681 struct net_device_path_stack *stack)
683 const struct net_device *last_dev;
684 struct net_device_path_ctx ctx = {
687 struct net_device_path *path;
690 memcpy(ctx.daddr, daddr, sizeof(ctx.daddr));
691 stack->num_paths = 0;
692 while (ctx.dev && ctx.dev->netdev_ops->ndo_fill_forward_path) {
694 path = dev_fwd_path(stack);
698 memset(path, 0, sizeof(struct net_device_path));
699 ret = ctx.dev->netdev_ops->ndo_fill_forward_path(&ctx, path);
703 if (WARN_ON_ONCE(last_dev == ctx.dev))
710 path = dev_fwd_path(stack);
713 path->type = DEV_PATH_ETHERNET;
718 EXPORT_SYMBOL_GPL(dev_fill_forward_path);
721 * __dev_get_by_name - find a device by its name
722 * @net: the applicable net namespace
723 * @name: name to find
725 * Find an interface by name. Must be called under RTNL semaphore
726 * or @dev_base_lock. If the name is found a pointer to the device
727 * is returned. If the name is not found then %NULL is returned. The
728 * reference counters are not incremented so the caller must be
729 * careful with locks.
732 struct net_device *__dev_get_by_name(struct net *net, const char *name)
734 struct netdev_name_node *node_name;
736 node_name = netdev_name_node_lookup(net, name);
737 return node_name ? node_name->dev : NULL;
739 EXPORT_SYMBOL(__dev_get_by_name);
742 * dev_get_by_name_rcu - find a device by its name
743 * @net: the applicable net namespace
744 * @name: name to find
746 * Find an interface by name.
747 * If the name is found a pointer to the device is returned.
748 * If the name is not found then %NULL is returned.
749 * The reference counters are not incremented so the caller must be
750 * careful with locks. The caller must hold RCU lock.
753 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
755 struct netdev_name_node *node_name;
757 node_name = netdev_name_node_lookup_rcu(net, name);
758 return node_name ? node_name->dev : NULL;
760 EXPORT_SYMBOL(dev_get_by_name_rcu);
762 /* Deprecated for new users, call netdev_get_by_name() instead */
763 struct net_device *dev_get_by_name(struct net *net, const char *name)
765 struct net_device *dev;
768 dev = dev_get_by_name_rcu(net, name);
773 EXPORT_SYMBOL(dev_get_by_name);
776 * netdev_get_by_name() - find a device by its name
777 * @net: the applicable net namespace
778 * @name: name to find
779 * @tracker: tracking object for the acquired reference
780 * @gfp: allocation flags for the tracker
782 * Find an interface by name. This can be called from any
783 * context and does its own locking. The returned handle has
784 * the usage count incremented and the caller must use netdev_put() to
785 * release it when it is no longer needed. %NULL is returned if no
786 * matching device is found.
788 struct net_device *netdev_get_by_name(struct net *net, const char *name,
789 netdevice_tracker *tracker, gfp_t gfp)
791 struct net_device *dev;
793 dev = dev_get_by_name(net, name);
795 netdev_tracker_alloc(dev, tracker, gfp);
798 EXPORT_SYMBOL(netdev_get_by_name);
801 * __dev_get_by_index - find a device by its ifindex
802 * @net: the applicable net namespace
803 * @ifindex: index of device
805 * Search for an interface by index. Returns %NULL if the device
806 * is not found or a pointer to the device. The device has not
807 * had its reference counter increased so the caller must be careful
808 * about locking. The caller must hold either the RTNL semaphore
812 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
814 struct net_device *dev;
815 struct hlist_head *head = dev_index_hash(net, ifindex);
817 hlist_for_each_entry(dev, head, index_hlist)
818 if (dev->ifindex == ifindex)
823 EXPORT_SYMBOL(__dev_get_by_index);
826 * dev_get_by_index_rcu - find a device by its ifindex
827 * @net: the applicable net namespace
828 * @ifindex: index of device
830 * Search for an interface by index. Returns %NULL if the device
831 * is not found or a pointer to the device. The device has not
832 * had its reference counter increased so the caller must be careful
833 * about locking. The caller must hold RCU lock.
836 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
838 struct net_device *dev;
839 struct hlist_head *head = dev_index_hash(net, ifindex);
841 hlist_for_each_entry_rcu(dev, head, index_hlist)
842 if (dev->ifindex == ifindex)
847 EXPORT_SYMBOL(dev_get_by_index_rcu);
849 /* Deprecated for new users, call netdev_get_by_index() instead */
850 struct net_device *dev_get_by_index(struct net *net, int ifindex)
852 struct net_device *dev;
855 dev = dev_get_by_index_rcu(net, ifindex);
860 EXPORT_SYMBOL(dev_get_by_index);
863 * netdev_get_by_index() - find a device by its ifindex
864 * @net: the applicable net namespace
865 * @ifindex: index of device
866 * @tracker: tracking object for the acquired reference
867 * @gfp: allocation flags for the tracker
869 * Search for an interface by index. Returns NULL if the device
870 * is not found or a pointer to the device. The device returned has
871 * had a reference added and the pointer is safe until the user calls
872 * netdev_put() to indicate they have finished with it.
874 struct net_device *netdev_get_by_index(struct net *net, int ifindex,
875 netdevice_tracker *tracker, gfp_t gfp)
877 struct net_device *dev;
879 dev = dev_get_by_index(net, ifindex);
881 netdev_tracker_alloc(dev, tracker, gfp);
884 EXPORT_SYMBOL(netdev_get_by_index);
887 * dev_get_by_napi_id - find a device by napi_id
888 * @napi_id: ID of the NAPI struct
890 * Search for an interface by NAPI ID. Returns %NULL if the device
891 * is not found or a pointer to the device. The device has not had
892 * its reference counter increased so the caller must be careful
893 * about locking. The caller must hold RCU lock.
896 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
898 struct napi_struct *napi;
900 WARN_ON_ONCE(!rcu_read_lock_held());
902 if (napi_id < MIN_NAPI_ID)
905 napi = napi_by_id(napi_id);
907 return napi ? napi->dev : NULL;
909 EXPORT_SYMBOL(dev_get_by_napi_id);
912 * netdev_get_name - get a netdevice name, knowing its ifindex.
913 * @net: network namespace
914 * @name: a pointer to the buffer where the name will be stored.
915 * @ifindex: the ifindex of the interface to get the name from.
917 int netdev_get_name(struct net *net, char *name, int ifindex)
919 struct net_device *dev;
922 down_read(&devnet_rename_sem);
925 dev = dev_get_by_index_rcu(net, ifindex);
931 strcpy(name, dev->name);
936 up_read(&devnet_rename_sem);
941 * dev_getbyhwaddr_rcu - find a device by its hardware address
942 * @net: the applicable net namespace
943 * @type: media type of device
944 * @ha: hardware address
946 * Search for an interface by MAC address. Returns NULL if the device
947 * is not found or a pointer to the device.
948 * The caller must hold RCU or RTNL.
949 * The returned device has not had its ref count increased
950 * and the caller must therefore be careful about locking
954 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
957 struct net_device *dev;
959 for_each_netdev_rcu(net, dev)
960 if (dev->type == type &&
961 !memcmp(dev->dev_addr, ha, dev->addr_len))
966 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
968 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
970 struct net_device *dev, *ret = NULL;
973 for_each_netdev_rcu(net, dev)
974 if (dev->type == type) {
982 EXPORT_SYMBOL(dev_getfirstbyhwtype);
985 * __dev_get_by_flags - find any device with given flags
986 * @net: the applicable net namespace
987 * @if_flags: IFF_* values
988 * @mask: bitmask of bits in if_flags to check
990 * Search for any interface with the given flags. Returns NULL if a device
991 * is not found or a pointer to the device. Must be called inside
992 * rtnl_lock(), and result refcount is unchanged.
995 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
998 struct net_device *dev, *ret;
1003 for_each_netdev(net, dev) {
1004 if (((dev->flags ^ if_flags) & mask) == 0) {
1011 EXPORT_SYMBOL(__dev_get_by_flags);
1014 * dev_valid_name - check if name is okay for network device
1015 * @name: name string
1017 * Network device names need to be valid file names to
1018 * allow sysfs to work. We also disallow any kind of
1021 bool dev_valid_name(const char *name)
1025 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1027 if (!strcmp(name, ".") || !strcmp(name, ".."))
1031 if (*name == '/' || *name == ':' || isspace(*name))
1037 EXPORT_SYMBOL(dev_valid_name);
1040 * __dev_alloc_name - allocate a name for a device
1041 * @net: network namespace to allocate the device name in
1042 * @name: name format string
1043 * @buf: scratch buffer and result name string
1045 * Passed a format string - eg "lt%d" it will try and find a suitable
1046 * id. It scans list of devices to build up a free map, then chooses
1047 * the first empty slot. The caller must hold the dev_base or rtnl lock
1048 * while allocating the name and adding the device in order to avoid
1050 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1051 * Returns the number of the unit assigned or a negative errno code.
1054 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1058 const int max_netdevices = 8*PAGE_SIZE;
1059 unsigned long *inuse;
1060 struct net_device *d;
1062 if (!dev_valid_name(name))
1065 p = strchr(name, '%');
1068 * Verify the string as this thing may have come from
1069 * the user. There must be either one "%d" and no other "%"
1072 if (p[1] != 'd' || strchr(p + 2, '%'))
1075 /* Use one page as a bit array of possible slots */
1076 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1080 for_each_netdev(net, d) {
1081 struct netdev_name_node *name_node;
1082 list_for_each_entry(name_node, &d->name_node->list, list) {
1083 if (!sscanf(name_node->name, name, &i))
1085 if (i < 0 || i >= max_netdevices)
1088 /* avoid cases where sscanf is not exact inverse of printf */
1089 snprintf(buf, IFNAMSIZ, name, i);
1090 if (!strncmp(buf, name_node->name, IFNAMSIZ))
1091 __set_bit(i, inuse);
1093 if (!sscanf(d->name, name, &i))
1095 if (i < 0 || i >= max_netdevices)
1098 /* avoid cases where sscanf is not exact inverse of printf */
1099 snprintf(buf, IFNAMSIZ, name, i);
1100 if (!strncmp(buf, d->name, IFNAMSIZ))
1101 __set_bit(i, inuse);
1104 i = find_first_zero_bit(inuse, max_netdevices);
1105 free_page((unsigned long) inuse);
1108 snprintf(buf, IFNAMSIZ, name, i);
1109 if (!netdev_name_in_use(net, buf))
1112 /* It is possible to run out of possible slots
1113 * when the name is long and there isn't enough space left
1114 * for the digits, or if all bits are used.
1119 static int dev_alloc_name_ns(struct net *net,
1120 struct net_device *dev,
1127 ret = __dev_alloc_name(net, name, buf);
1129 strscpy(dev->name, buf, IFNAMSIZ);
1134 * dev_alloc_name - allocate a name for a device
1136 * @name: name format string
1138 * Passed a format string - eg "lt%d" it will try and find a suitable
1139 * id. It scans list of devices to build up a free map, then chooses
1140 * the first empty slot. The caller must hold the dev_base or rtnl lock
1141 * while allocating the name and adding the device in order to avoid
1143 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1144 * Returns the number of the unit assigned or a negative errno code.
1147 int dev_alloc_name(struct net_device *dev, const char *name)
1149 return dev_alloc_name_ns(dev_net(dev), dev, name);
1151 EXPORT_SYMBOL(dev_alloc_name);
1153 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1158 if (!dev_valid_name(name))
1161 if (strchr(name, '%'))
1162 return dev_alloc_name_ns(net, dev, name);
1163 else if (netdev_name_in_use(net, name))
1165 else if (dev->name != name)
1166 strscpy(dev->name, name, IFNAMSIZ);
1172 * dev_change_name - change name of a device
1174 * @newname: name (or format string) must be at least IFNAMSIZ
1176 * Change name of a device, can pass format strings "eth%d".
1179 int dev_change_name(struct net_device *dev, const char *newname)
1181 unsigned char old_assign_type;
1182 char oldname[IFNAMSIZ];
1188 BUG_ON(!dev_net(dev));
1192 down_write(&devnet_rename_sem);
1194 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1195 up_write(&devnet_rename_sem);
1199 memcpy(oldname, dev->name, IFNAMSIZ);
1201 err = dev_get_valid_name(net, dev, newname);
1203 up_write(&devnet_rename_sem);
1207 if (oldname[0] && !strchr(oldname, '%'))
1208 netdev_info(dev, "renamed from %s%s\n", oldname,
1209 dev->flags & IFF_UP ? " (while UP)" : "");
1211 old_assign_type = dev->name_assign_type;
1212 dev->name_assign_type = NET_NAME_RENAMED;
1215 ret = device_rename(&dev->dev, dev->name);
1217 memcpy(dev->name, oldname, IFNAMSIZ);
1218 dev->name_assign_type = old_assign_type;
1219 up_write(&devnet_rename_sem);
1223 up_write(&devnet_rename_sem);
1225 netdev_adjacent_rename_links(dev, oldname);
1227 write_lock(&dev_base_lock);
1228 netdev_name_node_del(dev->name_node);
1229 write_unlock(&dev_base_lock);
1233 write_lock(&dev_base_lock);
1234 netdev_name_node_add(net, dev->name_node);
1235 write_unlock(&dev_base_lock);
1237 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1238 ret = notifier_to_errno(ret);
1241 /* err >= 0 after dev_alloc_name() or stores the first errno */
1244 down_write(&devnet_rename_sem);
1245 memcpy(dev->name, oldname, IFNAMSIZ);
1246 memcpy(oldname, newname, IFNAMSIZ);
1247 dev->name_assign_type = old_assign_type;
1248 old_assign_type = NET_NAME_RENAMED;
1251 netdev_err(dev, "name change rollback failed: %d\n",
1260 * dev_set_alias - change ifalias of a device
1262 * @alias: name up to IFALIASZ
1263 * @len: limit of bytes to copy from info
1265 * Set ifalias for a device,
1267 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1269 struct dev_ifalias *new_alias = NULL;
1271 if (len >= IFALIASZ)
1275 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1279 memcpy(new_alias->ifalias, alias, len);
1280 new_alias->ifalias[len] = 0;
1283 mutex_lock(&ifalias_mutex);
1284 new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1285 mutex_is_locked(&ifalias_mutex));
1286 mutex_unlock(&ifalias_mutex);
1289 kfree_rcu(new_alias, rcuhead);
1293 EXPORT_SYMBOL(dev_set_alias);
1296 * dev_get_alias - get ifalias of a device
1298 * @name: buffer to store name of ifalias
1299 * @len: size of buffer
1301 * get ifalias for a device. Caller must make sure dev cannot go
1302 * away, e.g. rcu read lock or own a reference count to device.
1304 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1306 const struct dev_ifalias *alias;
1310 alias = rcu_dereference(dev->ifalias);
1312 ret = snprintf(name, len, "%s", alias->ifalias);
1319 * netdev_features_change - device changes features
1320 * @dev: device to cause notification
1322 * Called to indicate a device has changed features.
1324 void netdev_features_change(struct net_device *dev)
1326 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1328 EXPORT_SYMBOL(netdev_features_change);
1331 * netdev_state_change - device changes state
1332 * @dev: device to cause notification
1334 * Called to indicate a device has changed state. This function calls
1335 * the notifier chains for netdev_chain and sends a NEWLINK message
1336 * to the routing socket.
1338 void netdev_state_change(struct net_device *dev)
1340 if (dev->flags & IFF_UP) {
1341 struct netdev_notifier_change_info change_info = {
1345 call_netdevice_notifiers_info(NETDEV_CHANGE,
1347 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL, 0, NULL);
1350 EXPORT_SYMBOL(netdev_state_change);
1353 * __netdev_notify_peers - notify network peers about existence of @dev,
1354 * to be called when rtnl lock is already held.
1355 * @dev: network device
1357 * Generate traffic such that interested network peers are aware of
1358 * @dev, such as by generating a gratuitous ARP. This may be used when
1359 * a device wants to inform the rest of the network about some sort of
1360 * reconfiguration such as a failover event or virtual machine
1363 void __netdev_notify_peers(struct net_device *dev)
1366 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1367 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1369 EXPORT_SYMBOL(__netdev_notify_peers);
1372 * netdev_notify_peers - notify network peers about existence of @dev
1373 * @dev: network device
1375 * Generate traffic such that interested network peers are aware of
1376 * @dev, such as by generating a gratuitous ARP. This may be used when
1377 * a device wants to inform the rest of the network about some sort of
1378 * reconfiguration such as a failover event or virtual machine
1381 void netdev_notify_peers(struct net_device *dev)
1384 __netdev_notify_peers(dev);
1387 EXPORT_SYMBOL(netdev_notify_peers);
1389 static int napi_threaded_poll(void *data);
1391 static int napi_kthread_create(struct napi_struct *n)
1395 /* Create and wake up the kthread once to put it in
1396 * TASK_INTERRUPTIBLE mode to avoid the blocked task
1397 * warning and work with loadavg.
1399 n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d",
1400 n->dev->name, n->napi_id);
1401 if (IS_ERR(n->thread)) {
1402 err = PTR_ERR(n->thread);
1403 pr_err("kthread_run failed with err %d\n", err);
1410 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1412 const struct net_device_ops *ops = dev->netdev_ops;
1416 dev_addr_check(dev);
1418 if (!netif_device_present(dev)) {
1419 /* may be detached because parent is runtime-suspended */
1420 if (dev->dev.parent)
1421 pm_runtime_resume(dev->dev.parent);
1422 if (!netif_device_present(dev))
1426 /* Block netpoll from trying to do any rx path servicing.
1427 * If we don't do this there is a chance ndo_poll_controller
1428 * or ndo_poll may be running while we open the device
1430 netpoll_poll_disable(dev);
1432 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1433 ret = notifier_to_errno(ret);
1437 set_bit(__LINK_STATE_START, &dev->state);
1439 if (ops->ndo_validate_addr)
1440 ret = ops->ndo_validate_addr(dev);
1442 if (!ret && ops->ndo_open)
1443 ret = ops->ndo_open(dev);
1445 netpoll_poll_enable(dev);
1448 clear_bit(__LINK_STATE_START, &dev->state);
1450 dev->flags |= IFF_UP;
1451 dev_set_rx_mode(dev);
1453 add_device_randomness(dev->dev_addr, dev->addr_len);
1460 * dev_open - prepare an interface for use.
1461 * @dev: device to open
1462 * @extack: netlink extended ack
1464 * Takes a device from down to up state. The device's private open
1465 * function is invoked and then the multicast lists are loaded. Finally
1466 * the device is moved into the up state and a %NETDEV_UP message is
1467 * sent to the netdev notifier chain.
1469 * Calling this function on an active interface is a nop. On a failure
1470 * a negative errno code is returned.
1472 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1476 if (dev->flags & IFF_UP)
1479 ret = __dev_open(dev, extack);
1483 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1484 call_netdevice_notifiers(NETDEV_UP, dev);
1488 EXPORT_SYMBOL(dev_open);
1490 static void __dev_close_many(struct list_head *head)
1492 struct net_device *dev;
1497 list_for_each_entry(dev, head, close_list) {
1498 /* Temporarily disable netpoll until the interface is down */
1499 netpoll_poll_disable(dev);
1501 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1503 clear_bit(__LINK_STATE_START, &dev->state);
1505 /* Synchronize to scheduled poll. We cannot touch poll list, it
1506 * can be even on different cpu. So just clear netif_running().
1508 * dev->stop() will invoke napi_disable() on all of it's
1509 * napi_struct instances on this device.
1511 smp_mb__after_atomic(); /* Commit netif_running(). */
1514 dev_deactivate_many(head);
1516 list_for_each_entry(dev, head, close_list) {
1517 const struct net_device_ops *ops = dev->netdev_ops;
1520 * Call the device specific close. This cannot fail.
1521 * Only if device is UP
1523 * We allow it to be called even after a DETACH hot-plug
1529 dev->flags &= ~IFF_UP;
1530 netpoll_poll_enable(dev);
1534 static void __dev_close(struct net_device *dev)
1538 list_add(&dev->close_list, &single);
1539 __dev_close_many(&single);
1543 void dev_close_many(struct list_head *head, bool unlink)
1545 struct net_device *dev, *tmp;
1547 /* Remove the devices that don't need to be closed */
1548 list_for_each_entry_safe(dev, tmp, head, close_list)
1549 if (!(dev->flags & IFF_UP))
1550 list_del_init(&dev->close_list);
1552 __dev_close_many(head);
1554 list_for_each_entry_safe(dev, tmp, head, close_list) {
1555 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1556 call_netdevice_notifiers(NETDEV_DOWN, dev);
1558 list_del_init(&dev->close_list);
1561 EXPORT_SYMBOL(dev_close_many);
1564 * dev_close - shutdown an interface.
1565 * @dev: device to shutdown
1567 * This function moves an active device into down state. A
1568 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1569 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1572 void dev_close(struct net_device *dev)
1574 if (dev->flags & IFF_UP) {
1577 list_add(&dev->close_list, &single);
1578 dev_close_many(&single, true);
1582 EXPORT_SYMBOL(dev_close);
1586 * dev_disable_lro - disable Large Receive Offload on a device
1589 * Disable Large Receive Offload (LRO) on a net device. Must be
1590 * called under RTNL. This is needed if received packets may be
1591 * forwarded to another interface.
1593 void dev_disable_lro(struct net_device *dev)
1595 struct net_device *lower_dev;
1596 struct list_head *iter;
1598 dev->wanted_features &= ~NETIF_F_LRO;
1599 netdev_update_features(dev);
1601 if (unlikely(dev->features & NETIF_F_LRO))
1602 netdev_WARN(dev, "failed to disable LRO!\n");
1604 netdev_for_each_lower_dev(dev, lower_dev, iter)
1605 dev_disable_lro(lower_dev);
1607 EXPORT_SYMBOL(dev_disable_lro);
1610 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1613 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1614 * called under RTNL. This is needed if Generic XDP is installed on
1617 static void dev_disable_gro_hw(struct net_device *dev)
1619 dev->wanted_features &= ~NETIF_F_GRO_HW;
1620 netdev_update_features(dev);
1622 if (unlikely(dev->features & NETIF_F_GRO_HW))
1623 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1626 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1629 case NETDEV_##val: \
1630 return "NETDEV_" __stringify(val);
1632 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1633 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1634 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1635 N(POST_INIT) N(PRE_UNINIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN)
1636 N(CHANGEUPPER) N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA)
1637 N(BONDING_INFO) N(PRECHANGEUPPER) N(CHANGELOWERSTATE)
1638 N(UDP_TUNNEL_PUSH_INFO) N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1639 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1640 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1641 N(PRE_CHANGEADDR) N(OFFLOAD_XSTATS_ENABLE) N(OFFLOAD_XSTATS_DISABLE)
1642 N(OFFLOAD_XSTATS_REPORT_USED) N(OFFLOAD_XSTATS_REPORT_DELTA)
1646 return "UNKNOWN_NETDEV_EVENT";
1648 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1650 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1651 struct net_device *dev)
1653 struct netdev_notifier_info info = {
1657 return nb->notifier_call(nb, val, &info);
1660 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1661 struct net_device *dev)
1665 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1666 err = notifier_to_errno(err);
1670 if (!(dev->flags & IFF_UP))
1673 call_netdevice_notifier(nb, NETDEV_UP, dev);
1677 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1678 struct net_device *dev)
1680 if (dev->flags & IFF_UP) {
1681 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1683 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1685 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1688 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1691 struct net_device *dev;
1694 for_each_netdev(net, dev) {
1695 err = call_netdevice_register_notifiers(nb, dev);
1702 for_each_netdev_continue_reverse(net, dev)
1703 call_netdevice_unregister_notifiers(nb, dev);
1707 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1710 struct net_device *dev;
1712 for_each_netdev(net, dev)
1713 call_netdevice_unregister_notifiers(nb, dev);
1716 static int dev_boot_phase = 1;
1719 * register_netdevice_notifier - register a network notifier block
1722 * Register a notifier to be called when network device events occur.
1723 * The notifier passed is linked into the kernel structures and must
1724 * not be reused until it has been unregistered. A negative errno code
1725 * is returned on a failure.
1727 * When registered all registration and up events are replayed
1728 * to the new notifier to allow device to have a race free
1729 * view of the network device list.
1732 int register_netdevice_notifier(struct notifier_block *nb)
1737 /* Close race with setup_net() and cleanup_net() */
1738 down_write(&pernet_ops_rwsem);
1740 err = raw_notifier_chain_register(&netdev_chain, nb);
1746 err = call_netdevice_register_net_notifiers(nb, net);
1753 up_write(&pernet_ops_rwsem);
1757 for_each_net_continue_reverse(net)
1758 call_netdevice_unregister_net_notifiers(nb, net);
1760 raw_notifier_chain_unregister(&netdev_chain, nb);
1763 EXPORT_SYMBOL(register_netdevice_notifier);
1766 * unregister_netdevice_notifier - unregister a network notifier block
1769 * Unregister a notifier previously registered by
1770 * register_netdevice_notifier(). The notifier is unlinked into the
1771 * kernel structures and may then be reused. A negative errno code
1772 * is returned on a failure.
1774 * After unregistering unregister and down device events are synthesized
1775 * for all devices on the device list to the removed notifier to remove
1776 * the need for special case cleanup code.
1779 int unregister_netdevice_notifier(struct notifier_block *nb)
1784 /* Close race with setup_net() and cleanup_net() */
1785 down_write(&pernet_ops_rwsem);
1787 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1792 call_netdevice_unregister_net_notifiers(nb, net);
1796 up_write(&pernet_ops_rwsem);
1799 EXPORT_SYMBOL(unregister_netdevice_notifier);
1801 static int __register_netdevice_notifier_net(struct net *net,
1802 struct notifier_block *nb,
1803 bool ignore_call_fail)
1807 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1813 err = call_netdevice_register_net_notifiers(nb, net);
1814 if (err && !ignore_call_fail)
1815 goto chain_unregister;
1820 raw_notifier_chain_unregister(&net->netdev_chain, nb);
1824 static int __unregister_netdevice_notifier_net(struct net *net,
1825 struct notifier_block *nb)
1829 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1833 call_netdevice_unregister_net_notifiers(nb, net);
1838 * register_netdevice_notifier_net - register a per-netns network notifier block
1839 * @net: network namespace
1842 * Register a notifier to be called when network device events occur.
1843 * The notifier passed is linked into the kernel structures and must
1844 * not be reused until it has been unregistered. A negative errno code
1845 * is returned on a failure.
1847 * When registered all registration and up events are replayed
1848 * to the new notifier to allow device to have a race free
1849 * view of the network device list.
1852 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1857 err = __register_netdevice_notifier_net(net, nb, false);
1861 EXPORT_SYMBOL(register_netdevice_notifier_net);
1864 * unregister_netdevice_notifier_net - unregister a per-netns
1865 * network notifier block
1866 * @net: network namespace
1869 * Unregister a notifier previously registered by
1870 * register_netdevice_notifier_net(). The notifier is unlinked from the
1871 * kernel structures and may then be reused. A negative errno code
1872 * is returned on a failure.
1874 * After unregistering unregister and down device events are synthesized
1875 * for all devices on the device list to the removed notifier to remove
1876 * the need for special case cleanup code.
1879 int unregister_netdevice_notifier_net(struct net *net,
1880 struct notifier_block *nb)
1885 err = __unregister_netdevice_notifier_net(net, nb);
1889 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1891 static void __move_netdevice_notifier_net(struct net *src_net,
1892 struct net *dst_net,
1893 struct notifier_block *nb)
1895 __unregister_netdevice_notifier_net(src_net, nb);
1896 __register_netdevice_notifier_net(dst_net, nb, true);
1899 int register_netdevice_notifier_dev_net(struct net_device *dev,
1900 struct notifier_block *nb,
1901 struct netdev_net_notifier *nn)
1906 err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
1909 list_add(&nn->list, &dev->net_notifier_list);
1914 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
1916 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
1917 struct notifier_block *nb,
1918 struct netdev_net_notifier *nn)
1923 list_del(&nn->list);
1924 err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
1928 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
1930 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
1933 struct netdev_net_notifier *nn;
1935 list_for_each_entry(nn, &dev->net_notifier_list, list)
1936 __move_netdevice_notifier_net(dev_net(dev), net, nn->nb);
1940 * call_netdevice_notifiers_info - call all network notifier blocks
1941 * @val: value passed unmodified to notifier function
1942 * @info: notifier information data
1944 * Call all network notifier blocks. Parameters and return value
1945 * are as for raw_notifier_call_chain().
1948 int call_netdevice_notifiers_info(unsigned long val,
1949 struct netdev_notifier_info *info)
1951 struct net *net = dev_net(info->dev);
1956 /* Run per-netns notifier block chain first, then run the global one.
1957 * Hopefully, one day, the global one is going to be removed after
1958 * all notifier block registrators get converted to be per-netns.
1960 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
1961 if (ret & NOTIFY_STOP_MASK)
1963 return raw_notifier_call_chain(&netdev_chain, val, info);
1967 * call_netdevice_notifiers_info_robust - call per-netns notifier blocks
1968 * for and rollback on error
1969 * @val_up: value passed unmodified to notifier function
1970 * @val_down: value passed unmodified to the notifier function when
1971 * recovering from an error on @val_up
1972 * @info: notifier information data
1974 * Call all per-netns network notifier blocks, but not notifier blocks on
1975 * the global notifier chain. Parameters and return value are as for
1976 * raw_notifier_call_chain_robust().
1980 call_netdevice_notifiers_info_robust(unsigned long val_up,
1981 unsigned long val_down,
1982 struct netdev_notifier_info *info)
1984 struct net *net = dev_net(info->dev);
1988 return raw_notifier_call_chain_robust(&net->netdev_chain,
1989 val_up, val_down, info);
1992 static int call_netdevice_notifiers_extack(unsigned long val,
1993 struct net_device *dev,
1994 struct netlink_ext_ack *extack)
1996 struct netdev_notifier_info info = {
2001 return call_netdevice_notifiers_info(val, &info);
2005 * call_netdevice_notifiers - call all network notifier blocks
2006 * @val: value passed unmodified to notifier function
2007 * @dev: net_device pointer passed unmodified to notifier function
2009 * Call all network notifier blocks. Parameters and return value
2010 * are as for raw_notifier_call_chain().
2013 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
2015 return call_netdevice_notifiers_extack(val, dev, NULL);
2017 EXPORT_SYMBOL(call_netdevice_notifiers);
2020 * call_netdevice_notifiers_mtu - call all network notifier blocks
2021 * @val: value passed unmodified to notifier function
2022 * @dev: net_device pointer passed unmodified to notifier function
2023 * @arg: additional u32 argument passed to the notifier function
2025 * Call all network notifier blocks. Parameters and return value
2026 * are as for raw_notifier_call_chain().
2028 static int call_netdevice_notifiers_mtu(unsigned long val,
2029 struct net_device *dev, u32 arg)
2031 struct netdev_notifier_info_ext info = {
2036 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2038 return call_netdevice_notifiers_info(val, &info.info);
2041 #ifdef CONFIG_NET_INGRESS
2042 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2044 void net_inc_ingress_queue(void)
2046 static_branch_inc(&ingress_needed_key);
2048 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2050 void net_dec_ingress_queue(void)
2052 static_branch_dec(&ingress_needed_key);
2054 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2057 #ifdef CONFIG_NET_EGRESS
2058 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2060 void net_inc_egress_queue(void)
2062 static_branch_inc(&egress_needed_key);
2064 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2066 void net_dec_egress_queue(void)
2068 static_branch_dec(&egress_needed_key);
2070 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2073 DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2074 EXPORT_SYMBOL(netstamp_needed_key);
2075 #ifdef CONFIG_JUMP_LABEL
2076 static atomic_t netstamp_needed_deferred;
2077 static atomic_t netstamp_wanted;
2078 static void netstamp_clear(struct work_struct *work)
2080 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2083 wanted = atomic_add_return(deferred, &netstamp_wanted);
2085 static_branch_enable(&netstamp_needed_key);
2087 static_branch_disable(&netstamp_needed_key);
2089 static DECLARE_WORK(netstamp_work, netstamp_clear);
2092 void net_enable_timestamp(void)
2094 #ifdef CONFIG_JUMP_LABEL
2095 int wanted = atomic_read(&netstamp_wanted);
2097 while (wanted > 0) {
2098 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted + 1))
2101 atomic_inc(&netstamp_needed_deferred);
2102 schedule_work(&netstamp_work);
2104 static_branch_inc(&netstamp_needed_key);
2107 EXPORT_SYMBOL(net_enable_timestamp);
2109 void net_disable_timestamp(void)
2111 #ifdef CONFIG_JUMP_LABEL
2112 int wanted = atomic_read(&netstamp_wanted);
2114 while (wanted > 1) {
2115 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted - 1))
2118 atomic_dec(&netstamp_needed_deferred);
2119 schedule_work(&netstamp_work);
2121 static_branch_dec(&netstamp_needed_key);
2124 EXPORT_SYMBOL(net_disable_timestamp);
2126 static inline void net_timestamp_set(struct sk_buff *skb)
2129 skb->mono_delivery_time = 0;
2130 if (static_branch_unlikely(&netstamp_needed_key))
2131 skb->tstamp = ktime_get_real();
2134 #define net_timestamp_check(COND, SKB) \
2135 if (static_branch_unlikely(&netstamp_needed_key)) { \
2136 if ((COND) && !(SKB)->tstamp) \
2137 (SKB)->tstamp = ktime_get_real(); \
2140 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2142 return __is_skb_forwardable(dev, skb, true);
2144 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2146 static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb,
2149 int ret = ____dev_forward_skb(dev, skb, check_mtu);
2152 skb->protocol = eth_type_trans(skb, dev);
2153 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2159 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2161 return __dev_forward_skb2(dev, skb, true);
2163 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2166 * dev_forward_skb - loopback an skb to another netif
2168 * @dev: destination network device
2169 * @skb: buffer to forward
2172 * NET_RX_SUCCESS (no congestion)
2173 * NET_RX_DROP (packet was dropped, but freed)
2175 * dev_forward_skb can be used for injecting an skb from the
2176 * start_xmit function of one device into the receive queue
2177 * of another device.
2179 * The receiving device may be in another namespace, so
2180 * we have to clear all information in the skb that could
2181 * impact namespace isolation.
2183 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2185 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2187 EXPORT_SYMBOL_GPL(dev_forward_skb);
2189 int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb)
2191 return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb);
2194 static inline int deliver_skb(struct sk_buff *skb,
2195 struct packet_type *pt_prev,
2196 struct net_device *orig_dev)
2198 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2200 refcount_inc(&skb->users);
2201 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2204 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2205 struct packet_type **pt,
2206 struct net_device *orig_dev,
2208 struct list_head *ptype_list)
2210 struct packet_type *ptype, *pt_prev = *pt;
2212 list_for_each_entry_rcu(ptype, ptype_list, list) {
2213 if (ptype->type != type)
2216 deliver_skb(skb, pt_prev, orig_dev);
2222 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2224 if (!ptype->af_packet_priv || !skb->sk)
2227 if (ptype->id_match)
2228 return ptype->id_match(ptype, skb->sk);
2229 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2236 * dev_nit_active - return true if any network interface taps are in use
2238 * @dev: network device to check for the presence of taps
2240 bool dev_nit_active(struct net_device *dev)
2242 return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2244 EXPORT_SYMBOL_GPL(dev_nit_active);
2247 * Support routine. Sends outgoing frames to any network
2248 * taps currently in use.
2251 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2253 struct packet_type *ptype;
2254 struct sk_buff *skb2 = NULL;
2255 struct packet_type *pt_prev = NULL;
2256 struct list_head *ptype_list = &ptype_all;
2260 list_for_each_entry_rcu(ptype, ptype_list, list) {
2261 if (ptype->ignore_outgoing)
2264 /* Never send packets back to the socket
2265 * they originated from - MvS (miquels@drinkel.ow.org)
2267 if (skb_loop_sk(ptype, skb))
2271 deliver_skb(skb2, pt_prev, skb->dev);
2276 /* need to clone skb, done only once */
2277 skb2 = skb_clone(skb, GFP_ATOMIC);
2281 net_timestamp_set(skb2);
2283 /* skb->nh should be correctly
2284 * set by sender, so that the second statement is
2285 * just protection against buggy protocols.
2287 skb_reset_mac_header(skb2);
2289 if (skb_network_header(skb2) < skb2->data ||
2290 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2291 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2292 ntohs(skb2->protocol),
2294 skb_reset_network_header(skb2);
2297 skb2->transport_header = skb2->network_header;
2298 skb2->pkt_type = PACKET_OUTGOING;
2302 if (ptype_list == &ptype_all) {
2303 ptype_list = &dev->ptype_all;
2308 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2309 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2315 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2318 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2319 * @dev: Network device
2320 * @txq: number of queues available
2322 * If real_num_tx_queues is changed the tc mappings may no longer be
2323 * valid. To resolve this verify the tc mapping remains valid and if
2324 * not NULL the mapping. With no priorities mapping to this
2325 * offset/count pair it will no longer be used. In the worst case TC0
2326 * is invalid nothing can be done so disable priority mappings. If is
2327 * expected that drivers will fix this mapping if they can before
2328 * calling netif_set_real_num_tx_queues.
2330 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2333 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2335 /* If TC0 is invalidated disable TC mapping */
2336 if (tc->offset + tc->count > txq) {
2337 netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2342 /* Invalidated prio to tc mappings set to TC0 */
2343 for (i = 1; i < TC_BITMASK + 1; i++) {
2344 int q = netdev_get_prio_tc_map(dev, i);
2346 tc = &dev->tc_to_txq[q];
2347 if (tc->offset + tc->count > txq) {
2348 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",
2350 netdev_set_prio_tc_map(dev, i, 0);
2355 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2358 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2361 /* walk through the TCs and see if it falls into any of them */
2362 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2363 if ((txq - tc->offset) < tc->count)
2367 /* didn't find it, just return -1 to indicate no match */
2373 EXPORT_SYMBOL(netdev_txq_to_tc);
2376 static struct static_key xps_needed __read_mostly;
2377 static struct static_key xps_rxqs_needed __read_mostly;
2378 static DEFINE_MUTEX(xps_map_mutex);
2379 #define xmap_dereference(P) \
2380 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2382 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2383 struct xps_dev_maps *old_maps, int tci, u16 index)
2385 struct xps_map *map = NULL;
2389 map = xmap_dereference(dev_maps->attr_map[tci]);
2393 for (pos = map->len; pos--;) {
2394 if (map->queues[pos] != index)
2398 map->queues[pos] = map->queues[--map->len];
2403 RCU_INIT_POINTER(old_maps->attr_map[tci], NULL);
2404 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2405 kfree_rcu(map, rcu);
2412 static bool remove_xps_queue_cpu(struct net_device *dev,
2413 struct xps_dev_maps *dev_maps,
2414 int cpu, u16 offset, u16 count)
2416 int num_tc = dev_maps->num_tc;
2417 bool active = false;
2420 for (tci = cpu * num_tc; num_tc--; tci++) {
2423 for (i = count, j = offset; i--; j++) {
2424 if (!remove_xps_queue(dev_maps, NULL, tci, j))
2434 static void reset_xps_maps(struct net_device *dev,
2435 struct xps_dev_maps *dev_maps,
2436 enum xps_map_type type)
2438 static_key_slow_dec_cpuslocked(&xps_needed);
2439 if (type == XPS_RXQS)
2440 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2442 RCU_INIT_POINTER(dev->xps_maps[type], NULL);
2444 kfree_rcu(dev_maps, rcu);
2447 static void clean_xps_maps(struct net_device *dev, enum xps_map_type type,
2448 u16 offset, u16 count)
2450 struct xps_dev_maps *dev_maps;
2451 bool active = false;
2454 dev_maps = xmap_dereference(dev->xps_maps[type]);
2458 for (j = 0; j < dev_maps->nr_ids; j++)
2459 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count);
2461 reset_xps_maps(dev, dev_maps, type);
2463 if (type == XPS_CPUS) {
2464 for (i = offset + (count - 1); count--; i--)
2465 netdev_queue_numa_node_write(
2466 netdev_get_tx_queue(dev, i), NUMA_NO_NODE);
2470 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2473 if (!static_key_false(&xps_needed))
2477 mutex_lock(&xps_map_mutex);
2479 if (static_key_false(&xps_rxqs_needed))
2480 clean_xps_maps(dev, XPS_RXQS, offset, count);
2482 clean_xps_maps(dev, XPS_CPUS, offset, count);
2484 mutex_unlock(&xps_map_mutex);
2488 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2490 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2493 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2494 u16 index, bool is_rxqs_map)
2496 struct xps_map *new_map;
2497 int alloc_len = XPS_MIN_MAP_ALLOC;
2500 for (pos = 0; map && pos < map->len; pos++) {
2501 if (map->queues[pos] != index)
2506 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2508 if (pos < map->alloc_len)
2511 alloc_len = map->alloc_len * 2;
2514 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2518 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2520 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2521 cpu_to_node(attr_index));
2525 for (i = 0; i < pos; i++)
2526 new_map->queues[i] = map->queues[i];
2527 new_map->alloc_len = alloc_len;
2533 /* Copy xps maps at a given index */
2534 static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps,
2535 struct xps_dev_maps *new_dev_maps, int index,
2536 int tc, bool skip_tc)
2538 int i, tci = index * dev_maps->num_tc;
2539 struct xps_map *map;
2541 /* copy maps belonging to foreign traffic classes */
2542 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2543 if (i == tc && skip_tc)
2546 /* fill in the new device map from the old device map */
2547 map = xmap_dereference(dev_maps->attr_map[tci]);
2548 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2552 /* Must be called under cpus_read_lock */
2553 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2554 u16 index, enum xps_map_type type)
2556 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL;
2557 const unsigned long *online_mask = NULL;
2558 bool active = false, copy = false;
2559 int i, j, tci, numa_node_id = -2;
2560 int maps_sz, num_tc = 1, tc = 0;
2561 struct xps_map *map, *new_map;
2562 unsigned int nr_ids;
2564 WARN_ON_ONCE(index >= dev->num_tx_queues);
2567 /* Do not allow XPS on subordinate device directly */
2568 num_tc = dev->num_tc;
2572 /* If queue belongs to subordinate dev use its map */
2573 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2575 tc = netdev_txq_to_tc(dev, index);
2580 mutex_lock(&xps_map_mutex);
2582 dev_maps = xmap_dereference(dev->xps_maps[type]);
2583 if (type == XPS_RXQS) {
2584 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2585 nr_ids = dev->num_rx_queues;
2587 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2588 if (num_possible_cpus() > 1)
2589 online_mask = cpumask_bits(cpu_online_mask);
2590 nr_ids = nr_cpu_ids;
2593 if (maps_sz < L1_CACHE_BYTES)
2594 maps_sz = L1_CACHE_BYTES;
2596 /* The old dev_maps could be larger or smaller than the one we're
2597 * setting up now, as dev->num_tc or nr_ids could have been updated in
2598 * between. We could try to be smart, but let's be safe instead and only
2599 * copy foreign traffic classes if the two map sizes match.
2602 dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids)
2605 /* allocate memory for queue storage */
2606 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2608 if (!new_dev_maps) {
2609 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2610 if (!new_dev_maps) {
2611 mutex_unlock(&xps_map_mutex);
2615 new_dev_maps->nr_ids = nr_ids;
2616 new_dev_maps->num_tc = num_tc;
2619 tci = j * num_tc + tc;
2620 map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL;
2622 map = expand_xps_map(map, j, index, type == XPS_RXQS);
2626 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2630 goto out_no_new_maps;
2633 /* Increment static keys at most once per type */
2634 static_key_slow_inc_cpuslocked(&xps_needed);
2635 if (type == XPS_RXQS)
2636 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2639 for (j = 0; j < nr_ids; j++) {
2640 bool skip_tc = false;
2642 tci = j * num_tc + tc;
2643 if (netif_attr_test_mask(j, mask, nr_ids) &&
2644 netif_attr_test_online(j, online_mask, nr_ids)) {
2645 /* add tx-queue to CPU/rx-queue maps */
2650 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2651 while ((pos < map->len) && (map->queues[pos] != index))
2654 if (pos == map->len)
2655 map->queues[map->len++] = index;
2657 if (type == XPS_CPUS) {
2658 if (numa_node_id == -2)
2659 numa_node_id = cpu_to_node(j);
2660 else if (numa_node_id != cpu_to_node(j))
2667 xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc,
2671 rcu_assign_pointer(dev->xps_maps[type], new_dev_maps);
2673 /* Cleanup old maps */
2675 goto out_no_old_maps;
2677 for (j = 0; j < dev_maps->nr_ids; j++) {
2678 for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
2679 map = xmap_dereference(dev_maps->attr_map[tci]);
2684 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2689 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2690 kfree_rcu(map, rcu);
2694 old_dev_maps = dev_maps;
2697 dev_maps = new_dev_maps;
2701 if (type == XPS_CPUS)
2702 /* update Tx queue numa node */
2703 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2704 (numa_node_id >= 0) ?
2705 numa_node_id : NUMA_NO_NODE);
2710 /* removes tx-queue from unused CPUs/rx-queues */
2711 for (j = 0; j < dev_maps->nr_ids; j++) {
2712 tci = j * dev_maps->num_tc;
2714 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2716 netif_attr_test_mask(j, mask, dev_maps->nr_ids) &&
2717 netif_attr_test_online(j, online_mask, dev_maps->nr_ids))
2720 active |= remove_xps_queue(dev_maps,
2721 copy ? old_dev_maps : NULL,
2727 kfree_rcu(old_dev_maps, rcu);
2729 /* free map if not active */
2731 reset_xps_maps(dev, dev_maps, type);
2734 mutex_unlock(&xps_map_mutex);
2738 /* remove any maps that we added */
2739 for (j = 0; j < nr_ids; j++) {
2740 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2741 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2743 xmap_dereference(dev_maps->attr_map[tci]) :
2745 if (new_map && new_map != map)
2750 mutex_unlock(&xps_map_mutex);
2752 kfree(new_dev_maps);
2755 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2757 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2763 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS);
2768 EXPORT_SYMBOL(netif_set_xps_queue);
2771 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2773 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2775 /* Unbind any subordinate channels */
2776 while (txq-- != &dev->_tx[0]) {
2778 netdev_unbind_sb_channel(dev, txq->sb_dev);
2782 void netdev_reset_tc(struct net_device *dev)
2785 netif_reset_xps_queues_gt(dev, 0);
2787 netdev_unbind_all_sb_channels(dev);
2789 /* Reset TC configuration of device */
2791 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2792 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2794 EXPORT_SYMBOL(netdev_reset_tc);
2796 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2798 if (tc >= dev->num_tc)
2802 netif_reset_xps_queues(dev, offset, count);
2804 dev->tc_to_txq[tc].count = count;
2805 dev->tc_to_txq[tc].offset = offset;
2808 EXPORT_SYMBOL(netdev_set_tc_queue);
2810 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2812 if (num_tc > TC_MAX_QUEUE)
2816 netif_reset_xps_queues_gt(dev, 0);
2818 netdev_unbind_all_sb_channels(dev);
2820 dev->num_tc = num_tc;
2823 EXPORT_SYMBOL(netdev_set_num_tc);
2825 void netdev_unbind_sb_channel(struct net_device *dev,
2826 struct net_device *sb_dev)
2828 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2831 netif_reset_xps_queues_gt(sb_dev, 0);
2833 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2834 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2836 while (txq-- != &dev->_tx[0]) {
2837 if (txq->sb_dev == sb_dev)
2841 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2843 int netdev_bind_sb_channel_queue(struct net_device *dev,
2844 struct net_device *sb_dev,
2845 u8 tc, u16 count, u16 offset)
2847 /* Make certain the sb_dev and dev are already configured */
2848 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2851 /* We cannot hand out queues we don't have */
2852 if ((offset + count) > dev->real_num_tx_queues)
2855 /* Record the mapping */
2856 sb_dev->tc_to_txq[tc].count = count;
2857 sb_dev->tc_to_txq[tc].offset = offset;
2859 /* Provide a way for Tx queue to find the tc_to_txq map or
2860 * XPS map for itself.
2863 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2867 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2869 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2871 /* Do not use a multiqueue device to represent a subordinate channel */
2872 if (netif_is_multiqueue(dev))
2875 /* We allow channels 1 - 32767 to be used for subordinate channels.
2876 * Channel 0 is meant to be "native" mode and used only to represent
2877 * the main root device. We allow writing 0 to reset the device back
2878 * to normal mode after being used as a subordinate channel.
2880 if (channel > S16_MAX)
2883 dev->num_tc = -channel;
2887 EXPORT_SYMBOL(netdev_set_sb_channel);
2890 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2891 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2893 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2898 disabling = txq < dev->real_num_tx_queues;
2900 if (txq < 1 || txq > dev->num_tx_queues)
2903 if (dev->reg_state == NETREG_REGISTERED ||
2904 dev->reg_state == NETREG_UNREGISTERING) {
2907 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2913 netif_setup_tc(dev, txq);
2915 dev_qdisc_change_real_num_tx(dev, txq);
2917 dev->real_num_tx_queues = txq;
2921 qdisc_reset_all_tx_gt(dev, txq);
2923 netif_reset_xps_queues_gt(dev, txq);
2927 dev->real_num_tx_queues = txq;
2932 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2936 * netif_set_real_num_rx_queues - set actual number of RX queues used
2937 * @dev: Network device
2938 * @rxq: Actual number of RX queues
2940 * This must be called either with the rtnl_lock held or before
2941 * registration of the net device. Returns 0 on success, or a
2942 * negative error code. If called before registration, it always
2945 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2949 if (rxq < 1 || rxq > dev->num_rx_queues)
2952 if (dev->reg_state == NETREG_REGISTERED) {
2955 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2961 dev->real_num_rx_queues = rxq;
2964 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2968 * netif_set_real_num_queues - set actual number of RX and TX queues used
2969 * @dev: Network device
2970 * @txq: Actual number of TX queues
2971 * @rxq: Actual number of RX queues
2973 * Set the real number of both TX and RX queues.
2974 * Does nothing if the number of queues is already correct.
2976 int netif_set_real_num_queues(struct net_device *dev,
2977 unsigned int txq, unsigned int rxq)
2979 unsigned int old_rxq = dev->real_num_rx_queues;
2982 if (txq < 1 || txq > dev->num_tx_queues ||
2983 rxq < 1 || rxq > dev->num_rx_queues)
2986 /* Start from increases, so the error path only does decreases -
2987 * decreases can't fail.
2989 if (rxq > dev->real_num_rx_queues) {
2990 err = netif_set_real_num_rx_queues(dev, rxq);
2994 if (txq > dev->real_num_tx_queues) {
2995 err = netif_set_real_num_tx_queues(dev, txq);
2999 if (rxq < dev->real_num_rx_queues)
3000 WARN_ON(netif_set_real_num_rx_queues(dev, rxq));
3001 if (txq < dev->real_num_tx_queues)
3002 WARN_ON(netif_set_real_num_tx_queues(dev, txq));
3006 WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq));
3009 EXPORT_SYMBOL(netif_set_real_num_queues);
3012 * netif_set_tso_max_size() - set the max size of TSO frames supported
3013 * @dev: netdev to update
3014 * @size: max skb->len of a TSO frame
3016 * Set the limit on the size of TSO super-frames the device can handle.
3017 * Unless explicitly set the stack will assume the value of
3018 * %GSO_LEGACY_MAX_SIZE.
3020 void netif_set_tso_max_size(struct net_device *dev, unsigned int size)
3022 dev->tso_max_size = min(GSO_MAX_SIZE, size);
3023 if (size < READ_ONCE(dev->gso_max_size))
3024 netif_set_gso_max_size(dev, size);
3025 if (size < READ_ONCE(dev->gso_ipv4_max_size))
3026 netif_set_gso_ipv4_max_size(dev, size);
3028 EXPORT_SYMBOL(netif_set_tso_max_size);
3031 * netif_set_tso_max_segs() - set the max number of segs supported for TSO
3032 * @dev: netdev to update
3033 * @segs: max number of TCP segments
3035 * Set the limit on the number of TCP segments the device can generate from
3036 * a single TSO super-frame.
3037 * Unless explicitly set the stack will assume the value of %GSO_MAX_SEGS.
3039 void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs)
3041 dev->tso_max_segs = segs;
3042 if (segs < READ_ONCE(dev->gso_max_segs))
3043 netif_set_gso_max_segs(dev, segs);
3045 EXPORT_SYMBOL(netif_set_tso_max_segs);
3048 * netif_inherit_tso_max() - copy all TSO limits from a lower device to an upper
3049 * @to: netdev to update
3050 * @from: netdev from which to copy the limits
3052 void netif_inherit_tso_max(struct net_device *to, const struct net_device *from)
3054 netif_set_tso_max_size(to, from->tso_max_size);
3055 netif_set_tso_max_segs(to, from->tso_max_segs);
3057 EXPORT_SYMBOL(netif_inherit_tso_max);
3060 * netif_get_num_default_rss_queues - default number of RSS queues
3062 * Default value is the number of physical cores if there are only 1 or 2, or
3063 * divided by 2 if there are more.
3065 int netif_get_num_default_rss_queues(void)
3070 if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL)))
3073 cpumask_copy(cpus, cpu_online_mask);
3074 for_each_cpu(cpu, cpus) {
3076 cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu));
3078 free_cpumask_var(cpus);
3080 return count > 2 ? DIV_ROUND_UP(count, 2) : count;
3082 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3084 static void __netif_reschedule(struct Qdisc *q)
3086 struct softnet_data *sd;
3087 unsigned long flags;
3089 local_irq_save(flags);
3090 sd = this_cpu_ptr(&softnet_data);
3091 q->next_sched = NULL;
3092 *sd->output_queue_tailp = q;
3093 sd->output_queue_tailp = &q->next_sched;
3094 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3095 local_irq_restore(flags);
3098 void __netif_schedule(struct Qdisc *q)
3100 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3101 __netif_reschedule(q);
3103 EXPORT_SYMBOL(__netif_schedule);
3105 struct dev_kfree_skb_cb {
3106 enum skb_drop_reason reason;
3109 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3111 return (struct dev_kfree_skb_cb *)skb->cb;
3114 void netif_schedule_queue(struct netdev_queue *txq)
3117 if (!netif_xmit_stopped(txq)) {
3118 struct Qdisc *q = rcu_dereference(txq->qdisc);
3120 __netif_schedule(q);
3124 EXPORT_SYMBOL(netif_schedule_queue);
3126 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3128 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3132 q = rcu_dereference(dev_queue->qdisc);
3133 __netif_schedule(q);
3137 EXPORT_SYMBOL(netif_tx_wake_queue);
3139 void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3141 unsigned long flags;
3146 if (likely(refcount_read(&skb->users) == 1)) {
3148 refcount_set(&skb->users, 0);
3149 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3152 get_kfree_skb_cb(skb)->reason = reason;
3153 local_irq_save(flags);
3154 skb->next = __this_cpu_read(softnet_data.completion_queue);
3155 __this_cpu_write(softnet_data.completion_queue, skb);
3156 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3157 local_irq_restore(flags);
3159 EXPORT_SYMBOL(dev_kfree_skb_irq_reason);
3161 void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3163 if (in_hardirq() || irqs_disabled())
3164 dev_kfree_skb_irq_reason(skb, reason);
3166 kfree_skb_reason(skb, reason);
3168 EXPORT_SYMBOL(dev_kfree_skb_any_reason);
3172 * netif_device_detach - mark device as removed
3173 * @dev: network device
3175 * Mark device as removed from system and therefore no longer available.
3177 void netif_device_detach(struct net_device *dev)
3179 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3180 netif_running(dev)) {
3181 netif_tx_stop_all_queues(dev);
3184 EXPORT_SYMBOL(netif_device_detach);
3187 * netif_device_attach - mark device as attached
3188 * @dev: network device
3190 * Mark device as attached from system and restart if needed.
3192 void netif_device_attach(struct net_device *dev)
3194 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3195 netif_running(dev)) {
3196 netif_tx_wake_all_queues(dev);
3197 __netdev_watchdog_up(dev);
3200 EXPORT_SYMBOL(netif_device_attach);
3203 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3204 * to be used as a distribution range.
3206 static u16 skb_tx_hash(const struct net_device *dev,
3207 const struct net_device *sb_dev,
3208 struct sk_buff *skb)
3212 u16 qcount = dev->real_num_tx_queues;
3215 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3217 qoffset = sb_dev->tc_to_txq[tc].offset;
3218 qcount = sb_dev->tc_to_txq[tc].count;
3219 if (unlikely(!qcount)) {
3220 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3221 sb_dev->name, qoffset, tc);
3223 qcount = dev->real_num_tx_queues;
3227 if (skb_rx_queue_recorded(skb)) {
3228 DEBUG_NET_WARN_ON_ONCE(qcount == 0);
3229 hash = skb_get_rx_queue(skb);
3230 if (hash >= qoffset)
3232 while (unlikely(hash >= qcount))
3234 return hash + qoffset;
3237 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3240 void skb_warn_bad_offload(const struct sk_buff *skb)
3242 static const netdev_features_t null_features;
3243 struct net_device *dev = skb->dev;
3244 const char *name = "";
3246 if (!net_ratelimit())
3250 if (dev->dev.parent)
3251 name = dev_driver_string(dev->dev.parent);
3253 name = netdev_name(dev);
3255 skb_dump(KERN_WARNING, skb, false);
3256 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3257 name, dev ? &dev->features : &null_features,
3258 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3262 * Invalidate hardware checksum when packet is to be mangled, and
3263 * complete checksum manually on outgoing path.
3265 int skb_checksum_help(struct sk_buff *skb)
3268 int ret = 0, offset;
3270 if (skb->ip_summed == CHECKSUM_COMPLETE)
3271 goto out_set_summed;
3273 if (unlikely(skb_is_gso(skb))) {
3274 skb_warn_bad_offload(skb);
3278 /* Before computing a checksum, we should make sure no frag could
3279 * be modified by an external entity : checksum could be wrong.
3281 if (skb_has_shared_frag(skb)) {
3282 ret = __skb_linearize(skb);
3287 offset = skb_checksum_start_offset(skb);
3289 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3290 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3293 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3295 offset += skb->csum_offset;
3296 if (WARN_ON_ONCE(offset + sizeof(__sum16) > skb_headlen(skb))) {
3297 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3300 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3304 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3306 skb->ip_summed = CHECKSUM_NONE;
3310 EXPORT_SYMBOL(skb_checksum_help);
3312 int skb_crc32c_csum_help(struct sk_buff *skb)
3315 int ret = 0, offset, start;
3317 if (skb->ip_summed != CHECKSUM_PARTIAL)
3320 if (unlikely(skb_is_gso(skb)))
3323 /* Before computing a checksum, we should make sure no frag could
3324 * be modified by an external entity : checksum could be wrong.
3326 if (unlikely(skb_has_shared_frag(skb))) {
3327 ret = __skb_linearize(skb);
3331 start = skb_checksum_start_offset(skb);
3332 offset = start + offsetof(struct sctphdr, checksum);
3333 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3338 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3342 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3343 skb->len - start, ~(__u32)0,
3345 *(__le32 *)(skb->data + offset) = crc32c_csum;
3346 skb_reset_csum_not_inet(skb);
3351 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3353 __be16 type = skb->protocol;
3355 /* Tunnel gso handlers can set protocol to ethernet. */
3356 if (type == htons(ETH_P_TEB)) {
3359 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3362 eth = (struct ethhdr *)skb->data;
3363 type = eth->h_proto;
3366 return vlan_get_protocol_and_depth(skb, type, depth);
3370 /* Take action when hardware reception checksum errors are detected. */
3372 static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3374 netdev_err(dev, "hw csum failure\n");
3375 skb_dump(KERN_ERR, skb, true);
3379 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3381 DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb);
3383 EXPORT_SYMBOL(netdev_rx_csum_fault);
3386 /* XXX: check that highmem exists at all on the given machine. */
3387 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3389 #ifdef CONFIG_HIGHMEM
3392 if (!(dev->features & NETIF_F_HIGHDMA)) {
3393 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3394 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3396 if (PageHighMem(skb_frag_page(frag)))
3404 /* If MPLS offload request, verify we are testing hardware MPLS features
3405 * instead of standard features for the netdev.
3407 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3408 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3409 netdev_features_t features,
3412 if (eth_p_mpls(type))
3413 features &= skb->dev->mpls_features;
3418 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3419 netdev_features_t features,
3426 static netdev_features_t harmonize_features(struct sk_buff *skb,
3427 netdev_features_t features)
3431 type = skb_network_protocol(skb, NULL);
3432 features = net_mpls_features(skb, features, type);
3434 if (skb->ip_summed != CHECKSUM_NONE &&
3435 !can_checksum_protocol(features, type)) {
3436 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3438 if (illegal_highdma(skb->dev, skb))
3439 features &= ~NETIF_F_SG;
3444 netdev_features_t passthru_features_check(struct sk_buff *skb,
3445 struct net_device *dev,
3446 netdev_features_t features)
3450 EXPORT_SYMBOL(passthru_features_check);
3452 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3453 struct net_device *dev,
3454 netdev_features_t features)
3456 return vlan_features_check(skb, features);
3459 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3460 struct net_device *dev,
3461 netdev_features_t features)
3463 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3465 if (gso_segs > READ_ONCE(dev->gso_max_segs))
3466 return features & ~NETIF_F_GSO_MASK;
3468 if (!skb_shinfo(skb)->gso_type) {
3469 skb_warn_bad_offload(skb);
3470 return features & ~NETIF_F_GSO_MASK;
3473 /* Support for GSO partial features requires software
3474 * intervention before we can actually process the packets
3475 * so we need to strip support for any partial features now
3476 * and we can pull them back in after we have partially
3477 * segmented the frame.
3479 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3480 features &= ~dev->gso_partial_features;
3482 /* Make sure to clear the IPv4 ID mangling feature if the
3483 * IPv4 header has the potential to be fragmented.
3485 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3486 struct iphdr *iph = skb->encapsulation ?
3487 inner_ip_hdr(skb) : ip_hdr(skb);
3489 if (!(iph->frag_off & htons(IP_DF)))
3490 features &= ~NETIF_F_TSO_MANGLEID;
3496 netdev_features_t netif_skb_features(struct sk_buff *skb)
3498 struct net_device *dev = skb->dev;
3499 netdev_features_t features = dev->features;
3501 if (skb_is_gso(skb))
3502 features = gso_features_check(skb, dev, features);
3504 /* If encapsulation offload request, verify we are testing
3505 * hardware encapsulation features instead of standard
3506 * features for the netdev
3508 if (skb->encapsulation)
3509 features &= dev->hw_enc_features;
3511 if (skb_vlan_tagged(skb))
3512 features = netdev_intersect_features(features,
3513 dev->vlan_features |
3514 NETIF_F_HW_VLAN_CTAG_TX |
3515 NETIF_F_HW_VLAN_STAG_TX);
3517 if (dev->netdev_ops->ndo_features_check)
3518 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3521 features &= dflt_features_check(skb, dev, features);
3523 return harmonize_features(skb, features);
3525 EXPORT_SYMBOL(netif_skb_features);
3527 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3528 struct netdev_queue *txq, bool more)
3533 if (dev_nit_active(dev))
3534 dev_queue_xmit_nit(skb, dev);
3537 trace_net_dev_start_xmit(skb, dev);
3538 rc = netdev_start_xmit(skb, dev, txq, more);
3539 trace_net_dev_xmit(skb, rc, dev, len);
3544 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3545 struct netdev_queue *txq, int *ret)
3547 struct sk_buff *skb = first;
3548 int rc = NETDEV_TX_OK;
3551 struct sk_buff *next = skb->next;
3553 skb_mark_not_on_list(skb);
3554 rc = xmit_one(skb, dev, txq, next != NULL);
3555 if (unlikely(!dev_xmit_complete(rc))) {
3561 if (netif_tx_queue_stopped(txq) && skb) {
3562 rc = NETDEV_TX_BUSY;
3572 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3573 netdev_features_t features)
3575 if (skb_vlan_tag_present(skb) &&
3576 !vlan_hw_offload_capable(features, skb->vlan_proto))
3577 skb = __vlan_hwaccel_push_inside(skb);
3581 int skb_csum_hwoffload_help(struct sk_buff *skb,
3582 const netdev_features_t features)
3584 if (unlikely(skb_csum_is_sctp(skb)))
3585 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3586 skb_crc32c_csum_help(skb);
3588 if (features & NETIF_F_HW_CSUM)
3591 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
3592 switch (skb->csum_offset) {
3593 case offsetof(struct tcphdr, check):
3594 case offsetof(struct udphdr, check):
3599 return skb_checksum_help(skb);
3601 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3603 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3605 netdev_features_t features;
3607 features = netif_skb_features(skb);
3608 skb = validate_xmit_vlan(skb, features);
3612 skb = sk_validate_xmit_skb(skb, dev);
3616 if (netif_needs_gso(skb, features)) {
3617 struct sk_buff *segs;
3619 segs = skb_gso_segment(skb, features);
3627 if (skb_needs_linearize(skb, features) &&
3628 __skb_linearize(skb))
3631 /* If packet is not checksummed and device does not
3632 * support checksumming for this protocol, complete
3633 * checksumming here.
3635 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3636 if (skb->encapsulation)
3637 skb_set_inner_transport_header(skb,
3638 skb_checksum_start_offset(skb));
3640 skb_set_transport_header(skb,
3641 skb_checksum_start_offset(skb));
3642 if (skb_csum_hwoffload_help(skb, features))
3647 skb = validate_xmit_xfrm(skb, features, again);
3654 dev_core_stats_tx_dropped_inc(dev);
3658 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3660 struct sk_buff *next, *head = NULL, *tail;
3662 for (; skb != NULL; skb = next) {
3664 skb_mark_not_on_list(skb);
3666 /* in case skb wont be segmented, point to itself */
3669 skb = validate_xmit_skb(skb, dev, again);
3677 /* If skb was segmented, skb->prev points to
3678 * the last segment. If not, it still contains skb.
3684 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3686 static void qdisc_pkt_len_init(struct sk_buff *skb)
3688 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3690 qdisc_skb_cb(skb)->pkt_len = skb->len;
3692 /* To get more precise estimation of bytes sent on wire,
3693 * we add to pkt_len the headers size of all segments
3695 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3696 u16 gso_segs = shinfo->gso_segs;
3697 unsigned int hdr_len;
3699 /* mac layer + network layer */
3700 hdr_len = skb_transport_offset(skb);
3702 /* + transport layer */
3703 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3704 const struct tcphdr *th;
3705 struct tcphdr _tcphdr;
3707 th = skb_header_pointer(skb, hdr_len,
3708 sizeof(_tcphdr), &_tcphdr);
3710 hdr_len += __tcp_hdrlen(th);
3712 struct udphdr _udphdr;
3714 if (skb_header_pointer(skb, hdr_len,
3715 sizeof(_udphdr), &_udphdr))
3716 hdr_len += sizeof(struct udphdr);
3719 if (shinfo->gso_type & SKB_GSO_DODGY)
3720 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3723 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3727 static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q,
3728 struct sk_buff **to_free,
3729 struct netdev_queue *txq)
3733 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK;
3734 if (rc == NET_XMIT_SUCCESS)
3735 trace_qdisc_enqueue(q, txq, skb);
3739 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3740 struct net_device *dev,
3741 struct netdev_queue *txq)
3743 spinlock_t *root_lock = qdisc_lock(q);
3744 struct sk_buff *to_free = NULL;
3748 qdisc_calculate_pkt_len(skb, q);
3750 if (q->flags & TCQ_F_NOLOCK) {
3751 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) &&
3752 qdisc_run_begin(q)) {
3753 /* Retest nolock_qdisc_is_empty() within the protection
3754 * of q->seqlock to protect from racing with requeuing.
3756 if (unlikely(!nolock_qdisc_is_empty(q))) {
3757 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3764 qdisc_bstats_cpu_update(q, skb);
3765 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) &&
3766 !nolock_qdisc_is_empty(q))
3770 return NET_XMIT_SUCCESS;
3773 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3777 if (unlikely(to_free))
3778 kfree_skb_list_reason(to_free,
3779 SKB_DROP_REASON_QDISC_DROP);
3784 * Heuristic to force contended enqueues to serialize on a
3785 * separate lock before trying to get qdisc main lock.
3786 * This permits qdisc->running owner to get the lock more
3787 * often and dequeue packets faster.
3788 * On PREEMPT_RT it is possible to preempt the qdisc owner during xmit
3789 * and then other tasks will only enqueue packets. The packets will be
3790 * sent after the qdisc owner is scheduled again. To prevent this
3791 * scenario the task always serialize on the lock.
3793 contended = qdisc_is_running(q) || IS_ENABLED(CONFIG_PREEMPT_RT);
3794 if (unlikely(contended))
3795 spin_lock(&q->busylock);
3797 spin_lock(root_lock);
3798 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3799 __qdisc_drop(skb, &to_free);
3801 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3802 qdisc_run_begin(q)) {
3804 * This is a work-conserving queue; there are no old skbs
3805 * waiting to be sent out; and the qdisc is not running -
3806 * xmit the skb directly.
3809 qdisc_bstats_update(q, skb);
3811 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3812 if (unlikely(contended)) {
3813 spin_unlock(&q->busylock);
3820 rc = NET_XMIT_SUCCESS;
3822 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3823 if (qdisc_run_begin(q)) {
3824 if (unlikely(contended)) {
3825 spin_unlock(&q->busylock);
3832 spin_unlock(root_lock);
3833 if (unlikely(to_free))
3834 kfree_skb_list_reason(to_free, SKB_DROP_REASON_QDISC_DROP);
3835 if (unlikely(contended))
3836 spin_unlock(&q->busylock);
3840 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3841 static void skb_update_prio(struct sk_buff *skb)
3843 const struct netprio_map *map;
3844 const struct sock *sk;
3845 unsigned int prioidx;
3849 map = rcu_dereference_bh(skb->dev->priomap);
3852 sk = skb_to_full_sk(skb);
3856 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3858 if (prioidx < map->priomap_len)
3859 skb->priority = map->priomap[prioidx];
3862 #define skb_update_prio(skb)
3866 * dev_loopback_xmit - loop back @skb
3867 * @net: network namespace this loopback is happening in
3868 * @sk: sk needed to be a netfilter okfn
3869 * @skb: buffer to transmit
3871 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3873 skb_reset_mac_header(skb);
3874 __skb_pull(skb, skb_network_offset(skb));
3875 skb->pkt_type = PACKET_LOOPBACK;
3876 if (skb->ip_summed == CHECKSUM_NONE)
3877 skb->ip_summed = CHECKSUM_UNNECESSARY;
3878 DEBUG_NET_WARN_ON_ONCE(!skb_dst(skb));
3883 EXPORT_SYMBOL(dev_loopback_xmit);
3885 #ifdef CONFIG_NET_EGRESS
3886 static struct netdev_queue *
3887 netdev_tx_queue_mapping(struct net_device *dev, struct sk_buff *skb)
3889 int qm = skb_get_queue_mapping(skb);
3891 return netdev_get_tx_queue(dev, netdev_cap_txqueue(dev, qm));
3894 static bool netdev_xmit_txqueue_skipped(void)
3896 return __this_cpu_read(softnet_data.xmit.skip_txqueue);
3899 void netdev_xmit_skip_txqueue(bool skip)
3901 __this_cpu_write(softnet_data.xmit.skip_txqueue, skip);
3903 EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
3904 #endif /* CONFIG_NET_EGRESS */
3906 #ifdef CONFIG_NET_XGRESS
3907 static int tc_run(struct tcx_entry *entry, struct sk_buff *skb)
3909 int ret = TC_ACT_UNSPEC;
3910 #ifdef CONFIG_NET_CLS_ACT
3911 struct mini_Qdisc *miniq = rcu_dereference_bh(entry->miniq);
3912 struct tcf_result res;
3917 tc_skb_cb(skb)->mru = 0;
3918 tc_skb_cb(skb)->post_ct = false;
3920 mini_qdisc_bstats_cpu_update(miniq, skb);
3921 ret = tcf_classify(skb, miniq->block, miniq->filter_list, &res, false);
3922 /* Only tcf related quirks below. */
3925 mini_qdisc_qstats_cpu_drop(miniq);
3928 case TC_ACT_RECLASSIFY:
3929 skb->tc_index = TC_H_MIN(res.classid);
3932 #endif /* CONFIG_NET_CLS_ACT */
3936 static DEFINE_STATIC_KEY_FALSE(tcx_needed_key);
3940 static_branch_inc(&tcx_needed_key);
3945 static_branch_dec(&tcx_needed_key);
3948 static __always_inline enum tcx_action_base
3949 tcx_run(const struct bpf_mprog_entry *entry, struct sk_buff *skb,
3950 const bool needs_mac)
3952 const struct bpf_mprog_fp *fp;
3953 const struct bpf_prog *prog;
3957 __skb_push(skb, skb->mac_len);
3958 bpf_mprog_foreach_prog(entry, fp, prog) {
3959 bpf_compute_data_pointers(skb);
3960 ret = bpf_prog_run(prog, skb);
3961 if (ret != TCX_NEXT)
3965 __skb_pull(skb, skb->mac_len);
3966 return tcx_action_code(skb, ret);
3969 static __always_inline struct sk_buff *
3970 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
3971 struct net_device *orig_dev, bool *another)
3973 struct bpf_mprog_entry *entry = rcu_dereference_bh(skb->dev->tcx_ingress);
3979 *ret = deliver_skb(skb, *pt_prev, orig_dev);
3983 qdisc_skb_cb(skb)->pkt_len = skb->len;
3984 tcx_set_ingress(skb, true);
3986 if (static_branch_unlikely(&tcx_needed_key)) {
3987 sch_ret = tcx_run(entry, skb, true);
3988 if (sch_ret != TC_ACT_UNSPEC)
3989 goto ingress_verdict;
3991 sch_ret = tc_run(tcx_entry(entry), skb);
3994 case TC_ACT_REDIRECT:
3995 /* skb_mac_header check was done by BPF, so we can safely
3996 * push the L2 header back before redirecting to another
3999 __skb_push(skb, skb->mac_len);
4000 if (skb_do_redirect(skb) == -EAGAIN) {
4001 __skb_pull(skb, skb->mac_len);
4005 *ret = NET_RX_SUCCESS;
4008 kfree_skb_reason(skb, SKB_DROP_REASON_TC_INGRESS);
4011 /* used by tc_run */
4017 case TC_ACT_CONSUMED:
4018 *ret = NET_RX_SUCCESS;
4025 static __always_inline struct sk_buff *
4026 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
4028 struct bpf_mprog_entry *entry = rcu_dereference_bh(dev->tcx_egress);
4034 /* qdisc_skb_cb(skb)->pkt_len & tcx_set_ingress() was
4035 * already set by the caller.
4037 if (static_branch_unlikely(&tcx_needed_key)) {
4038 sch_ret = tcx_run(entry, skb, false);
4039 if (sch_ret != TC_ACT_UNSPEC)
4040 goto egress_verdict;
4042 sch_ret = tc_run(tcx_entry(entry), skb);
4045 case TC_ACT_REDIRECT:
4046 /* No need to push/pop skb's mac_header here on egress! */
4047 skb_do_redirect(skb);
4048 *ret = NET_XMIT_SUCCESS;
4051 kfree_skb_reason(skb, SKB_DROP_REASON_TC_EGRESS);
4052 *ret = NET_XMIT_DROP;
4054 /* used by tc_run */
4058 *ret = NET_XMIT_SUCCESS;
4065 static __always_inline struct sk_buff *
4066 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4067 struct net_device *orig_dev, bool *another)
4072 static __always_inline struct sk_buff *
4073 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
4077 #endif /* CONFIG_NET_XGRESS */
4080 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
4081 struct xps_dev_maps *dev_maps, unsigned int tci)
4083 int tc = netdev_get_prio_tc_map(dev, skb->priority);
4084 struct xps_map *map;
4085 int queue_index = -1;
4087 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids)
4090 tci *= dev_maps->num_tc;
4093 map = rcu_dereference(dev_maps->attr_map[tci]);
4096 queue_index = map->queues[0];
4098 queue_index = map->queues[reciprocal_scale(
4099 skb_get_hash(skb), map->len)];
4100 if (unlikely(queue_index >= dev->real_num_tx_queues))
4107 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
4108 struct sk_buff *skb)
4111 struct xps_dev_maps *dev_maps;
4112 struct sock *sk = skb->sk;
4113 int queue_index = -1;
4115 if (!static_key_false(&xps_needed))
4119 if (!static_key_false(&xps_rxqs_needed))
4122 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]);
4124 int tci = sk_rx_queue_get(sk);
4127 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4132 if (queue_index < 0) {
4133 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]);
4135 unsigned int tci = skb->sender_cpu - 1;
4137 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4149 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
4150 struct net_device *sb_dev)
4154 EXPORT_SYMBOL(dev_pick_tx_zero);
4156 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
4157 struct net_device *sb_dev)
4159 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
4161 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
4163 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4164 struct net_device *sb_dev)
4166 struct sock *sk = skb->sk;
4167 int queue_index = sk_tx_queue_get(sk);
4169 sb_dev = sb_dev ? : dev;
4171 if (queue_index < 0 || skb->ooo_okay ||
4172 queue_index >= dev->real_num_tx_queues) {
4173 int new_index = get_xps_queue(dev, sb_dev, skb);
4176 new_index = skb_tx_hash(dev, sb_dev, skb);
4178 if (queue_index != new_index && sk &&
4180 rcu_access_pointer(sk->sk_dst_cache))
4181 sk_tx_queue_set(sk, new_index);
4183 queue_index = new_index;
4188 EXPORT_SYMBOL(netdev_pick_tx);
4190 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4191 struct sk_buff *skb,
4192 struct net_device *sb_dev)
4194 int queue_index = 0;
4197 u32 sender_cpu = skb->sender_cpu - 1;
4199 if (sender_cpu >= (u32)NR_CPUS)
4200 skb->sender_cpu = raw_smp_processor_id() + 1;
4203 if (dev->real_num_tx_queues != 1) {
4204 const struct net_device_ops *ops = dev->netdev_ops;
4206 if (ops->ndo_select_queue)
4207 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4209 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4211 queue_index = netdev_cap_txqueue(dev, queue_index);
4214 skb_set_queue_mapping(skb, queue_index);
4215 return netdev_get_tx_queue(dev, queue_index);
4219 * __dev_queue_xmit() - transmit a buffer
4220 * @skb: buffer to transmit
4221 * @sb_dev: suboordinate device used for L2 forwarding offload
4223 * Queue a buffer for transmission to a network device. The caller must
4224 * have set the device and priority and built the buffer before calling
4225 * this function. The function can be called from an interrupt.
4227 * When calling this method, interrupts MUST be enabled. This is because
4228 * the BH enable code must have IRQs enabled so that it will not deadlock.
4230 * Regardless of the return value, the skb is consumed, so it is currently
4231 * difficult to retry a send to this method. (You can bump the ref count
4232 * before sending to hold a reference for retry if you are careful.)
4235 * * 0 - buffer successfully transmitted
4236 * * positive qdisc return code - NET_XMIT_DROP etc.
4237 * * negative errno - other errors
4239 int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4241 struct net_device *dev = skb->dev;
4242 struct netdev_queue *txq = NULL;
4247 skb_reset_mac_header(skb);
4248 skb_assert_len(skb);
4250 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4251 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED);
4253 /* Disable soft irqs for various locks below. Also
4254 * stops preemption for RCU.
4258 skb_update_prio(skb);
4260 qdisc_pkt_len_init(skb);
4261 tcx_set_ingress(skb, false);
4262 #ifdef CONFIG_NET_EGRESS
4263 if (static_branch_unlikely(&egress_needed_key)) {
4264 if (nf_hook_egress_active()) {
4265 skb = nf_hook_egress(skb, &rc, dev);
4270 netdev_xmit_skip_txqueue(false);
4272 nf_skip_egress(skb, true);
4273 skb = sch_handle_egress(skb, &rc, dev);
4276 nf_skip_egress(skb, false);
4278 if (netdev_xmit_txqueue_skipped())
4279 txq = netdev_tx_queue_mapping(dev, skb);
4282 /* If device/qdisc don't need skb->dst, release it right now while
4283 * its hot in this cpu cache.
4285 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4291 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4293 q = rcu_dereference_bh(txq->qdisc);
4295 trace_net_dev_queue(skb);
4297 rc = __dev_xmit_skb(skb, q, dev, txq);
4301 /* The device has no queue. Common case for software devices:
4302 * loopback, all the sorts of tunnels...
4304 * Really, it is unlikely that netif_tx_lock protection is necessary
4305 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4307 * However, it is possible, that they rely on protection
4310 * Check this and shot the lock. It is not prone from deadlocks.
4311 *Either shot noqueue qdisc, it is even simpler 8)
4313 if (dev->flags & IFF_UP) {
4314 int cpu = smp_processor_id(); /* ok because BHs are off */
4316 /* Other cpus might concurrently change txq->xmit_lock_owner
4317 * to -1 or to their cpu id, but not to our id.
4319 if (READ_ONCE(txq->xmit_lock_owner) != cpu) {
4320 if (dev_xmit_recursion())
4321 goto recursion_alert;
4323 skb = validate_xmit_skb(skb, dev, &again);
4327 HARD_TX_LOCK(dev, txq, cpu);
4329 if (!netif_xmit_stopped(txq)) {
4330 dev_xmit_recursion_inc();
4331 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4332 dev_xmit_recursion_dec();
4333 if (dev_xmit_complete(rc)) {
4334 HARD_TX_UNLOCK(dev, txq);
4338 HARD_TX_UNLOCK(dev, txq);
4339 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4342 /* Recursion is detected! It is possible,
4346 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4352 rcu_read_unlock_bh();
4354 dev_core_stats_tx_dropped_inc(dev);
4355 kfree_skb_list(skb);
4358 rcu_read_unlock_bh();
4361 EXPORT_SYMBOL(__dev_queue_xmit);
4363 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4365 struct net_device *dev = skb->dev;
4366 struct sk_buff *orig_skb = skb;
4367 struct netdev_queue *txq;
4368 int ret = NETDEV_TX_BUSY;
4371 if (unlikely(!netif_running(dev) ||
4372 !netif_carrier_ok(dev)))
4375 skb = validate_xmit_skb_list(skb, dev, &again);
4376 if (skb != orig_skb)
4379 skb_set_queue_mapping(skb, queue_id);
4380 txq = skb_get_tx_queue(dev, skb);
4384 dev_xmit_recursion_inc();
4385 HARD_TX_LOCK(dev, txq, smp_processor_id());
4386 if (!netif_xmit_frozen_or_drv_stopped(txq))
4387 ret = netdev_start_xmit(skb, dev, txq, false);
4388 HARD_TX_UNLOCK(dev, txq);
4389 dev_xmit_recursion_dec();
4394 dev_core_stats_tx_dropped_inc(dev);
4395 kfree_skb_list(skb);
4396 return NET_XMIT_DROP;
4398 EXPORT_SYMBOL(__dev_direct_xmit);
4400 /*************************************************************************
4402 *************************************************************************/
4404 int netdev_max_backlog __read_mostly = 1000;
4405 EXPORT_SYMBOL(netdev_max_backlog);
4407 int netdev_tstamp_prequeue __read_mostly = 1;
4408 unsigned int sysctl_skb_defer_max __read_mostly = 64;
4409 int netdev_budget __read_mostly = 300;
4410 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4411 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4412 int weight_p __read_mostly = 64; /* old backlog weight */
4413 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4414 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4415 int dev_rx_weight __read_mostly = 64;
4416 int dev_tx_weight __read_mostly = 64;
4418 /* Called with irq disabled */
4419 static inline void ____napi_schedule(struct softnet_data *sd,
4420 struct napi_struct *napi)
4422 struct task_struct *thread;
4424 lockdep_assert_irqs_disabled();
4426 if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
4427 /* Paired with smp_mb__before_atomic() in
4428 * napi_enable()/dev_set_threaded().
4429 * Use READ_ONCE() to guarantee a complete
4430 * read on napi->thread. Only call
4431 * wake_up_process() when it's not NULL.
4433 thread = READ_ONCE(napi->thread);
4435 /* Avoid doing set_bit() if the thread is in
4436 * INTERRUPTIBLE state, cause napi_thread_wait()
4437 * makes sure to proceed with napi polling
4438 * if the thread is explicitly woken from here.
4440 if (READ_ONCE(thread->__state) != TASK_INTERRUPTIBLE)
4441 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
4442 wake_up_process(thread);
4447 list_add_tail(&napi->poll_list, &sd->poll_list);
4448 WRITE_ONCE(napi->list_owner, smp_processor_id());
4449 /* If not called from net_rx_action()
4450 * we have to raise NET_RX_SOFTIRQ.
4452 if (!sd->in_net_rx_action)
4453 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4458 /* One global table that all flow-based protocols share. */
4459 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4460 EXPORT_SYMBOL(rps_sock_flow_table);
4461 u32 rps_cpu_mask __read_mostly;
4462 EXPORT_SYMBOL(rps_cpu_mask);
4464 struct static_key_false rps_needed __read_mostly;
4465 EXPORT_SYMBOL(rps_needed);
4466 struct static_key_false rfs_needed __read_mostly;
4467 EXPORT_SYMBOL(rfs_needed);
4469 static struct rps_dev_flow *
4470 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4471 struct rps_dev_flow *rflow, u16 next_cpu)
4473 if (next_cpu < nr_cpu_ids) {
4474 #ifdef CONFIG_RFS_ACCEL
4475 struct netdev_rx_queue *rxqueue;
4476 struct rps_dev_flow_table *flow_table;
4477 struct rps_dev_flow *old_rflow;
4482 /* Should we steer this flow to a different hardware queue? */
4483 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4484 !(dev->features & NETIF_F_NTUPLE))
4486 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4487 if (rxq_index == skb_get_rx_queue(skb))
4490 rxqueue = dev->_rx + rxq_index;
4491 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4494 flow_id = skb_get_hash(skb) & flow_table->mask;
4495 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4496 rxq_index, flow_id);
4500 rflow = &flow_table->flows[flow_id];
4502 if (old_rflow->filter == rflow->filter)
4503 old_rflow->filter = RPS_NO_FILTER;
4507 per_cpu(softnet_data, next_cpu).input_queue_head;
4510 rflow->cpu = next_cpu;
4515 * get_rps_cpu is called from netif_receive_skb and returns the target
4516 * CPU from the RPS map of the receiving queue for a given skb.
4517 * rcu_read_lock must be held on entry.
4519 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4520 struct rps_dev_flow **rflowp)
4522 const struct rps_sock_flow_table *sock_flow_table;
4523 struct netdev_rx_queue *rxqueue = dev->_rx;
4524 struct rps_dev_flow_table *flow_table;
4525 struct rps_map *map;
4530 if (skb_rx_queue_recorded(skb)) {
4531 u16 index = skb_get_rx_queue(skb);
4533 if (unlikely(index >= dev->real_num_rx_queues)) {
4534 WARN_ONCE(dev->real_num_rx_queues > 1,
4535 "%s received packet on queue %u, but number "
4536 "of RX queues is %u\n",
4537 dev->name, index, dev->real_num_rx_queues);
4543 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4545 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4546 map = rcu_dereference(rxqueue->rps_map);
4547 if (!flow_table && !map)
4550 skb_reset_network_header(skb);
4551 hash = skb_get_hash(skb);
4555 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4556 if (flow_table && sock_flow_table) {
4557 struct rps_dev_flow *rflow;
4561 /* First check into global flow table if there is a match.
4562 * This READ_ONCE() pairs with WRITE_ONCE() from rps_record_sock_flow().
4564 ident = READ_ONCE(sock_flow_table->ents[hash & sock_flow_table->mask]);
4565 if ((ident ^ hash) & ~rps_cpu_mask)
4568 next_cpu = ident & rps_cpu_mask;
4570 /* OK, now we know there is a match,
4571 * we can look at the local (per receive queue) flow table
4573 rflow = &flow_table->flows[hash & flow_table->mask];
4577 * If the desired CPU (where last recvmsg was done) is
4578 * different from current CPU (one in the rx-queue flow
4579 * table entry), switch if one of the following holds:
4580 * - Current CPU is unset (>= nr_cpu_ids).
4581 * - Current CPU is offline.
4582 * - The current CPU's queue tail has advanced beyond the
4583 * last packet that was enqueued using this table entry.
4584 * This guarantees that all previous packets for the flow
4585 * have been dequeued, thus preserving in order delivery.
4587 if (unlikely(tcpu != next_cpu) &&
4588 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4589 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4590 rflow->last_qtail)) >= 0)) {
4592 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4595 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4605 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4606 if (cpu_online(tcpu)) {
4616 #ifdef CONFIG_RFS_ACCEL
4619 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4620 * @dev: Device on which the filter was set
4621 * @rxq_index: RX queue index
4622 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4623 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4625 * Drivers that implement ndo_rx_flow_steer() should periodically call
4626 * this function for each installed filter and remove the filters for
4627 * which it returns %true.
4629 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4630 u32 flow_id, u16 filter_id)
4632 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4633 struct rps_dev_flow_table *flow_table;
4634 struct rps_dev_flow *rflow;
4639 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4640 if (flow_table && flow_id <= flow_table->mask) {
4641 rflow = &flow_table->flows[flow_id];
4642 cpu = READ_ONCE(rflow->cpu);
4643 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4644 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4645 rflow->last_qtail) <
4646 (int)(10 * flow_table->mask)))
4652 EXPORT_SYMBOL(rps_may_expire_flow);
4654 #endif /* CONFIG_RFS_ACCEL */
4656 /* Called from hardirq (IPI) context */
4657 static void rps_trigger_softirq(void *data)
4659 struct softnet_data *sd = data;
4661 ____napi_schedule(sd, &sd->backlog);
4665 #endif /* CONFIG_RPS */
4667 /* Called from hardirq (IPI) context */
4668 static void trigger_rx_softirq(void *data)
4670 struct softnet_data *sd = data;
4672 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4673 smp_store_release(&sd->defer_ipi_scheduled, 0);
4677 * After we queued a packet into sd->input_pkt_queue,
4678 * we need to make sure this queue is serviced soon.
4680 * - If this is another cpu queue, link it to our rps_ipi_list,
4681 * and make sure we will process rps_ipi_list from net_rx_action().
4683 * - If this is our own queue, NAPI schedule our backlog.
4684 * Note that this also raises NET_RX_SOFTIRQ.
4686 static void napi_schedule_rps(struct softnet_data *sd)
4688 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4692 sd->rps_ipi_next = mysd->rps_ipi_list;
4693 mysd->rps_ipi_list = sd;
4695 /* If not called from net_rx_action() or napi_threaded_poll()
4696 * we have to raise NET_RX_SOFTIRQ.
4698 if (!mysd->in_net_rx_action && !mysd->in_napi_threaded_poll)
4699 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4702 #endif /* CONFIG_RPS */
4703 __napi_schedule_irqoff(&mysd->backlog);
4706 #ifdef CONFIG_NET_FLOW_LIMIT
4707 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4710 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4712 #ifdef CONFIG_NET_FLOW_LIMIT
4713 struct sd_flow_limit *fl;
4714 struct softnet_data *sd;
4715 unsigned int old_flow, new_flow;
4717 if (qlen < (READ_ONCE(netdev_max_backlog) >> 1))
4720 sd = this_cpu_ptr(&softnet_data);
4723 fl = rcu_dereference(sd->flow_limit);
4725 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4726 old_flow = fl->history[fl->history_head];
4727 fl->history[fl->history_head] = new_flow;
4730 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4732 if (likely(fl->buckets[old_flow]))
4733 fl->buckets[old_flow]--;
4735 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4747 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4748 * queue (may be a remote CPU queue).
4750 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4751 unsigned int *qtail)
4753 enum skb_drop_reason reason;
4754 struct softnet_data *sd;
4755 unsigned long flags;
4758 reason = SKB_DROP_REASON_NOT_SPECIFIED;
4759 sd = &per_cpu(softnet_data, cpu);
4761 rps_lock_irqsave(sd, &flags);
4762 if (!netif_running(skb->dev))
4764 qlen = skb_queue_len(&sd->input_pkt_queue);
4765 if (qlen <= READ_ONCE(netdev_max_backlog) && !skb_flow_limit(skb, qlen)) {
4768 __skb_queue_tail(&sd->input_pkt_queue, skb);
4769 input_queue_tail_incr_save(sd, qtail);
4770 rps_unlock_irq_restore(sd, &flags);
4771 return NET_RX_SUCCESS;
4774 /* Schedule NAPI for backlog device
4775 * We can use non atomic operation since we own the queue lock
4777 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state))
4778 napi_schedule_rps(sd);
4781 reason = SKB_DROP_REASON_CPU_BACKLOG;
4785 rps_unlock_irq_restore(sd, &flags);
4787 dev_core_stats_rx_dropped_inc(skb->dev);
4788 kfree_skb_reason(skb, reason);
4792 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4794 struct net_device *dev = skb->dev;
4795 struct netdev_rx_queue *rxqueue;
4799 if (skb_rx_queue_recorded(skb)) {
4800 u16 index = skb_get_rx_queue(skb);
4802 if (unlikely(index >= dev->real_num_rx_queues)) {
4803 WARN_ONCE(dev->real_num_rx_queues > 1,
4804 "%s received packet on queue %u, but number "
4805 "of RX queues is %u\n",
4806 dev->name, index, dev->real_num_rx_queues);
4808 return rxqueue; /* Return first rxqueue */
4815 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp,
4816 struct bpf_prog *xdp_prog)
4818 void *orig_data, *orig_data_end, *hard_start;
4819 struct netdev_rx_queue *rxqueue;
4820 bool orig_bcast, orig_host;
4821 u32 mac_len, frame_sz;
4822 __be16 orig_eth_type;
4827 /* The XDP program wants to see the packet starting at the MAC
4830 mac_len = skb->data - skb_mac_header(skb);
4831 hard_start = skb->data - skb_headroom(skb);
4833 /* SKB "head" area always have tailroom for skb_shared_info */
4834 frame_sz = (void *)skb_end_pointer(skb) - hard_start;
4835 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4837 rxqueue = netif_get_rxqueue(skb);
4838 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq);
4839 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len,
4840 skb_headlen(skb) + mac_len, true);
4842 orig_data_end = xdp->data_end;
4843 orig_data = xdp->data;
4844 eth = (struct ethhdr *)xdp->data;
4845 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr);
4846 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4847 orig_eth_type = eth->h_proto;
4849 act = bpf_prog_run_xdp(xdp_prog, xdp);
4851 /* check if bpf_xdp_adjust_head was used */
4852 off = xdp->data - orig_data;
4855 __skb_pull(skb, off);
4857 __skb_push(skb, -off);
4859 skb->mac_header += off;
4860 skb_reset_network_header(skb);
4863 /* check if bpf_xdp_adjust_tail was used */
4864 off = xdp->data_end - orig_data_end;
4866 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4867 skb->len += off; /* positive on grow, negative on shrink */
4870 /* check if XDP changed eth hdr such SKB needs update */
4871 eth = (struct ethhdr *)xdp->data;
4872 if ((orig_eth_type != eth->h_proto) ||
4873 (orig_host != ether_addr_equal_64bits(eth->h_dest,
4874 skb->dev->dev_addr)) ||
4875 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4876 __skb_push(skb, ETH_HLEN);
4877 skb->pkt_type = PACKET_HOST;
4878 skb->protocol = eth_type_trans(skb, skb->dev);
4881 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull
4882 * before calling us again on redirect path. We do not call do_redirect
4883 * as we leave that up to the caller.
4885 * Caller is responsible for managing lifetime of skb (i.e. calling
4886 * kfree_skb in response to actions it cannot handle/XDP_DROP).
4891 __skb_push(skb, mac_len);
4894 metalen = xdp->data - xdp->data_meta;
4896 skb_metadata_set(skb, metalen);
4903 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4904 struct xdp_buff *xdp,
4905 struct bpf_prog *xdp_prog)
4909 /* Reinjected packets coming from act_mirred or similar should
4910 * not get XDP generic processing.
4912 if (skb_is_redirected(skb))
4915 /* XDP packets must be linear and must have sufficient headroom
4916 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4917 * native XDP provides, thus we need to do it here as well.
4919 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4920 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4921 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4922 int troom = skb->tail + skb->data_len - skb->end;
4924 /* In case we have to go down the path and also linearize,
4925 * then lets do the pskb_expand_head() work just once here.
4927 if (pskb_expand_head(skb,
4928 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4929 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4931 if (skb_linearize(skb))
4935 act = bpf_prog_run_generic_xdp(skb, xdp, xdp_prog);
4942 bpf_warn_invalid_xdp_action(skb->dev, xdp_prog, act);
4945 trace_xdp_exception(skb->dev, xdp_prog, act);
4956 /* When doing generic XDP we have to bypass the qdisc layer and the
4957 * network taps in order to match in-driver-XDP behavior. This also means
4958 * that XDP packets are able to starve other packets going through a qdisc,
4959 * and DDOS attacks will be more effective. In-driver-XDP use dedicated TX
4960 * queues, so they do not have this starvation issue.
4962 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4964 struct net_device *dev = skb->dev;
4965 struct netdev_queue *txq;
4966 bool free_skb = true;
4969 txq = netdev_core_pick_tx(dev, skb, NULL);
4970 cpu = smp_processor_id();
4971 HARD_TX_LOCK(dev, txq, cpu);
4972 if (!netif_xmit_frozen_or_drv_stopped(txq)) {
4973 rc = netdev_start_xmit(skb, dev, txq, 0);
4974 if (dev_xmit_complete(rc))
4977 HARD_TX_UNLOCK(dev, txq);
4979 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4980 dev_core_stats_tx_dropped_inc(dev);
4985 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4987 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4990 struct xdp_buff xdp;
4994 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4995 if (act != XDP_PASS) {
4998 err = xdp_do_generic_redirect(skb->dev, skb,
5004 generic_xdp_tx(skb, xdp_prog);
5012 kfree_skb_reason(skb, SKB_DROP_REASON_XDP);
5015 EXPORT_SYMBOL_GPL(do_xdp_generic);
5017 static int netif_rx_internal(struct sk_buff *skb)
5021 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5023 trace_netif_rx(skb);
5026 if (static_branch_unlikely(&rps_needed)) {
5027 struct rps_dev_flow voidflow, *rflow = &voidflow;
5032 cpu = get_rps_cpu(skb->dev, skb, &rflow);
5034 cpu = smp_processor_id();
5036 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5044 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail);
5050 * __netif_rx - Slightly optimized version of netif_rx
5051 * @skb: buffer to post
5053 * This behaves as netif_rx except that it does not disable bottom halves.
5054 * As a result this function may only be invoked from the interrupt context
5055 * (either hard or soft interrupt).
5057 int __netif_rx(struct sk_buff *skb)
5061 lockdep_assert_once(hardirq_count() | softirq_count());
5063 trace_netif_rx_entry(skb);
5064 ret = netif_rx_internal(skb);
5065 trace_netif_rx_exit(ret);
5068 EXPORT_SYMBOL(__netif_rx);
5071 * netif_rx - post buffer to the network code
5072 * @skb: buffer to post
5074 * This function receives a packet from a device driver and queues it for
5075 * the upper (protocol) levels to process via the backlog NAPI device. It
5076 * always succeeds. The buffer may be dropped during processing for
5077 * congestion control or by the protocol layers.
5078 * The network buffer is passed via the backlog NAPI device. Modern NIC
5079 * driver should use NAPI and GRO.
5080 * This function can used from interrupt and from process context. The
5081 * caller from process context must not disable interrupts before invoking
5085 * NET_RX_SUCCESS (no congestion)
5086 * NET_RX_DROP (packet was dropped)
5089 int netif_rx(struct sk_buff *skb)
5091 bool need_bh_off = !(hardirq_count() | softirq_count());
5096 trace_netif_rx_entry(skb);
5097 ret = netif_rx_internal(skb);
5098 trace_netif_rx_exit(ret);
5103 EXPORT_SYMBOL(netif_rx);
5105 static __latent_entropy void net_tx_action(struct softirq_action *h)
5107 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
5109 if (sd->completion_queue) {
5110 struct sk_buff *clist;
5112 local_irq_disable();
5113 clist = sd->completion_queue;
5114 sd->completion_queue = NULL;
5118 struct sk_buff *skb = clist;
5120 clist = clist->next;
5122 WARN_ON(refcount_read(&skb->users));
5123 if (likely(get_kfree_skb_cb(skb)->reason == SKB_CONSUMED))
5124 trace_consume_skb(skb, net_tx_action);
5126 trace_kfree_skb(skb, net_tx_action,
5127 get_kfree_skb_cb(skb)->reason);
5129 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
5132 __napi_kfree_skb(skb,
5133 get_kfree_skb_cb(skb)->reason);
5137 if (sd->output_queue) {
5140 local_irq_disable();
5141 head = sd->output_queue;
5142 sd->output_queue = NULL;
5143 sd->output_queue_tailp = &sd->output_queue;
5149 struct Qdisc *q = head;
5150 spinlock_t *root_lock = NULL;
5152 head = head->next_sched;
5154 /* We need to make sure head->next_sched is read
5155 * before clearing __QDISC_STATE_SCHED
5157 smp_mb__before_atomic();
5159 if (!(q->flags & TCQ_F_NOLOCK)) {
5160 root_lock = qdisc_lock(q);
5161 spin_lock(root_lock);
5162 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
5164 /* There is a synchronize_net() between
5165 * STATE_DEACTIVATED flag being set and
5166 * qdisc_reset()/some_qdisc_is_busy() in
5167 * dev_deactivate(), so we can safely bail out
5168 * early here to avoid data race between
5169 * qdisc_deactivate() and some_qdisc_is_busy()
5170 * for lockless qdisc.
5172 clear_bit(__QDISC_STATE_SCHED, &q->state);
5176 clear_bit(__QDISC_STATE_SCHED, &q->state);
5179 spin_unlock(root_lock);
5185 xfrm_dev_backlog(sd);
5188 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
5189 /* This hook is defined here for ATM LANE */
5190 int (*br_fdb_test_addr_hook)(struct net_device *dev,
5191 unsigned char *addr) __read_mostly;
5192 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
5196 * netdev_is_rx_handler_busy - check if receive handler is registered
5197 * @dev: device to check
5199 * Check if a receive handler is already registered for a given device.
5200 * Return true if there one.
5202 * The caller must hold the rtnl_mutex.
5204 bool netdev_is_rx_handler_busy(struct net_device *dev)
5207 return dev && rtnl_dereference(dev->rx_handler);
5209 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5212 * netdev_rx_handler_register - register receive handler
5213 * @dev: device to register a handler for
5214 * @rx_handler: receive handler to register
5215 * @rx_handler_data: data pointer that is used by rx handler
5217 * Register a receive handler for a device. This handler will then be
5218 * called from __netif_receive_skb. A negative errno code is returned
5221 * The caller must hold the rtnl_mutex.
5223 * For a general description of rx_handler, see enum rx_handler_result.
5225 int netdev_rx_handler_register(struct net_device *dev,
5226 rx_handler_func_t *rx_handler,
5227 void *rx_handler_data)
5229 if (netdev_is_rx_handler_busy(dev))
5232 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5235 /* Note: rx_handler_data must be set before rx_handler */
5236 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5237 rcu_assign_pointer(dev->rx_handler, rx_handler);
5241 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5244 * netdev_rx_handler_unregister - unregister receive handler
5245 * @dev: device to unregister a handler from
5247 * Unregister a receive handler from a device.
5249 * The caller must hold the rtnl_mutex.
5251 void netdev_rx_handler_unregister(struct net_device *dev)
5255 RCU_INIT_POINTER(dev->rx_handler, NULL);
5256 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5257 * section has a guarantee to see a non NULL rx_handler_data
5261 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5263 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5266 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5267 * the special handling of PFMEMALLOC skbs.
5269 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5271 switch (skb->protocol) {
5272 case htons(ETH_P_ARP):
5273 case htons(ETH_P_IP):
5274 case htons(ETH_P_IPV6):
5275 case htons(ETH_P_8021Q):
5276 case htons(ETH_P_8021AD):
5283 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5284 int *ret, struct net_device *orig_dev)
5286 if (nf_hook_ingress_active(skb)) {
5290 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5295 ingress_retval = nf_hook_ingress(skb);
5297 return ingress_retval;
5302 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5303 struct packet_type **ppt_prev)
5305 struct packet_type *ptype, *pt_prev;
5306 rx_handler_func_t *rx_handler;
5307 struct sk_buff *skb = *pskb;
5308 struct net_device *orig_dev;
5309 bool deliver_exact = false;
5310 int ret = NET_RX_DROP;
5313 net_timestamp_check(!READ_ONCE(netdev_tstamp_prequeue), skb);
5315 trace_netif_receive_skb(skb);
5317 orig_dev = skb->dev;
5319 skb_reset_network_header(skb);
5320 if (!skb_transport_header_was_set(skb))
5321 skb_reset_transport_header(skb);
5322 skb_reset_mac_len(skb);
5327 skb->skb_iif = skb->dev->ifindex;
5329 __this_cpu_inc(softnet_data.processed);
5331 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5335 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5338 if (ret2 != XDP_PASS) {
5344 if (eth_type_vlan(skb->protocol)) {
5345 skb = skb_vlan_untag(skb);
5350 if (skb_skip_tc_classify(skb))
5356 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5358 ret = deliver_skb(skb, pt_prev, orig_dev);
5362 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5364 ret = deliver_skb(skb, pt_prev, orig_dev);
5369 #ifdef CONFIG_NET_INGRESS
5370 if (static_branch_unlikely(&ingress_needed_key)) {
5371 bool another = false;
5373 nf_skip_egress(skb, true);
5374 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5381 nf_skip_egress(skb, false);
5382 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5386 skb_reset_redirect(skb);
5388 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5391 if (skb_vlan_tag_present(skb)) {
5393 ret = deliver_skb(skb, pt_prev, orig_dev);
5396 if (vlan_do_receive(&skb))
5398 else if (unlikely(!skb))
5402 rx_handler = rcu_dereference(skb->dev->rx_handler);
5405 ret = deliver_skb(skb, pt_prev, orig_dev);
5408 switch (rx_handler(&skb)) {
5409 case RX_HANDLER_CONSUMED:
5410 ret = NET_RX_SUCCESS;
5412 case RX_HANDLER_ANOTHER:
5414 case RX_HANDLER_EXACT:
5415 deliver_exact = true;
5417 case RX_HANDLER_PASS:
5424 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5426 if (skb_vlan_tag_get_id(skb)) {
5427 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5430 skb->pkt_type = PACKET_OTHERHOST;
5431 } else if (eth_type_vlan(skb->protocol)) {
5432 /* Outer header is 802.1P with vlan 0, inner header is
5433 * 802.1Q or 802.1AD and vlan_do_receive() above could
5434 * not find vlan dev for vlan id 0.
5436 __vlan_hwaccel_clear_tag(skb);
5437 skb = skb_vlan_untag(skb);
5440 if (vlan_do_receive(&skb))
5441 /* After stripping off 802.1P header with vlan 0
5442 * vlan dev is found for inner header.
5445 else if (unlikely(!skb))
5448 /* We have stripped outer 802.1P vlan 0 header.
5449 * But could not find vlan dev.
5450 * check again for vlan id to set OTHERHOST.
5454 /* Note: we might in the future use prio bits
5455 * and set skb->priority like in vlan_do_receive()
5456 * For the time being, just ignore Priority Code Point
5458 __vlan_hwaccel_clear_tag(skb);
5461 type = skb->protocol;
5463 /* deliver only exact match when indicated */
5464 if (likely(!deliver_exact)) {
5465 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5466 &ptype_base[ntohs(type) &
5470 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5471 &orig_dev->ptype_specific);
5473 if (unlikely(skb->dev != orig_dev)) {
5474 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5475 &skb->dev->ptype_specific);
5479 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5481 *ppt_prev = pt_prev;
5485 dev_core_stats_rx_dropped_inc(skb->dev);
5487 dev_core_stats_rx_nohandler_inc(skb->dev);
5488 kfree_skb_reason(skb, SKB_DROP_REASON_UNHANDLED_PROTO);
5489 /* Jamal, now you will not able to escape explaining
5490 * me how you were going to use this. :-)
5496 /* The invariant here is that if *ppt_prev is not NULL
5497 * then skb should also be non-NULL.
5499 * Apparently *ppt_prev assignment above holds this invariant due to
5500 * skb dereferencing near it.
5506 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5508 struct net_device *orig_dev = skb->dev;
5509 struct packet_type *pt_prev = NULL;
5512 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5514 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5515 skb->dev, pt_prev, orig_dev);
5520 * netif_receive_skb_core - special purpose version of netif_receive_skb
5521 * @skb: buffer to process
5523 * More direct receive version of netif_receive_skb(). It should
5524 * only be used by callers that have a need to skip RPS and Generic XDP.
5525 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5527 * This function may only be called from softirq context and interrupts
5528 * should be enabled.
5530 * Return values (usually ignored):
5531 * NET_RX_SUCCESS: no congestion
5532 * NET_RX_DROP: packet was dropped
5534 int netif_receive_skb_core(struct sk_buff *skb)
5539 ret = __netif_receive_skb_one_core(skb, false);
5544 EXPORT_SYMBOL(netif_receive_skb_core);
5546 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5547 struct packet_type *pt_prev,
5548 struct net_device *orig_dev)
5550 struct sk_buff *skb, *next;
5554 if (list_empty(head))
5556 if (pt_prev->list_func != NULL)
5557 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5558 ip_list_rcv, head, pt_prev, orig_dev);
5560 list_for_each_entry_safe(skb, next, head, list) {
5561 skb_list_del_init(skb);
5562 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5566 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5568 /* Fast-path assumptions:
5569 * - There is no RX handler.
5570 * - Only one packet_type matches.
5571 * If either of these fails, we will end up doing some per-packet
5572 * processing in-line, then handling the 'last ptype' for the whole
5573 * sublist. This can't cause out-of-order delivery to any single ptype,
5574 * because the 'last ptype' must be constant across the sublist, and all
5575 * other ptypes are handled per-packet.
5577 /* Current (common) ptype of sublist */
5578 struct packet_type *pt_curr = NULL;
5579 /* Current (common) orig_dev of sublist */
5580 struct net_device *od_curr = NULL;
5581 struct list_head sublist;
5582 struct sk_buff *skb, *next;
5584 INIT_LIST_HEAD(&sublist);
5585 list_for_each_entry_safe(skb, next, head, list) {
5586 struct net_device *orig_dev = skb->dev;
5587 struct packet_type *pt_prev = NULL;
5589 skb_list_del_init(skb);
5590 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5593 if (pt_curr != pt_prev || od_curr != orig_dev) {
5594 /* dispatch old sublist */
5595 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5596 /* start new sublist */
5597 INIT_LIST_HEAD(&sublist);
5601 list_add_tail(&skb->list, &sublist);
5604 /* dispatch final sublist */
5605 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5608 static int __netif_receive_skb(struct sk_buff *skb)
5612 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5613 unsigned int noreclaim_flag;
5616 * PFMEMALLOC skbs are special, they should
5617 * - be delivered to SOCK_MEMALLOC sockets only
5618 * - stay away from userspace
5619 * - have bounded memory usage
5621 * Use PF_MEMALLOC as this saves us from propagating the allocation
5622 * context down to all allocation sites.
5624 noreclaim_flag = memalloc_noreclaim_save();
5625 ret = __netif_receive_skb_one_core(skb, true);
5626 memalloc_noreclaim_restore(noreclaim_flag);
5628 ret = __netif_receive_skb_one_core(skb, false);
5633 static void __netif_receive_skb_list(struct list_head *head)
5635 unsigned long noreclaim_flag = 0;
5636 struct sk_buff *skb, *next;
5637 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5639 list_for_each_entry_safe(skb, next, head, list) {
5640 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5641 struct list_head sublist;
5643 /* Handle the previous sublist */
5644 list_cut_before(&sublist, head, &skb->list);
5645 if (!list_empty(&sublist))
5646 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5647 pfmemalloc = !pfmemalloc;
5648 /* See comments in __netif_receive_skb */
5650 noreclaim_flag = memalloc_noreclaim_save();
5652 memalloc_noreclaim_restore(noreclaim_flag);
5655 /* Handle the remaining sublist */
5656 if (!list_empty(head))
5657 __netif_receive_skb_list_core(head, pfmemalloc);
5658 /* Restore pflags */
5660 memalloc_noreclaim_restore(noreclaim_flag);
5663 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5665 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5666 struct bpf_prog *new = xdp->prog;
5669 switch (xdp->command) {
5670 case XDP_SETUP_PROG:
5671 rcu_assign_pointer(dev->xdp_prog, new);
5676 static_branch_dec(&generic_xdp_needed_key);
5677 } else if (new && !old) {
5678 static_branch_inc(&generic_xdp_needed_key);
5679 dev_disable_lro(dev);
5680 dev_disable_gro_hw(dev);
5692 static int netif_receive_skb_internal(struct sk_buff *skb)
5696 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5698 if (skb_defer_rx_timestamp(skb))
5699 return NET_RX_SUCCESS;
5703 if (static_branch_unlikely(&rps_needed)) {
5704 struct rps_dev_flow voidflow, *rflow = &voidflow;
5705 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5708 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5714 ret = __netif_receive_skb(skb);
5719 void netif_receive_skb_list_internal(struct list_head *head)
5721 struct sk_buff *skb, *next;
5722 struct list_head sublist;
5724 INIT_LIST_HEAD(&sublist);
5725 list_for_each_entry_safe(skb, next, head, list) {
5726 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5727 skb_list_del_init(skb);
5728 if (!skb_defer_rx_timestamp(skb))
5729 list_add_tail(&skb->list, &sublist);
5731 list_splice_init(&sublist, head);
5735 if (static_branch_unlikely(&rps_needed)) {
5736 list_for_each_entry_safe(skb, next, head, list) {
5737 struct rps_dev_flow voidflow, *rflow = &voidflow;
5738 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5741 /* Will be handled, remove from list */
5742 skb_list_del_init(skb);
5743 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5748 __netif_receive_skb_list(head);
5753 * netif_receive_skb - process receive buffer from network
5754 * @skb: buffer to process
5756 * netif_receive_skb() is the main receive data processing function.
5757 * It always succeeds. The buffer may be dropped during processing
5758 * for congestion control or by the protocol layers.
5760 * This function may only be called from softirq context and interrupts
5761 * should be enabled.
5763 * Return values (usually ignored):
5764 * NET_RX_SUCCESS: no congestion
5765 * NET_RX_DROP: packet was dropped
5767 int netif_receive_skb(struct sk_buff *skb)
5771 trace_netif_receive_skb_entry(skb);
5773 ret = netif_receive_skb_internal(skb);
5774 trace_netif_receive_skb_exit(ret);
5778 EXPORT_SYMBOL(netif_receive_skb);
5781 * netif_receive_skb_list - process many receive buffers from network
5782 * @head: list of skbs to process.
5784 * Since return value of netif_receive_skb() is normally ignored, and
5785 * wouldn't be meaningful for a list, this function returns void.
5787 * This function may only be called from softirq context and interrupts
5788 * should be enabled.
5790 void netif_receive_skb_list(struct list_head *head)
5792 struct sk_buff *skb;
5794 if (list_empty(head))
5796 if (trace_netif_receive_skb_list_entry_enabled()) {
5797 list_for_each_entry(skb, head, list)
5798 trace_netif_receive_skb_list_entry(skb);
5800 netif_receive_skb_list_internal(head);
5801 trace_netif_receive_skb_list_exit(0);
5803 EXPORT_SYMBOL(netif_receive_skb_list);
5805 static DEFINE_PER_CPU(struct work_struct, flush_works);
5807 /* Network device is going away, flush any packets still pending */
5808 static void flush_backlog(struct work_struct *work)
5810 struct sk_buff *skb, *tmp;
5811 struct softnet_data *sd;
5814 sd = this_cpu_ptr(&softnet_data);
5816 rps_lock_irq_disable(sd);
5817 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5818 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5819 __skb_unlink(skb, &sd->input_pkt_queue);
5820 dev_kfree_skb_irq(skb);
5821 input_queue_head_incr(sd);
5824 rps_unlock_irq_enable(sd);
5826 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5827 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5828 __skb_unlink(skb, &sd->process_queue);
5830 input_queue_head_incr(sd);
5836 static bool flush_required(int cpu)
5838 #if IS_ENABLED(CONFIG_RPS)
5839 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5842 rps_lock_irq_disable(sd);
5844 /* as insertion into process_queue happens with the rps lock held,
5845 * process_queue access may race only with dequeue
5847 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5848 !skb_queue_empty_lockless(&sd->process_queue);
5849 rps_unlock_irq_enable(sd);
5853 /* without RPS we can't safely check input_pkt_queue: during a
5854 * concurrent remote skb_queue_splice() we can detect as empty both
5855 * input_pkt_queue and process_queue even if the latter could end-up
5856 * containing a lot of packets.
5861 static void flush_all_backlogs(void)
5863 static cpumask_t flush_cpus;
5866 /* since we are under rtnl lock protection we can use static data
5867 * for the cpumask and avoid allocating on stack the possibly
5874 cpumask_clear(&flush_cpus);
5875 for_each_online_cpu(cpu) {
5876 if (flush_required(cpu)) {
5877 queue_work_on(cpu, system_highpri_wq,
5878 per_cpu_ptr(&flush_works, cpu));
5879 cpumask_set_cpu(cpu, &flush_cpus);
5883 /* we can have in flight packet[s] on the cpus we are not flushing,
5884 * synchronize_net() in unregister_netdevice_many() will take care of
5887 for_each_cpu(cpu, &flush_cpus)
5888 flush_work(per_cpu_ptr(&flush_works, cpu));
5893 static void net_rps_send_ipi(struct softnet_data *remsd)
5897 struct softnet_data *next = remsd->rps_ipi_next;
5899 if (cpu_online(remsd->cpu))
5900 smp_call_function_single_async(remsd->cpu, &remsd->csd);
5907 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
5908 * Note: called with local irq disabled, but exits with local irq enabled.
5910 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
5913 struct softnet_data *remsd = sd->rps_ipi_list;
5916 sd->rps_ipi_list = NULL;
5920 /* Send pending IPI's to kick RPS processing on remote cpus. */
5921 net_rps_send_ipi(remsd);
5927 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
5930 return sd->rps_ipi_list != NULL;
5936 static int process_backlog(struct napi_struct *napi, int quota)
5938 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
5942 /* Check if we have pending ipi, its better to send them now,
5943 * not waiting net_rx_action() end.
5945 if (sd_has_rps_ipi_waiting(sd)) {
5946 local_irq_disable();
5947 net_rps_action_and_irq_enable(sd);
5950 napi->weight = READ_ONCE(dev_rx_weight);
5952 struct sk_buff *skb;
5954 while ((skb = __skb_dequeue(&sd->process_queue))) {
5956 __netif_receive_skb(skb);
5958 input_queue_head_incr(sd);
5959 if (++work >= quota)
5964 rps_lock_irq_disable(sd);
5965 if (skb_queue_empty(&sd->input_pkt_queue)) {
5967 * Inline a custom version of __napi_complete().
5968 * only current cpu owns and manipulates this napi,
5969 * and NAPI_STATE_SCHED is the only possible flag set
5971 * We can use a plain write instead of clear_bit(),
5972 * and we dont need an smp_mb() memory barrier.
5977 skb_queue_splice_tail_init(&sd->input_pkt_queue,
5978 &sd->process_queue);
5980 rps_unlock_irq_enable(sd);
5987 * __napi_schedule - schedule for receive
5988 * @n: entry to schedule
5990 * The entry's receive function will be scheduled to run.
5991 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
5993 void __napi_schedule(struct napi_struct *n)
5995 unsigned long flags;
5997 local_irq_save(flags);
5998 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5999 local_irq_restore(flags);
6001 EXPORT_SYMBOL(__napi_schedule);
6004 * napi_schedule_prep - check if napi can be scheduled
6007 * Test if NAPI routine is already running, and if not mark
6008 * it as running. This is used as a condition variable to
6009 * insure only one NAPI poll instance runs. We also make
6010 * sure there is no pending NAPI disable.
6012 bool napi_schedule_prep(struct napi_struct *n)
6014 unsigned long new, val = READ_ONCE(n->state);
6017 if (unlikely(val & NAPIF_STATE_DISABLE))
6019 new = val | NAPIF_STATE_SCHED;
6021 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6022 * This was suggested by Alexander Duyck, as compiler
6023 * emits better code than :
6024 * if (val & NAPIF_STATE_SCHED)
6025 * new |= NAPIF_STATE_MISSED;
6027 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6029 } while (!try_cmpxchg(&n->state, &val, new));
6031 return !(val & NAPIF_STATE_SCHED);
6033 EXPORT_SYMBOL(napi_schedule_prep);
6036 * __napi_schedule_irqoff - schedule for receive
6037 * @n: entry to schedule
6039 * Variant of __napi_schedule() assuming hard irqs are masked.
6041 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
6042 * because the interrupt disabled assumption might not be true
6043 * due to force-threaded interrupts and spinlock substitution.
6045 void __napi_schedule_irqoff(struct napi_struct *n)
6047 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6048 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6052 EXPORT_SYMBOL(__napi_schedule_irqoff);
6054 bool napi_complete_done(struct napi_struct *n, int work_done)
6056 unsigned long flags, val, new, timeout = 0;
6060 * 1) Don't let napi dequeue from the cpu poll list
6061 * just in case its running on a different cpu.
6062 * 2) If we are busy polling, do nothing here, we have
6063 * the guarantee we will be called later.
6065 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6066 NAPIF_STATE_IN_BUSY_POLL)))
6071 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6072 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
6074 if (n->defer_hard_irqs_count > 0) {
6075 n->defer_hard_irqs_count--;
6076 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6080 if (n->gro_bitmask) {
6081 /* When the NAPI instance uses a timeout and keeps postponing
6082 * it, we need to bound somehow the time packets are kept in
6085 napi_gro_flush(n, !!timeout);
6090 if (unlikely(!list_empty(&n->poll_list))) {
6091 /* If n->poll_list is not empty, we need to mask irqs */
6092 local_irq_save(flags);
6093 list_del_init(&n->poll_list);
6094 local_irq_restore(flags);
6096 WRITE_ONCE(n->list_owner, -1);
6098 val = READ_ONCE(n->state);
6100 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6102 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
6103 NAPIF_STATE_SCHED_THREADED |
6104 NAPIF_STATE_PREFER_BUSY_POLL);
6106 /* If STATE_MISSED was set, leave STATE_SCHED set,
6107 * because we will call napi->poll() one more time.
6108 * This C code was suggested by Alexander Duyck to help gcc.
6110 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6112 } while (!try_cmpxchg(&n->state, &val, new));
6114 if (unlikely(val & NAPIF_STATE_MISSED)) {
6120 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6121 HRTIMER_MODE_REL_PINNED);
6124 EXPORT_SYMBOL(napi_complete_done);
6126 /* must be called under rcu_read_lock(), as we dont take a reference */
6127 static struct napi_struct *napi_by_id(unsigned int napi_id)
6129 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6130 struct napi_struct *napi;
6132 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6133 if (napi->napi_id == napi_id)
6139 #if defined(CONFIG_NET_RX_BUSY_POLL)
6141 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
6143 if (!skip_schedule) {
6144 gro_normal_list(napi);
6145 __napi_schedule(napi);
6149 if (napi->gro_bitmask) {
6150 /* flush too old packets
6151 * If HZ < 1000, flush all packets.
6153 napi_gro_flush(napi, HZ >= 1000);
6156 gro_normal_list(napi);
6157 clear_bit(NAPI_STATE_SCHED, &napi->state);
6160 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, bool prefer_busy_poll,
6163 bool skip_schedule = false;
6164 unsigned long timeout;
6167 /* Busy polling means there is a high chance device driver hard irq
6168 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6169 * set in napi_schedule_prep().
6170 * Since we are about to call napi->poll() once more, we can safely
6171 * clear NAPI_STATE_MISSED.
6173 * Note: x86 could use a single "lock and ..." instruction
6174 * to perform these two clear_bit()
6176 clear_bit(NAPI_STATE_MISSED, &napi->state);
6177 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6181 if (prefer_busy_poll) {
6182 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
6183 timeout = READ_ONCE(napi->dev->gro_flush_timeout);
6184 if (napi->defer_hard_irqs_count && timeout) {
6185 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
6186 skip_schedule = true;
6190 /* All we really want here is to re-enable device interrupts.
6191 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6193 rc = napi->poll(napi, budget);
6194 /* We can't gro_normal_list() here, because napi->poll() might have
6195 * rearmed the napi (napi_complete_done()) in which case it could
6196 * already be running on another CPU.
6198 trace_napi_poll(napi, rc, budget);
6199 netpoll_poll_unlock(have_poll_lock);
6201 __busy_poll_stop(napi, skip_schedule);
6205 void napi_busy_loop(unsigned int napi_id,
6206 bool (*loop_end)(void *, unsigned long),
6207 void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6209 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6210 int (*napi_poll)(struct napi_struct *napi, int budget);
6211 void *have_poll_lock = NULL;
6212 struct napi_struct *napi;
6219 napi = napi_by_id(napi_id);
6223 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6230 unsigned long val = READ_ONCE(napi->state);
6232 /* If multiple threads are competing for this napi,
6233 * we avoid dirtying napi->state as much as we can.
6235 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6236 NAPIF_STATE_IN_BUSY_POLL)) {
6237 if (prefer_busy_poll)
6238 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6241 if (cmpxchg(&napi->state, val,
6242 val | NAPIF_STATE_IN_BUSY_POLL |
6243 NAPIF_STATE_SCHED) != val) {
6244 if (prefer_busy_poll)
6245 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6248 have_poll_lock = netpoll_poll_lock(napi);
6249 napi_poll = napi->poll;
6251 work = napi_poll(napi, budget);
6252 trace_napi_poll(napi, work, budget);
6253 gro_normal_list(napi);
6256 __NET_ADD_STATS(dev_net(napi->dev),
6257 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6260 if (!loop_end || loop_end(loop_end_arg, start_time))
6263 if (unlikely(need_resched())) {
6265 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6266 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6270 if (loop_end(loop_end_arg, start_time))
6277 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6278 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6283 EXPORT_SYMBOL(napi_busy_loop);
6285 #endif /* CONFIG_NET_RX_BUSY_POLL */
6287 static void napi_hash_add(struct napi_struct *napi)
6289 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6292 spin_lock(&napi_hash_lock);
6294 /* 0..NR_CPUS range is reserved for sender_cpu use */
6296 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6297 napi_gen_id = MIN_NAPI_ID;
6298 } while (napi_by_id(napi_gen_id));
6299 napi->napi_id = napi_gen_id;
6301 hlist_add_head_rcu(&napi->napi_hash_node,
6302 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6304 spin_unlock(&napi_hash_lock);
6307 /* Warning : caller is responsible to make sure rcu grace period
6308 * is respected before freeing memory containing @napi
6310 static void napi_hash_del(struct napi_struct *napi)
6312 spin_lock(&napi_hash_lock);
6314 hlist_del_init_rcu(&napi->napi_hash_node);
6316 spin_unlock(&napi_hash_lock);
6319 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6321 struct napi_struct *napi;
6323 napi = container_of(timer, struct napi_struct, timer);
6325 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6326 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6328 if (!napi_disable_pending(napi) &&
6329 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
6330 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6331 __napi_schedule_irqoff(napi);
6334 return HRTIMER_NORESTART;
6337 static void init_gro_hash(struct napi_struct *napi)
6341 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6342 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6343 napi->gro_hash[i].count = 0;
6345 napi->gro_bitmask = 0;
6348 int dev_set_threaded(struct net_device *dev, bool threaded)
6350 struct napi_struct *napi;
6353 if (dev->threaded == threaded)
6357 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6358 if (!napi->thread) {
6359 err = napi_kthread_create(napi);
6368 dev->threaded = threaded;
6370 /* Make sure kthread is created before THREADED bit
6373 smp_mb__before_atomic();
6375 /* Setting/unsetting threaded mode on a napi might not immediately
6376 * take effect, if the current napi instance is actively being
6377 * polled. In this case, the switch between threaded mode and
6378 * softirq mode will happen in the next round of napi_schedule().
6379 * This should not cause hiccups/stalls to the live traffic.
6381 list_for_each_entry(napi, &dev->napi_list, dev_list)
6382 assign_bit(NAPI_STATE_THREADED, &napi->state, threaded);
6386 EXPORT_SYMBOL(dev_set_threaded);
6388 void netif_napi_add_weight(struct net_device *dev, struct napi_struct *napi,
6389 int (*poll)(struct napi_struct *, int), int weight)
6391 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6394 INIT_LIST_HEAD(&napi->poll_list);
6395 INIT_HLIST_NODE(&napi->napi_hash_node);
6396 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6397 napi->timer.function = napi_watchdog;
6398 init_gro_hash(napi);
6400 INIT_LIST_HEAD(&napi->rx_list);
6403 if (weight > NAPI_POLL_WEIGHT)
6404 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6406 napi->weight = weight;
6408 #ifdef CONFIG_NETPOLL
6409 napi->poll_owner = -1;
6411 napi->list_owner = -1;
6412 set_bit(NAPI_STATE_SCHED, &napi->state);
6413 set_bit(NAPI_STATE_NPSVC, &napi->state);
6414 list_add_rcu(&napi->dev_list, &dev->napi_list);
6415 napi_hash_add(napi);
6416 napi_get_frags_check(napi);
6417 /* Create kthread for this napi if dev->threaded is set.
6418 * Clear dev->threaded if kthread creation failed so that
6419 * threaded mode will not be enabled in napi_enable().
6421 if (dev->threaded && napi_kthread_create(napi))
6424 EXPORT_SYMBOL(netif_napi_add_weight);
6426 void napi_disable(struct napi_struct *n)
6428 unsigned long val, new;
6431 set_bit(NAPI_STATE_DISABLE, &n->state);
6433 val = READ_ONCE(n->state);
6435 while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
6436 usleep_range(20, 200);
6437 val = READ_ONCE(n->state);
6440 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
6441 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
6442 } while (!try_cmpxchg(&n->state, &val, new));
6444 hrtimer_cancel(&n->timer);
6446 clear_bit(NAPI_STATE_DISABLE, &n->state);
6448 EXPORT_SYMBOL(napi_disable);
6451 * napi_enable - enable NAPI scheduling
6454 * Resume NAPI from being scheduled on this context.
6455 * Must be paired with napi_disable.
6457 void napi_enable(struct napi_struct *n)
6459 unsigned long new, val = READ_ONCE(n->state);
6462 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
6464 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
6465 if (n->dev->threaded && n->thread)
6466 new |= NAPIF_STATE_THREADED;
6467 } while (!try_cmpxchg(&n->state, &val, new));
6469 EXPORT_SYMBOL(napi_enable);
6471 static void flush_gro_hash(struct napi_struct *napi)
6475 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6476 struct sk_buff *skb, *n;
6478 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6480 napi->gro_hash[i].count = 0;
6484 /* Must be called in process context */
6485 void __netif_napi_del(struct napi_struct *napi)
6487 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6490 napi_hash_del(napi);
6491 list_del_rcu(&napi->dev_list);
6492 napi_free_frags(napi);
6494 flush_gro_hash(napi);
6495 napi->gro_bitmask = 0;
6498 kthread_stop(napi->thread);
6499 napi->thread = NULL;
6502 EXPORT_SYMBOL(__netif_napi_del);
6504 static int __napi_poll(struct napi_struct *n, bool *repoll)
6510 /* This NAPI_STATE_SCHED test is for avoiding a race
6511 * with netpoll's poll_napi(). Only the entity which
6512 * obtains the lock and sees NAPI_STATE_SCHED set will
6513 * actually make the ->poll() call. Therefore we avoid
6514 * accidentally calling ->poll() when NAPI is not scheduled.
6517 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6518 work = n->poll(n, weight);
6519 trace_napi_poll(n, work, weight);
6522 if (unlikely(work > weight))
6523 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6524 n->poll, work, weight);
6526 if (likely(work < weight))
6529 /* Drivers must not modify the NAPI state if they
6530 * consume the entire weight. In such cases this code
6531 * still "owns" the NAPI instance and therefore can
6532 * move the instance around on the list at-will.
6534 if (unlikely(napi_disable_pending(n))) {
6539 /* The NAPI context has more processing work, but busy-polling
6540 * is preferred. Exit early.
6542 if (napi_prefer_busy_poll(n)) {
6543 if (napi_complete_done(n, work)) {
6544 /* If timeout is not set, we need to make sure
6545 * that the NAPI is re-scheduled.
6552 if (n->gro_bitmask) {
6553 /* flush too old packets
6554 * If HZ < 1000, flush all packets.
6556 napi_gro_flush(n, HZ >= 1000);
6561 /* Some drivers may have called napi_schedule
6562 * prior to exhausting their budget.
6564 if (unlikely(!list_empty(&n->poll_list))) {
6565 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6566 n->dev ? n->dev->name : "backlog");
6575 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6577 bool do_repoll = false;
6581 list_del_init(&n->poll_list);
6583 have = netpoll_poll_lock(n);
6585 work = __napi_poll(n, &do_repoll);
6588 list_add_tail(&n->poll_list, repoll);
6590 netpoll_poll_unlock(have);
6595 static int napi_thread_wait(struct napi_struct *napi)
6599 set_current_state(TASK_INTERRUPTIBLE);
6601 while (!kthread_should_stop()) {
6602 /* Testing SCHED_THREADED bit here to make sure the current
6603 * kthread owns this napi and could poll on this napi.
6604 * Testing SCHED bit is not enough because SCHED bit might be
6605 * set by some other busy poll thread or by napi_disable().
6607 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state) || woken) {
6608 WARN_ON(!list_empty(&napi->poll_list));
6609 __set_current_state(TASK_RUNNING);
6614 /* woken being true indicates this thread owns this napi. */
6616 set_current_state(TASK_INTERRUPTIBLE);
6618 __set_current_state(TASK_RUNNING);
6623 static void skb_defer_free_flush(struct softnet_data *sd)
6625 struct sk_buff *skb, *next;
6627 /* Paired with WRITE_ONCE() in skb_attempt_defer_free() */
6628 if (!READ_ONCE(sd->defer_list))
6631 spin_lock(&sd->defer_lock);
6632 skb = sd->defer_list;
6633 sd->defer_list = NULL;
6634 sd->defer_count = 0;
6635 spin_unlock(&sd->defer_lock);
6637 while (skb != NULL) {
6639 napi_consume_skb(skb, 1);
6644 static int napi_threaded_poll(void *data)
6646 struct napi_struct *napi = data;
6647 struct softnet_data *sd;
6650 while (!napi_thread_wait(napi)) {
6652 bool repoll = false;
6655 sd = this_cpu_ptr(&softnet_data);
6656 sd->in_napi_threaded_poll = true;
6658 have = netpoll_poll_lock(napi);
6659 __napi_poll(napi, &repoll);
6660 netpoll_poll_unlock(have);
6662 sd->in_napi_threaded_poll = false;
6665 if (sd_has_rps_ipi_waiting(sd)) {
6666 local_irq_disable();
6667 net_rps_action_and_irq_enable(sd);
6669 skb_defer_free_flush(sd);
6681 static __latent_entropy void net_rx_action(struct softirq_action *h)
6683 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6684 unsigned long time_limit = jiffies +
6685 usecs_to_jiffies(READ_ONCE(netdev_budget_usecs));
6686 int budget = READ_ONCE(netdev_budget);
6691 sd->in_net_rx_action = true;
6692 local_irq_disable();
6693 list_splice_init(&sd->poll_list, &list);
6697 struct napi_struct *n;
6699 skb_defer_free_flush(sd);
6701 if (list_empty(&list)) {
6702 if (list_empty(&repoll)) {
6703 sd->in_net_rx_action = false;
6705 /* We need to check if ____napi_schedule()
6706 * had refilled poll_list while
6707 * sd->in_net_rx_action was true.
6709 if (!list_empty(&sd->poll_list))
6711 if (!sd_has_rps_ipi_waiting(sd))
6717 n = list_first_entry(&list, struct napi_struct, poll_list);
6718 budget -= napi_poll(n, &repoll);
6720 /* If softirq window is exhausted then punt.
6721 * Allow this to run for 2 jiffies since which will allow
6722 * an average latency of 1.5/HZ.
6724 if (unlikely(budget <= 0 ||
6725 time_after_eq(jiffies, time_limit))) {
6731 local_irq_disable();
6733 list_splice_tail_init(&sd->poll_list, &list);
6734 list_splice_tail(&repoll, &list);
6735 list_splice(&list, &sd->poll_list);
6736 if (!list_empty(&sd->poll_list))
6737 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6739 sd->in_net_rx_action = false;
6741 net_rps_action_and_irq_enable(sd);
6745 struct netdev_adjacent {
6746 struct net_device *dev;
6747 netdevice_tracker dev_tracker;
6749 /* upper master flag, there can only be one master device per list */
6752 /* lookup ignore flag */
6755 /* counter for the number of times this device was added to us */
6758 /* private field for the users */
6761 struct list_head list;
6762 struct rcu_head rcu;
6765 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6766 struct list_head *adj_list)
6768 struct netdev_adjacent *adj;
6770 list_for_each_entry(adj, adj_list, list) {
6771 if (adj->dev == adj_dev)
6777 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6778 struct netdev_nested_priv *priv)
6780 struct net_device *dev = (struct net_device *)priv->data;
6782 return upper_dev == dev;
6786 * netdev_has_upper_dev - Check if device is linked to an upper device
6788 * @upper_dev: upper device to check
6790 * Find out if a device is linked to specified upper device and return true
6791 * in case it is. Note that this checks only immediate upper device,
6792 * not through a complete stack of devices. The caller must hold the RTNL lock.
6794 bool netdev_has_upper_dev(struct net_device *dev,
6795 struct net_device *upper_dev)
6797 struct netdev_nested_priv priv = {
6798 .data = (void *)upper_dev,
6803 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6806 EXPORT_SYMBOL(netdev_has_upper_dev);
6809 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
6811 * @upper_dev: upper device to check
6813 * Find out if a device is linked to specified upper device and return true
6814 * in case it is. Note that this checks the entire upper device chain.
6815 * The caller must hold rcu lock.
6818 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6819 struct net_device *upper_dev)
6821 struct netdev_nested_priv priv = {
6822 .data = (void *)upper_dev,
6825 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6828 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6831 * netdev_has_any_upper_dev - Check if device is linked to some device
6834 * Find out if a device is linked to an upper device and return true in case
6835 * it is. The caller must hold the RTNL lock.
6837 bool netdev_has_any_upper_dev(struct net_device *dev)
6841 return !list_empty(&dev->adj_list.upper);
6843 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6846 * netdev_master_upper_dev_get - Get master upper device
6849 * Find a master upper device and return pointer to it or NULL in case
6850 * it's not there. The caller must hold the RTNL lock.
6852 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6854 struct netdev_adjacent *upper;
6858 if (list_empty(&dev->adj_list.upper))
6861 upper = list_first_entry(&dev->adj_list.upper,
6862 struct netdev_adjacent, list);
6863 if (likely(upper->master))
6867 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6869 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
6871 struct netdev_adjacent *upper;
6875 if (list_empty(&dev->adj_list.upper))
6878 upper = list_first_entry(&dev->adj_list.upper,
6879 struct netdev_adjacent, list);
6880 if (likely(upper->master) && !upper->ignore)
6886 * netdev_has_any_lower_dev - Check if device is linked to some device
6889 * Find out if a device is linked to a lower device and return true in case
6890 * it is. The caller must hold the RTNL lock.
6892 static bool netdev_has_any_lower_dev(struct net_device *dev)
6896 return !list_empty(&dev->adj_list.lower);
6899 void *netdev_adjacent_get_private(struct list_head *adj_list)
6901 struct netdev_adjacent *adj;
6903 adj = list_entry(adj_list, struct netdev_adjacent, list);
6905 return adj->private;
6907 EXPORT_SYMBOL(netdev_adjacent_get_private);
6910 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
6912 * @iter: list_head ** of the current position
6914 * Gets the next device from the dev's upper list, starting from iter
6915 * position. The caller must hold RCU read lock.
6917 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
6918 struct list_head **iter)
6920 struct netdev_adjacent *upper;
6922 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6924 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6926 if (&upper->list == &dev->adj_list.upper)
6929 *iter = &upper->list;
6933 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
6935 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
6936 struct list_head **iter,
6939 struct netdev_adjacent *upper;
6941 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
6943 if (&upper->list == &dev->adj_list.upper)
6946 *iter = &upper->list;
6947 *ignore = upper->ignore;
6952 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
6953 struct list_head **iter)
6955 struct netdev_adjacent *upper;
6957 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6959 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6961 if (&upper->list == &dev->adj_list.upper)
6964 *iter = &upper->list;
6969 static int __netdev_walk_all_upper_dev(struct net_device *dev,
6970 int (*fn)(struct net_device *dev,
6971 struct netdev_nested_priv *priv),
6972 struct netdev_nested_priv *priv)
6974 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6975 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6980 iter = &dev->adj_list.upper;
6984 ret = fn(now, priv);
6991 udev = __netdev_next_upper_dev(now, &iter, &ignore);
6998 niter = &udev->adj_list.upper;
6999 dev_stack[cur] = now;
7000 iter_stack[cur++] = iter;
7007 next = dev_stack[--cur];
7008 niter = iter_stack[cur];
7018 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
7019 int (*fn)(struct net_device *dev,
7020 struct netdev_nested_priv *priv),
7021 struct netdev_nested_priv *priv)
7023 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7024 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7028 iter = &dev->adj_list.upper;
7032 ret = fn(now, priv);
7039 udev = netdev_next_upper_dev_rcu(now, &iter);
7044 niter = &udev->adj_list.upper;
7045 dev_stack[cur] = now;
7046 iter_stack[cur++] = iter;
7053 next = dev_stack[--cur];
7054 niter = iter_stack[cur];
7063 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7065 static bool __netdev_has_upper_dev(struct net_device *dev,
7066 struct net_device *upper_dev)
7068 struct netdev_nested_priv priv = {
7070 .data = (void *)upper_dev,
7075 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7080 * netdev_lower_get_next_private - Get the next ->private from the
7081 * lower neighbour list
7083 * @iter: list_head ** of the current position
7085 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7086 * list, starting from iter position. The caller must hold either hold the
7087 * RTNL lock or its own locking that guarantees that the neighbour lower
7088 * list will remain unchanged.
7090 void *netdev_lower_get_next_private(struct net_device *dev,
7091 struct list_head **iter)
7093 struct netdev_adjacent *lower;
7095 lower = list_entry(*iter, struct netdev_adjacent, list);
7097 if (&lower->list == &dev->adj_list.lower)
7100 *iter = lower->list.next;
7102 return lower->private;
7104 EXPORT_SYMBOL(netdev_lower_get_next_private);
7107 * netdev_lower_get_next_private_rcu - Get the next ->private from the
7108 * lower neighbour list, RCU
7111 * @iter: list_head ** of the current position
7113 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7114 * list, starting from iter position. The caller must hold RCU read lock.
7116 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
7117 struct list_head **iter)
7119 struct netdev_adjacent *lower;
7121 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
7123 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7125 if (&lower->list == &dev->adj_list.lower)
7128 *iter = &lower->list;
7130 return lower->private;
7132 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7135 * netdev_lower_get_next - Get the next device from the lower neighbour
7138 * @iter: list_head ** of the current position
7140 * Gets the next netdev_adjacent from the dev's lower neighbour
7141 * list, starting from iter position. The caller must hold RTNL lock or
7142 * its own locking that guarantees that the neighbour lower
7143 * list will remain unchanged.
7145 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7147 struct netdev_adjacent *lower;
7149 lower = list_entry(*iter, struct netdev_adjacent, list);
7151 if (&lower->list == &dev->adj_list.lower)
7154 *iter = lower->list.next;
7158 EXPORT_SYMBOL(netdev_lower_get_next);
7160 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7161 struct list_head **iter)
7163 struct netdev_adjacent *lower;
7165 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7167 if (&lower->list == &dev->adj_list.lower)
7170 *iter = &lower->list;
7175 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7176 struct list_head **iter,
7179 struct netdev_adjacent *lower;
7181 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7183 if (&lower->list == &dev->adj_list.lower)
7186 *iter = &lower->list;
7187 *ignore = lower->ignore;
7192 int netdev_walk_all_lower_dev(struct net_device *dev,
7193 int (*fn)(struct net_device *dev,
7194 struct netdev_nested_priv *priv),
7195 struct netdev_nested_priv *priv)
7197 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7198 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7202 iter = &dev->adj_list.lower;
7206 ret = fn(now, priv);
7213 ldev = netdev_next_lower_dev(now, &iter);
7218 niter = &ldev->adj_list.lower;
7219 dev_stack[cur] = now;
7220 iter_stack[cur++] = iter;
7227 next = dev_stack[--cur];
7228 niter = iter_stack[cur];
7237 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7239 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7240 int (*fn)(struct net_device *dev,
7241 struct netdev_nested_priv *priv),
7242 struct netdev_nested_priv *priv)
7244 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7245 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7250 iter = &dev->adj_list.lower;
7254 ret = fn(now, priv);
7261 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7268 niter = &ldev->adj_list.lower;
7269 dev_stack[cur] = now;
7270 iter_stack[cur++] = iter;
7277 next = dev_stack[--cur];
7278 niter = iter_stack[cur];
7288 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7289 struct list_head **iter)
7291 struct netdev_adjacent *lower;
7293 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7294 if (&lower->list == &dev->adj_list.lower)
7297 *iter = &lower->list;
7301 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7303 static u8 __netdev_upper_depth(struct net_device *dev)
7305 struct net_device *udev;
7306 struct list_head *iter;
7310 for (iter = &dev->adj_list.upper,
7311 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7313 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7316 if (max_depth < udev->upper_level)
7317 max_depth = udev->upper_level;
7323 static u8 __netdev_lower_depth(struct net_device *dev)
7325 struct net_device *ldev;
7326 struct list_head *iter;
7330 for (iter = &dev->adj_list.lower,
7331 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7333 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7336 if (max_depth < ldev->lower_level)
7337 max_depth = ldev->lower_level;
7343 static int __netdev_update_upper_level(struct net_device *dev,
7344 struct netdev_nested_priv *__unused)
7346 dev->upper_level = __netdev_upper_depth(dev) + 1;
7350 #ifdef CONFIG_LOCKDEP
7351 static LIST_HEAD(net_unlink_list);
7353 static void net_unlink_todo(struct net_device *dev)
7355 if (list_empty(&dev->unlink_list))
7356 list_add_tail(&dev->unlink_list, &net_unlink_list);
7360 static int __netdev_update_lower_level(struct net_device *dev,
7361 struct netdev_nested_priv *priv)
7363 dev->lower_level = __netdev_lower_depth(dev) + 1;
7365 #ifdef CONFIG_LOCKDEP
7369 if (priv->flags & NESTED_SYNC_IMM)
7370 dev->nested_level = dev->lower_level - 1;
7371 if (priv->flags & NESTED_SYNC_TODO)
7372 net_unlink_todo(dev);
7377 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7378 int (*fn)(struct net_device *dev,
7379 struct netdev_nested_priv *priv),
7380 struct netdev_nested_priv *priv)
7382 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7383 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7387 iter = &dev->adj_list.lower;
7391 ret = fn(now, priv);
7398 ldev = netdev_next_lower_dev_rcu(now, &iter);
7403 niter = &ldev->adj_list.lower;
7404 dev_stack[cur] = now;
7405 iter_stack[cur++] = iter;
7412 next = dev_stack[--cur];
7413 niter = iter_stack[cur];
7422 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7425 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7426 * lower neighbour list, RCU
7430 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7431 * list. The caller must hold RCU read lock.
7433 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7435 struct netdev_adjacent *lower;
7437 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7438 struct netdev_adjacent, list);
7440 return lower->private;
7443 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7446 * netdev_master_upper_dev_get_rcu - Get master upper device
7449 * Find a master upper device and return pointer to it or NULL in case
7450 * it's not there. The caller must hold the RCU read lock.
7452 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7454 struct netdev_adjacent *upper;
7456 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7457 struct netdev_adjacent, list);
7458 if (upper && likely(upper->master))
7462 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7464 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7465 struct net_device *adj_dev,
7466 struct list_head *dev_list)
7468 char linkname[IFNAMSIZ+7];
7470 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7471 "upper_%s" : "lower_%s", adj_dev->name);
7472 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7475 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7477 struct list_head *dev_list)
7479 char linkname[IFNAMSIZ+7];
7481 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7482 "upper_%s" : "lower_%s", name);
7483 sysfs_remove_link(&(dev->dev.kobj), linkname);
7486 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7487 struct net_device *adj_dev,
7488 struct list_head *dev_list)
7490 return (dev_list == &dev->adj_list.upper ||
7491 dev_list == &dev->adj_list.lower) &&
7492 net_eq(dev_net(dev), dev_net(adj_dev));
7495 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7496 struct net_device *adj_dev,
7497 struct list_head *dev_list,
7498 void *private, bool master)
7500 struct netdev_adjacent *adj;
7503 adj = __netdev_find_adj(adj_dev, dev_list);
7507 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7508 dev->name, adj_dev->name, adj->ref_nr);
7513 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7518 adj->master = master;
7520 adj->private = private;
7521 adj->ignore = false;
7522 netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL);
7524 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7525 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7527 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7528 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7533 /* Ensure that master link is always the first item in list. */
7535 ret = sysfs_create_link(&(dev->dev.kobj),
7536 &(adj_dev->dev.kobj), "master");
7538 goto remove_symlinks;
7540 list_add_rcu(&adj->list, dev_list);
7542 list_add_tail_rcu(&adj->list, dev_list);
7548 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7549 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7551 netdev_put(adj_dev, &adj->dev_tracker);
7557 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7558 struct net_device *adj_dev,
7560 struct list_head *dev_list)
7562 struct netdev_adjacent *adj;
7564 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7565 dev->name, adj_dev->name, ref_nr);
7567 adj = __netdev_find_adj(adj_dev, dev_list);
7570 pr_err("Adjacency does not exist for device %s from %s\n",
7571 dev->name, adj_dev->name);
7576 if (adj->ref_nr > ref_nr) {
7577 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7578 dev->name, adj_dev->name, ref_nr,
7579 adj->ref_nr - ref_nr);
7580 adj->ref_nr -= ref_nr;
7585 sysfs_remove_link(&(dev->dev.kobj), "master");
7587 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7588 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7590 list_del_rcu(&adj->list);
7591 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7592 adj_dev->name, dev->name, adj_dev->name);
7593 netdev_put(adj_dev, &adj->dev_tracker);
7594 kfree_rcu(adj, rcu);
7597 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7598 struct net_device *upper_dev,
7599 struct list_head *up_list,
7600 struct list_head *down_list,
7601 void *private, bool master)
7605 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7610 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7613 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7620 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7621 struct net_device *upper_dev,
7623 struct list_head *up_list,
7624 struct list_head *down_list)
7626 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7627 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7630 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7631 struct net_device *upper_dev,
7632 void *private, bool master)
7634 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7635 &dev->adj_list.upper,
7636 &upper_dev->adj_list.lower,
7640 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7641 struct net_device *upper_dev)
7643 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7644 &dev->adj_list.upper,
7645 &upper_dev->adj_list.lower);
7648 static int __netdev_upper_dev_link(struct net_device *dev,
7649 struct net_device *upper_dev, bool master,
7650 void *upper_priv, void *upper_info,
7651 struct netdev_nested_priv *priv,
7652 struct netlink_ext_ack *extack)
7654 struct netdev_notifier_changeupper_info changeupper_info = {
7659 .upper_dev = upper_dev,
7662 .upper_info = upper_info,
7664 struct net_device *master_dev;
7669 if (dev == upper_dev)
7672 /* To prevent loops, check if dev is not upper device to upper_dev. */
7673 if (__netdev_has_upper_dev(upper_dev, dev))
7676 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7680 if (__netdev_has_upper_dev(dev, upper_dev))
7683 master_dev = __netdev_master_upper_dev_get(dev);
7685 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7688 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7689 &changeupper_info.info);
7690 ret = notifier_to_errno(ret);
7694 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7699 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7700 &changeupper_info.info);
7701 ret = notifier_to_errno(ret);
7705 __netdev_update_upper_level(dev, NULL);
7706 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7708 __netdev_update_lower_level(upper_dev, priv);
7709 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7715 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7721 * netdev_upper_dev_link - Add a link to the upper device
7723 * @upper_dev: new upper device
7724 * @extack: netlink extended ack
7726 * Adds a link to device which is upper to this one. The caller must hold
7727 * the RTNL lock. On a failure a negative errno code is returned.
7728 * On success the reference counts are adjusted and the function
7731 int netdev_upper_dev_link(struct net_device *dev,
7732 struct net_device *upper_dev,
7733 struct netlink_ext_ack *extack)
7735 struct netdev_nested_priv priv = {
7736 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7740 return __netdev_upper_dev_link(dev, upper_dev, false,
7741 NULL, NULL, &priv, extack);
7743 EXPORT_SYMBOL(netdev_upper_dev_link);
7746 * netdev_master_upper_dev_link - Add a master link to the upper device
7748 * @upper_dev: new upper device
7749 * @upper_priv: upper device private
7750 * @upper_info: upper info to be passed down via notifier
7751 * @extack: netlink extended ack
7753 * Adds a link to device which is upper to this one. In this case, only
7754 * one master upper device can be linked, although other non-master devices
7755 * might be linked as well. The caller must hold the RTNL lock.
7756 * On a failure a negative errno code is returned. On success the reference
7757 * counts are adjusted and the function returns zero.
7759 int netdev_master_upper_dev_link(struct net_device *dev,
7760 struct net_device *upper_dev,
7761 void *upper_priv, void *upper_info,
7762 struct netlink_ext_ack *extack)
7764 struct netdev_nested_priv priv = {
7765 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7769 return __netdev_upper_dev_link(dev, upper_dev, true,
7770 upper_priv, upper_info, &priv, extack);
7772 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7774 static void __netdev_upper_dev_unlink(struct net_device *dev,
7775 struct net_device *upper_dev,
7776 struct netdev_nested_priv *priv)
7778 struct netdev_notifier_changeupper_info changeupper_info = {
7782 .upper_dev = upper_dev,
7788 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7790 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7791 &changeupper_info.info);
7793 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7795 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7796 &changeupper_info.info);
7798 __netdev_update_upper_level(dev, NULL);
7799 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7801 __netdev_update_lower_level(upper_dev, priv);
7802 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7807 * netdev_upper_dev_unlink - Removes a link to upper device
7809 * @upper_dev: new upper device
7811 * Removes a link to device which is upper to this one. The caller must hold
7814 void netdev_upper_dev_unlink(struct net_device *dev,
7815 struct net_device *upper_dev)
7817 struct netdev_nested_priv priv = {
7818 .flags = NESTED_SYNC_TODO,
7822 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
7824 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7826 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7827 struct net_device *lower_dev,
7830 struct netdev_adjacent *adj;
7832 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
7836 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
7841 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
7842 struct net_device *lower_dev)
7844 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
7847 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
7848 struct net_device *lower_dev)
7850 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
7853 int netdev_adjacent_change_prepare(struct net_device *old_dev,
7854 struct net_device *new_dev,
7855 struct net_device *dev,
7856 struct netlink_ext_ack *extack)
7858 struct netdev_nested_priv priv = {
7867 if (old_dev && new_dev != old_dev)
7868 netdev_adjacent_dev_disable(dev, old_dev);
7869 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
7872 if (old_dev && new_dev != old_dev)
7873 netdev_adjacent_dev_enable(dev, old_dev);
7879 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
7881 void netdev_adjacent_change_commit(struct net_device *old_dev,
7882 struct net_device *new_dev,
7883 struct net_device *dev)
7885 struct netdev_nested_priv priv = {
7886 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7890 if (!new_dev || !old_dev)
7893 if (new_dev == old_dev)
7896 netdev_adjacent_dev_enable(dev, old_dev);
7897 __netdev_upper_dev_unlink(old_dev, dev, &priv);
7899 EXPORT_SYMBOL(netdev_adjacent_change_commit);
7901 void netdev_adjacent_change_abort(struct net_device *old_dev,
7902 struct net_device *new_dev,
7903 struct net_device *dev)
7905 struct netdev_nested_priv priv = {
7913 if (old_dev && new_dev != old_dev)
7914 netdev_adjacent_dev_enable(dev, old_dev);
7916 __netdev_upper_dev_unlink(new_dev, dev, &priv);
7918 EXPORT_SYMBOL(netdev_adjacent_change_abort);
7921 * netdev_bonding_info_change - Dispatch event about slave change
7923 * @bonding_info: info to dispatch
7925 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
7926 * The caller must hold the RTNL lock.
7928 void netdev_bonding_info_change(struct net_device *dev,
7929 struct netdev_bonding_info *bonding_info)
7931 struct netdev_notifier_bonding_info info = {
7935 memcpy(&info.bonding_info, bonding_info,
7936 sizeof(struct netdev_bonding_info));
7937 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
7940 EXPORT_SYMBOL(netdev_bonding_info_change);
7942 static int netdev_offload_xstats_enable_l3(struct net_device *dev,
7943 struct netlink_ext_ack *extack)
7945 struct netdev_notifier_offload_xstats_info info = {
7947 .info.extack = extack,
7948 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
7953 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
7955 if (!dev->offload_xstats_l3)
7958 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
7959 NETDEV_OFFLOAD_XSTATS_DISABLE,
7961 err = notifier_to_errno(rc);
7968 kfree(dev->offload_xstats_l3);
7969 dev->offload_xstats_l3 = NULL;
7973 int netdev_offload_xstats_enable(struct net_device *dev,
7974 enum netdev_offload_xstats_type type,
7975 struct netlink_ext_ack *extack)
7979 if (netdev_offload_xstats_enabled(dev, type))
7983 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
7984 return netdev_offload_xstats_enable_l3(dev, extack);
7990 EXPORT_SYMBOL(netdev_offload_xstats_enable);
7992 static void netdev_offload_xstats_disable_l3(struct net_device *dev)
7994 struct netdev_notifier_offload_xstats_info info = {
7996 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
7999 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
8001 kfree(dev->offload_xstats_l3);
8002 dev->offload_xstats_l3 = NULL;
8005 int netdev_offload_xstats_disable(struct net_device *dev,
8006 enum netdev_offload_xstats_type type)
8010 if (!netdev_offload_xstats_enabled(dev, type))
8014 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8015 netdev_offload_xstats_disable_l3(dev);
8022 EXPORT_SYMBOL(netdev_offload_xstats_disable);
8024 static void netdev_offload_xstats_disable_all(struct net_device *dev)
8026 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
8029 static struct rtnl_hw_stats64 *
8030 netdev_offload_xstats_get_ptr(const struct net_device *dev,
8031 enum netdev_offload_xstats_type type)
8034 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8035 return dev->offload_xstats_l3;
8042 bool netdev_offload_xstats_enabled(const struct net_device *dev,
8043 enum netdev_offload_xstats_type type)
8047 return netdev_offload_xstats_get_ptr(dev, type);
8049 EXPORT_SYMBOL(netdev_offload_xstats_enabled);
8051 struct netdev_notifier_offload_xstats_ru {
8055 struct netdev_notifier_offload_xstats_rd {
8056 struct rtnl_hw_stats64 stats;
8060 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
8061 const struct rtnl_hw_stats64 *src)
8063 dest->rx_packets += src->rx_packets;
8064 dest->tx_packets += src->tx_packets;
8065 dest->rx_bytes += src->rx_bytes;
8066 dest->tx_bytes += src->tx_bytes;
8067 dest->rx_errors += src->rx_errors;
8068 dest->tx_errors += src->tx_errors;
8069 dest->rx_dropped += src->rx_dropped;
8070 dest->tx_dropped += src->tx_dropped;
8071 dest->multicast += src->multicast;
8074 static int netdev_offload_xstats_get_used(struct net_device *dev,
8075 enum netdev_offload_xstats_type type,
8077 struct netlink_ext_ack *extack)
8079 struct netdev_notifier_offload_xstats_ru report_used = {};
8080 struct netdev_notifier_offload_xstats_info info = {
8082 .info.extack = extack,
8084 .report_used = &report_used,
8088 WARN_ON(!netdev_offload_xstats_enabled(dev, type));
8089 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
8091 *p_used = report_used.used;
8092 return notifier_to_errno(rc);
8095 static int netdev_offload_xstats_get_stats(struct net_device *dev,
8096 enum netdev_offload_xstats_type type,
8097 struct rtnl_hw_stats64 *p_stats,
8099 struct netlink_ext_ack *extack)
8101 struct netdev_notifier_offload_xstats_rd report_delta = {};
8102 struct netdev_notifier_offload_xstats_info info = {
8104 .info.extack = extack,
8106 .report_delta = &report_delta,
8108 struct rtnl_hw_stats64 *stats;
8111 stats = netdev_offload_xstats_get_ptr(dev, type);
8112 if (WARN_ON(!stats))
8115 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
8118 /* Cache whatever we got, even if there was an error, otherwise the
8119 * successful stats retrievals would get lost.
8121 netdev_hw_stats64_add(stats, &report_delta.stats);
8125 *p_used = report_delta.used;
8127 return notifier_to_errno(rc);
8130 int netdev_offload_xstats_get(struct net_device *dev,
8131 enum netdev_offload_xstats_type type,
8132 struct rtnl_hw_stats64 *p_stats, bool *p_used,
8133 struct netlink_ext_ack *extack)
8138 return netdev_offload_xstats_get_stats(dev, type, p_stats,
8141 return netdev_offload_xstats_get_used(dev, type, p_used,
8144 EXPORT_SYMBOL(netdev_offload_xstats_get);
8147 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
8148 const struct rtnl_hw_stats64 *stats)
8150 report_delta->used = true;
8151 netdev_hw_stats64_add(&report_delta->stats, stats);
8153 EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
8156 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
8158 report_used->used = true;
8160 EXPORT_SYMBOL(netdev_offload_xstats_report_used);
8162 void netdev_offload_xstats_push_delta(struct net_device *dev,
8163 enum netdev_offload_xstats_type type,
8164 const struct rtnl_hw_stats64 *p_stats)
8166 struct rtnl_hw_stats64 *stats;
8170 stats = netdev_offload_xstats_get_ptr(dev, type);
8171 if (WARN_ON(!stats))
8174 netdev_hw_stats64_add(stats, p_stats);
8176 EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
8179 * netdev_get_xmit_slave - Get the xmit slave of master device
8182 * @all_slaves: assume all the slaves are active
8184 * The reference counters are not incremented so the caller must be
8185 * careful with locks. The caller must hold RCU lock.
8186 * %NULL is returned if no slave is found.
8189 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8190 struct sk_buff *skb,
8193 const struct net_device_ops *ops = dev->netdev_ops;
8195 if (!ops->ndo_get_xmit_slave)
8197 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8199 EXPORT_SYMBOL(netdev_get_xmit_slave);
8201 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
8204 const struct net_device_ops *ops = dev->netdev_ops;
8206 if (!ops->ndo_sk_get_lower_dev)
8208 return ops->ndo_sk_get_lower_dev(dev, sk);
8212 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
8216 * %NULL is returned if no lower device is found.
8219 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
8222 struct net_device *lower;
8224 lower = netdev_sk_get_lower_dev(dev, sk);
8227 lower = netdev_sk_get_lower_dev(dev, sk);
8232 EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
8234 static void netdev_adjacent_add_links(struct net_device *dev)
8236 struct netdev_adjacent *iter;
8238 struct net *net = dev_net(dev);
8240 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8241 if (!net_eq(net, dev_net(iter->dev)))
8243 netdev_adjacent_sysfs_add(iter->dev, dev,
8244 &iter->dev->adj_list.lower);
8245 netdev_adjacent_sysfs_add(dev, iter->dev,
8246 &dev->adj_list.upper);
8249 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8250 if (!net_eq(net, dev_net(iter->dev)))
8252 netdev_adjacent_sysfs_add(iter->dev, dev,
8253 &iter->dev->adj_list.upper);
8254 netdev_adjacent_sysfs_add(dev, iter->dev,
8255 &dev->adj_list.lower);
8259 static void netdev_adjacent_del_links(struct net_device *dev)
8261 struct netdev_adjacent *iter;
8263 struct net *net = dev_net(dev);
8265 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8266 if (!net_eq(net, dev_net(iter->dev)))
8268 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8269 &iter->dev->adj_list.lower);
8270 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8271 &dev->adj_list.upper);
8274 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8275 if (!net_eq(net, dev_net(iter->dev)))
8277 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8278 &iter->dev->adj_list.upper);
8279 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8280 &dev->adj_list.lower);
8284 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8286 struct netdev_adjacent *iter;
8288 struct net *net = dev_net(dev);
8290 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8291 if (!net_eq(net, dev_net(iter->dev)))
8293 netdev_adjacent_sysfs_del(iter->dev, oldname,
8294 &iter->dev->adj_list.lower);
8295 netdev_adjacent_sysfs_add(iter->dev, dev,
8296 &iter->dev->adj_list.lower);
8299 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8300 if (!net_eq(net, dev_net(iter->dev)))
8302 netdev_adjacent_sysfs_del(iter->dev, oldname,
8303 &iter->dev->adj_list.upper);
8304 netdev_adjacent_sysfs_add(iter->dev, dev,
8305 &iter->dev->adj_list.upper);
8309 void *netdev_lower_dev_get_private(struct net_device *dev,
8310 struct net_device *lower_dev)
8312 struct netdev_adjacent *lower;
8316 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8320 return lower->private;
8322 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8326 * netdev_lower_state_changed - Dispatch event about lower device state change
8327 * @lower_dev: device
8328 * @lower_state_info: state to dispatch
8330 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8331 * The caller must hold the RTNL lock.
8333 void netdev_lower_state_changed(struct net_device *lower_dev,
8334 void *lower_state_info)
8336 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8337 .info.dev = lower_dev,
8341 changelowerstate_info.lower_state_info = lower_state_info;
8342 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8343 &changelowerstate_info.info);
8345 EXPORT_SYMBOL(netdev_lower_state_changed);
8347 static void dev_change_rx_flags(struct net_device *dev, int flags)
8349 const struct net_device_ops *ops = dev->netdev_ops;
8351 if (ops->ndo_change_rx_flags)
8352 ops->ndo_change_rx_flags(dev, flags);
8355 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8357 unsigned int old_flags = dev->flags;
8363 dev->flags |= IFF_PROMISC;
8364 dev->promiscuity += inc;
8365 if (dev->promiscuity == 0) {
8368 * If inc causes overflow, untouch promisc and return error.
8371 dev->flags &= ~IFF_PROMISC;
8373 dev->promiscuity -= inc;
8374 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
8378 if (dev->flags != old_flags) {
8379 netdev_info(dev, "%s promiscuous mode\n",
8380 dev->flags & IFF_PROMISC ? "entered" : "left");
8381 if (audit_enabled) {
8382 current_uid_gid(&uid, &gid);
8383 audit_log(audit_context(), GFP_ATOMIC,
8384 AUDIT_ANOM_PROMISCUOUS,
8385 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8386 dev->name, (dev->flags & IFF_PROMISC),
8387 (old_flags & IFF_PROMISC),
8388 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8389 from_kuid(&init_user_ns, uid),
8390 from_kgid(&init_user_ns, gid),
8391 audit_get_sessionid(current));
8394 dev_change_rx_flags(dev, IFF_PROMISC);
8397 __dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL);
8402 * dev_set_promiscuity - update promiscuity count on a device
8406 * Add or remove promiscuity from a device. While the count in the device
8407 * remains above zero the interface remains promiscuous. Once it hits zero
8408 * the device reverts back to normal filtering operation. A negative inc
8409 * value is used to drop promiscuity on the device.
8410 * Return 0 if successful or a negative errno code on error.
8412 int dev_set_promiscuity(struct net_device *dev, int inc)
8414 unsigned int old_flags = dev->flags;
8417 err = __dev_set_promiscuity(dev, inc, true);
8420 if (dev->flags != old_flags)
8421 dev_set_rx_mode(dev);
8424 EXPORT_SYMBOL(dev_set_promiscuity);
8426 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8428 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8432 dev->flags |= IFF_ALLMULTI;
8433 dev->allmulti += inc;
8434 if (dev->allmulti == 0) {
8437 * If inc causes overflow, untouch allmulti and return error.
8440 dev->flags &= ~IFF_ALLMULTI;
8442 dev->allmulti -= inc;
8443 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
8447 if (dev->flags ^ old_flags) {
8448 netdev_info(dev, "%s allmulticast mode\n",
8449 dev->flags & IFF_ALLMULTI ? "entered" : "left");
8450 dev_change_rx_flags(dev, IFF_ALLMULTI);
8451 dev_set_rx_mode(dev);
8453 __dev_notify_flags(dev, old_flags,
8454 dev->gflags ^ old_gflags, 0, NULL);
8460 * dev_set_allmulti - update allmulti count on a device
8464 * Add or remove reception of all multicast frames to a device. While the
8465 * count in the device remains above zero the interface remains listening
8466 * to all interfaces. Once it hits zero the device reverts back to normal
8467 * filtering operation. A negative @inc value is used to drop the counter
8468 * when releasing a resource needing all multicasts.
8469 * Return 0 if successful or a negative errno code on error.
8472 int dev_set_allmulti(struct net_device *dev, int inc)
8474 return __dev_set_allmulti(dev, inc, true);
8476 EXPORT_SYMBOL(dev_set_allmulti);
8479 * Upload unicast and multicast address lists to device and
8480 * configure RX filtering. When the device doesn't support unicast
8481 * filtering it is put in promiscuous mode while unicast addresses
8484 void __dev_set_rx_mode(struct net_device *dev)
8486 const struct net_device_ops *ops = dev->netdev_ops;
8488 /* dev_open will call this function so the list will stay sane. */
8489 if (!(dev->flags&IFF_UP))
8492 if (!netif_device_present(dev))
8495 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8496 /* Unicast addresses changes may only happen under the rtnl,
8497 * therefore calling __dev_set_promiscuity here is safe.
8499 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8500 __dev_set_promiscuity(dev, 1, false);
8501 dev->uc_promisc = true;
8502 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8503 __dev_set_promiscuity(dev, -1, false);
8504 dev->uc_promisc = false;
8508 if (ops->ndo_set_rx_mode)
8509 ops->ndo_set_rx_mode(dev);
8512 void dev_set_rx_mode(struct net_device *dev)
8514 netif_addr_lock_bh(dev);
8515 __dev_set_rx_mode(dev);
8516 netif_addr_unlock_bh(dev);
8520 * dev_get_flags - get flags reported to userspace
8523 * Get the combination of flag bits exported through APIs to userspace.
8525 unsigned int dev_get_flags(const struct net_device *dev)
8529 flags = (dev->flags & ~(IFF_PROMISC |
8534 (dev->gflags & (IFF_PROMISC |
8537 if (netif_running(dev)) {
8538 if (netif_oper_up(dev))
8539 flags |= IFF_RUNNING;
8540 if (netif_carrier_ok(dev))
8541 flags |= IFF_LOWER_UP;
8542 if (netif_dormant(dev))
8543 flags |= IFF_DORMANT;
8548 EXPORT_SYMBOL(dev_get_flags);
8550 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8551 struct netlink_ext_ack *extack)
8553 unsigned int old_flags = dev->flags;
8559 * Set the flags on our device.
8562 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8563 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8565 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8569 * Load in the correct multicast list now the flags have changed.
8572 if ((old_flags ^ flags) & IFF_MULTICAST)
8573 dev_change_rx_flags(dev, IFF_MULTICAST);
8575 dev_set_rx_mode(dev);
8578 * Have we downed the interface. We handle IFF_UP ourselves
8579 * according to user attempts to set it, rather than blindly
8584 if ((old_flags ^ flags) & IFF_UP) {
8585 if (old_flags & IFF_UP)
8588 ret = __dev_open(dev, extack);
8591 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8592 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8593 unsigned int old_flags = dev->flags;
8595 dev->gflags ^= IFF_PROMISC;
8597 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8598 if (dev->flags != old_flags)
8599 dev_set_rx_mode(dev);
8602 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8603 * is important. Some (broken) drivers set IFF_PROMISC, when
8604 * IFF_ALLMULTI is requested not asking us and not reporting.
8606 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8607 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8609 dev->gflags ^= IFF_ALLMULTI;
8610 __dev_set_allmulti(dev, inc, false);
8616 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8617 unsigned int gchanges, u32 portid,
8618 const struct nlmsghdr *nlh)
8620 unsigned int changes = dev->flags ^ old_flags;
8623 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh);
8625 if (changes & IFF_UP) {
8626 if (dev->flags & IFF_UP)
8627 call_netdevice_notifiers(NETDEV_UP, dev);
8629 call_netdevice_notifiers(NETDEV_DOWN, dev);
8632 if (dev->flags & IFF_UP &&
8633 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8634 struct netdev_notifier_change_info change_info = {
8638 .flags_changed = changes,
8641 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8646 * dev_change_flags - change device settings
8648 * @flags: device state flags
8649 * @extack: netlink extended ack
8651 * Change settings on device based state flags. The flags are
8652 * in the userspace exported format.
8654 int dev_change_flags(struct net_device *dev, unsigned int flags,
8655 struct netlink_ext_ack *extack)
8658 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8660 ret = __dev_change_flags(dev, flags, extack);
8664 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8665 __dev_notify_flags(dev, old_flags, changes, 0, NULL);
8668 EXPORT_SYMBOL(dev_change_flags);
8670 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8672 const struct net_device_ops *ops = dev->netdev_ops;
8674 if (ops->ndo_change_mtu)
8675 return ops->ndo_change_mtu(dev, new_mtu);
8677 /* Pairs with all the lockless reads of dev->mtu in the stack */
8678 WRITE_ONCE(dev->mtu, new_mtu);
8681 EXPORT_SYMBOL(__dev_set_mtu);
8683 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8684 struct netlink_ext_ack *extack)
8686 /* MTU must be positive, and in range */
8687 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8688 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8692 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8693 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8700 * dev_set_mtu_ext - Change maximum transfer unit
8702 * @new_mtu: new transfer unit
8703 * @extack: netlink extended ack
8705 * Change the maximum transfer size of the network device.
8707 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8708 struct netlink_ext_ack *extack)
8712 if (new_mtu == dev->mtu)
8715 err = dev_validate_mtu(dev, new_mtu, extack);
8719 if (!netif_device_present(dev))
8722 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8723 err = notifier_to_errno(err);
8727 orig_mtu = dev->mtu;
8728 err = __dev_set_mtu(dev, new_mtu);
8731 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8733 err = notifier_to_errno(err);
8735 /* setting mtu back and notifying everyone again,
8736 * so that they have a chance to revert changes.
8738 __dev_set_mtu(dev, orig_mtu);
8739 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8746 int dev_set_mtu(struct net_device *dev, int new_mtu)
8748 struct netlink_ext_ack extack;
8751 memset(&extack, 0, sizeof(extack));
8752 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8753 if (err && extack._msg)
8754 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8757 EXPORT_SYMBOL(dev_set_mtu);
8760 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8762 * @new_len: new tx queue length
8764 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8766 unsigned int orig_len = dev->tx_queue_len;
8769 if (new_len != (unsigned int)new_len)
8772 if (new_len != orig_len) {
8773 dev->tx_queue_len = new_len;
8774 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8775 res = notifier_to_errno(res);
8778 res = dev_qdisc_change_tx_queue_len(dev);
8786 netdev_err(dev, "refused to change device tx_queue_len\n");
8787 dev->tx_queue_len = orig_len;
8792 * dev_set_group - Change group this device belongs to
8794 * @new_group: group this device should belong to
8796 void dev_set_group(struct net_device *dev, int new_group)
8798 dev->group = new_group;
8802 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8804 * @addr: new address
8805 * @extack: netlink extended ack
8807 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8808 struct netlink_ext_ack *extack)
8810 struct netdev_notifier_pre_changeaddr_info info = {
8812 .info.extack = extack,
8817 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8818 return notifier_to_errno(rc);
8820 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8823 * dev_set_mac_address - Change Media Access Control Address
8826 * @extack: netlink extended ack
8828 * Change the hardware (MAC) address of the device
8830 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8831 struct netlink_ext_ack *extack)
8833 const struct net_device_ops *ops = dev->netdev_ops;
8836 if (!ops->ndo_set_mac_address)
8838 if (sa->sa_family != dev->type)
8840 if (!netif_device_present(dev))
8842 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8845 if (memcmp(dev->dev_addr, sa->sa_data, dev->addr_len)) {
8846 err = ops->ndo_set_mac_address(dev, sa);
8850 dev->addr_assign_type = NET_ADDR_SET;
8851 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8852 add_device_randomness(dev->dev_addr, dev->addr_len);
8855 EXPORT_SYMBOL(dev_set_mac_address);
8857 static DECLARE_RWSEM(dev_addr_sem);
8859 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
8860 struct netlink_ext_ack *extack)
8864 down_write(&dev_addr_sem);
8865 ret = dev_set_mac_address(dev, sa, extack);
8866 up_write(&dev_addr_sem);
8869 EXPORT_SYMBOL(dev_set_mac_address_user);
8871 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
8873 size_t size = sizeof(sa->sa_data_min);
8874 struct net_device *dev;
8877 down_read(&dev_addr_sem);
8880 dev = dev_get_by_name_rcu(net, dev_name);
8886 memset(sa->sa_data, 0, size);
8888 memcpy(sa->sa_data, dev->dev_addr,
8889 min_t(size_t, size, dev->addr_len));
8890 sa->sa_family = dev->type;
8894 up_read(&dev_addr_sem);
8897 EXPORT_SYMBOL(dev_get_mac_address);
8900 * dev_change_carrier - Change device carrier
8902 * @new_carrier: new value
8904 * Change device carrier
8906 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8908 const struct net_device_ops *ops = dev->netdev_ops;
8910 if (!ops->ndo_change_carrier)
8912 if (!netif_device_present(dev))
8914 return ops->ndo_change_carrier(dev, new_carrier);
8918 * dev_get_phys_port_id - Get device physical port ID
8922 * Get device physical port ID
8924 int dev_get_phys_port_id(struct net_device *dev,
8925 struct netdev_phys_item_id *ppid)
8927 const struct net_device_ops *ops = dev->netdev_ops;
8929 if (!ops->ndo_get_phys_port_id)
8931 return ops->ndo_get_phys_port_id(dev, ppid);
8935 * dev_get_phys_port_name - Get device physical port name
8938 * @len: limit of bytes to copy to name
8940 * Get device physical port name
8942 int dev_get_phys_port_name(struct net_device *dev,
8943 char *name, size_t len)
8945 const struct net_device_ops *ops = dev->netdev_ops;
8948 if (ops->ndo_get_phys_port_name) {
8949 err = ops->ndo_get_phys_port_name(dev, name, len);
8950 if (err != -EOPNOTSUPP)
8953 return devlink_compat_phys_port_name_get(dev, name, len);
8957 * dev_get_port_parent_id - Get the device's port parent identifier
8958 * @dev: network device
8959 * @ppid: pointer to a storage for the port's parent identifier
8960 * @recurse: allow/disallow recursion to lower devices
8962 * Get the devices's port parent identifier
8964 int dev_get_port_parent_id(struct net_device *dev,
8965 struct netdev_phys_item_id *ppid,
8968 const struct net_device_ops *ops = dev->netdev_ops;
8969 struct netdev_phys_item_id first = { };
8970 struct net_device *lower_dev;
8971 struct list_head *iter;
8974 if (ops->ndo_get_port_parent_id) {
8975 err = ops->ndo_get_port_parent_id(dev, ppid);
8976 if (err != -EOPNOTSUPP)
8980 err = devlink_compat_switch_id_get(dev, ppid);
8981 if (!recurse || err != -EOPNOTSUPP)
8984 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8985 err = dev_get_port_parent_id(lower_dev, ppid, true);
8990 else if (memcmp(&first, ppid, sizeof(*ppid)))
8996 EXPORT_SYMBOL(dev_get_port_parent_id);
8999 * netdev_port_same_parent_id - Indicate if two network devices have
9000 * the same port parent identifier
9001 * @a: first network device
9002 * @b: second network device
9004 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
9006 struct netdev_phys_item_id a_id = { };
9007 struct netdev_phys_item_id b_id = { };
9009 if (dev_get_port_parent_id(a, &a_id, true) ||
9010 dev_get_port_parent_id(b, &b_id, true))
9013 return netdev_phys_item_id_same(&a_id, &b_id);
9015 EXPORT_SYMBOL(netdev_port_same_parent_id);
9018 * dev_change_proto_down - set carrier according to proto_down.
9021 * @proto_down: new value
9023 int dev_change_proto_down(struct net_device *dev, bool proto_down)
9025 if (!(dev->priv_flags & IFF_CHANGE_PROTO_DOWN))
9027 if (!netif_device_present(dev))
9030 netif_carrier_off(dev);
9032 netif_carrier_on(dev);
9033 dev->proto_down = proto_down;
9038 * dev_change_proto_down_reason - proto down reason
9041 * @mask: proto down mask
9042 * @value: proto down value
9044 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
9050 dev->proto_down_reason = value;
9052 for_each_set_bit(b, &mask, 32) {
9053 if (value & (1 << b))
9054 dev->proto_down_reason |= BIT(b);
9056 dev->proto_down_reason &= ~BIT(b);
9061 struct bpf_xdp_link {
9062 struct bpf_link link;
9063 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
9067 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
9069 if (flags & XDP_FLAGS_HW_MODE)
9071 if (flags & XDP_FLAGS_DRV_MODE)
9072 return XDP_MODE_DRV;
9073 if (flags & XDP_FLAGS_SKB_MODE)
9074 return XDP_MODE_SKB;
9075 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
9078 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
9082 return generic_xdp_install;
9085 return dev->netdev_ops->ndo_bpf;
9091 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
9092 enum bpf_xdp_mode mode)
9094 return dev->xdp_state[mode].link;
9097 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
9098 enum bpf_xdp_mode mode)
9100 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
9103 return link->link.prog;
9104 return dev->xdp_state[mode].prog;
9107 u8 dev_xdp_prog_count(struct net_device *dev)
9112 for (i = 0; i < __MAX_XDP_MODE; i++)
9113 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
9117 EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
9119 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
9121 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
9123 return prog ? prog->aux->id : 0;
9126 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
9127 struct bpf_xdp_link *link)
9129 dev->xdp_state[mode].link = link;
9130 dev->xdp_state[mode].prog = NULL;
9133 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
9134 struct bpf_prog *prog)
9136 dev->xdp_state[mode].link = NULL;
9137 dev->xdp_state[mode].prog = prog;
9140 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
9141 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
9142 u32 flags, struct bpf_prog *prog)
9144 struct netdev_bpf xdp;
9147 memset(&xdp, 0, sizeof(xdp));
9148 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
9149 xdp.extack = extack;
9153 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
9154 * "moved" into driver), so they don't increment it on their own, but
9155 * they do decrement refcnt when program is detached or replaced.
9156 * Given net_device also owns link/prog, we need to bump refcnt here
9157 * to prevent drivers from underflowing it.
9161 err = bpf_op(dev, &xdp);
9168 if (mode != XDP_MODE_HW)
9169 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9174 static void dev_xdp_uninstall(struct net_device *dev)
9176 struct bpf_xdp_link *link;
9177 struct bpf_prog *prog;
9178 enum bpf_xdp_mode mode;
9183 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9184 prog = dev_xdp_prog(dev, mode);
9188 bpf_op = dev_xdp_bpf_op(dev, mode);
9192 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9194 /* auto-detach link from net device */
9195 link = dev_xdp_link(dev, mode);
9201 dev_xdp_set_link(dev, mode, NULL);
9205 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9206 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9207 struct bpf_prog *old_prog, u32 flags)
9209 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9210 struct bpf_prog *cur_prog;
9211 struct net_device *upper;
9212 struct list_head *iter;
9213 enum bpf_xdp_mode mode;
9219 /* either link or prog attachment, never both */
9220 if (link && (new_prog || old_prog))
9222 /* link supports only XDP mode flags */
9223 if (link && (flags & ~XDP_FLAGS_MODES)) {
9224 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9227 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9228 if (num_modes > 1) {
9229 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9232 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9233 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9234 NL_SET_ERR_MSG(extack,
9235 "More than one program loaded, unset mode is ambiguous");
9238 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9239 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9240 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9244 mode = dev_xdp_mode(dev, flags);
9245 /* can't replace attached link */
9246 if (dev_xdp_link(dev, mode)) {
9247 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9251 /* don't allow if an upper device already has a program */
9252 netdev_for_each_upper_dev_rcu(dev, upper, iter) {
9253 if (dev_xdp_prog_count(upper) > 0) {
9254 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
9259 cur_prog = dev_xdp_prog(dev, mode);
9260 /* can't replace attached prog with link */
9261 if (link && cur_prog) {
9262 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9265 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9266 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9270 /* put effective new program into new_prog */
9272 new_prog = link->link.prog;
9275 bool offload = mode == XDP_MODE_HW;
9276 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9277 ? XDP_MODE_DRV : XDP_MODE_SKB;
9279 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9280 NL_SET_ERR_MSG(extack, "XDP program already attached");
9283 if (!offload && dev_xdp_prog(dev, other_mode)) {
9284 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9287 if (!offload && bpf_prog_is_offloaded(new_prog->aux)) {
9288 NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
9291 if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) {
9292 NL_SET_ERR_MSG(extack, "Program bound to different device");
9295 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9296 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9299 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9300 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9305 /* don't call drivers if the effective program didn't change */
9306 if (new_prog != cur_prog) {
9307 bpf_op = dev_xdp_bpf_op(dev, mode);
9309 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9313 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9319 dev_xdp_set_link(dev, mode, link);
9321 dev_xdp_set_prog(dev, mode, new_prog);
9323 bpf_prog_put(cur_prog);
9328 static int dev_xdp_attach_link(struct net_device *dev,
9329 struct netlink_ext_ack *extack,
9330 struct bpf_xdp_link *link)
9332 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9335 static int dev_xdp_detach_link(struct net_device *dev,
9336 struct netlink_ext_ack *extack,
9337 struct bpf_xdp_link *link)
9339 enum bpf_xdp_mode mode;
9344 mode = dev_xdp_mode(dev, link->flags);
9345 if (dev_xdp_link(dev, mode) != link)
9348 bpf_op = dev_xdp_bpf_op(dev, mode);
9349 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9350 dev_xdp_set_link(dev, mode, NULL);
9354 static void bpf_xdp_link_release(struct bpf_link *link)
9356 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9360 /* if racing with net_device's tear down, xdp_link->dev might be
9361 * already NULL, in which case link was already auto-detached
9363 if (xdp_link->dev) {
9364 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9365 xdp_link->dev = NULL;
9371 static int bpf_xdp_link_detach(struct bpf_link *link)
9373 bpf_xdp_link_release(link);
9377 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9379 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9384 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9385 struct seq_file *seq)
9387 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9392 ifindex = xdp_link->dev->ifindex;
9395 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9398 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9399 struct bpf_link_info *info)
9401 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9406 ifindex = xdp_link->dev->ifindex;
9409 info->xdp.ifindex = ifindex;
9413 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9414 struct bpf_prog *old_prog)
9416 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9417 enum bpf_xdp_mode mode;
9423 /* link might have been auto-released already, so fail */
9424 if (!xdp_link->dev) {
9429 if (old_prog && link->prog != old_prog) {
9433 old_prog = link->prog;
9434 if (old_prog->type != new_prog->type ||
9435 old_prog->expected_attach_type != new_prog->expected_attach_type) {
9440 if (old_prog == new_prog) {
9441 /* no-op, don't disturb drivers */
9442 bpf_prog_put(new_prog);
9446 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9447 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9448 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9449 xdp_link->flags, new_prog);
9453 old_prog = xchg(&link->prog, new_prog);
9454 bpf_prog_put(old_prog);
9461 static const struct bpf_link_ops bpf_xdp_link_lops = {
9462 .release = bpf_xdp_link_release,
9463 .dealloc = bpf_xdp_link_dealloc,
9464 .detach = bpf_xdp_link_detach,
9465 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9466 .fill_link_info = bpf_xdp_link_fill_link_info,
9467 .update_prog = bpf_xdp_link_update,
9470 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9472 struct net *net = current->nsproxy->net_ns;
9473 struct bpf_link_primer link_primer;
9474 struct netlink_ext_ack extack = {};
9475 struct bpf_xdp_link *link;
9476 struct net_device *dev;
9480 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9486 link = kzalloc(sizeof(*link), GFP_USER);
9492 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9494 link->flags = attr->link_create.flags;
9496 err = bpf_link_prime(&link->link, &link_primer);
9502 err = dev_xdp_attach_link(dev, &extack, link);
9507 bpf_link_cleanup(&link_primer);
9508 trace_bpf_xdp_link_attach_failed(extack._msg);
9512 fd = bpf_link_settle(&link_primer);
9513 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9526 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9528 * @extack: netlink extended ack
9529 * @fd: new program fd or negative value to clear
9530 * @expected_fd: old program fd that userspace expects to replace or clear
9531 * @flags: xdp-related flags
9533 * Set or clear a bpf program for a device
9535 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9536 int fd, int expected_fd, u32 flags)
9538 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9539 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9545 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9546 mode != XDP_MODE_SKB);
9547 if (IS_ERR(new_prog))
9548 return PTR_ERR(new_prog);
9551 if (expected_fd >= 0) {
9552 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9553 mode != XDP_MODE_SKB);
9554 if (IS_ERR(old_prog)) {
9555 err = PTR_ERR(old_prog);
9561 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9564 if (err && new_prog)
9565 bpf_prog_put(new_prog);
9567 bpf_prog_put(old_prog);
9572 * dev_new_index - allocate an ifindex
9573 * @net: the applicable net namespace
9575 * Returns a suitable unique value for a new device interface
9576 * number. The caller must hold the rtnl semaphore or the
9577 * dev_base_lock to be sure it remains unique.
9579 static int dev_new_index(struct net *net)
9581 int ifindex = net->ifindex;
9586 if (!__dev_get_by_index(net, ifindex))
9587 return net->ifindex = ifindex;
9591 /* Delayed registration/unregisteration */
9592 LIST_HEAD(net_todo_list);
9593 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9595 static void net_set_todo(struct net_device *dev)
9597 list_add_tail(&dev->todo_list, &net_todo_list);
9598 atomic_inc(&dev_net(dev)->dev_unreg_count);
9601 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9602 struct net_device *upper, netdev_features_t features)
9604 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9605 netdev_features_t feature;
9608 for_each_netdev_feature(upper_disables, feature_bit) {
9609 feature = __NETIF_F_BIT(feature_bit);
9610 if (!(upper->wanted_features & feature)
9611 && (features & feature)) {
9612 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9613 &feature, upper->name);
9614 features &= ~feature;
9621 static void netdev_sync_lower_features(struct net_device *upper,
9622 struct net_device *lower, netdev_features_t features)
9624 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9625 netdev_features_t feature;
9628 for_each_netdev_feature(upper_disables, feature_bit) {
9629 feature = __NETIF_F_BIT(feature_bit);
9630 if (!(features & feature) && (lower->features & feature)) {
9631 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9632 &feature, lower->name);
9633 lower->wanted_features &= ~feature;
9634 __netdev_update_features(lower);
9636 if (unlikely(lower->features & feature))
9637 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9638 &feature, lower->name);
9640 netdev_features_change(lower);
9645 static netdev_features_t netdev_fix_features(struct net_device *dev,
9646 netdev_features_t features)
9648 /* Fix illegal checksum combinations */
9649 if ((features & NETIF_F_HW_CSUM) &&
9650 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9651 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9652 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9655 /* TSO requires that SG is present as well. */
9656 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9657 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9658 features &= ~NETIF_F_ALL_TSO;
9661 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9662 !(features & NETIF_F_IP_CSUM)) {
9663 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9664 features &= ~NETIF_F_TSO;
9665 features &= ~NETIF_F_TSO_ECN;
9668 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9669 !(features & NETIF_F_IPV6_CSUM)) {
9670 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9671 features &= ~NETIF_F_TSO6;
9674 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9675 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9676 features &= ~NETIF_F_TSO_MANGLEID;
9678 /* TSO ECN requires that TSO is present as well. */
9679 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9680 features &= ~NETIF_F_TSO_ECN;
9682 /* Software GSO depends on SG. */
9683 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9684 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9685 features &= ~NETIF_F_GSO;
9688 /* GSO partial features require GSO partial be set */
9689 if ((features & dev->gso_partial_features) &&
9690 !(features & NETIF_F_GSO_PARTIAL)) {
9692 "Dropping partially supported GSO features since no GSO partial.\n");
9693 features &= ~dev->gso_partial_features;
9696 if (!(features & NETIF_F_RXCSUM)) {
9697 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9698 * successfully merged by hardware must also have the
9699 * checksum verified by hardware. If the user does not
9700 * want to enable RXCSUM, logically, we should disable GRO_HW.
9702 if (features & NETIF_F_GRO_HW) {
9703 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9704 features &= ~NETIF_F_GRO_HW;
9708 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9709 if (features & NETIF_F_RXFCS) {
9710 if (features & NETIF_F_LRO) {
9711 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9712 features &= ~NETIF_F_LRO;
9715 if (features & NETIF_F_GRO_HW) {
9716 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9717 features &= ~NETIF_F_GRO_HW;
9721 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
9722 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
9723 features &= ~NETIF_F_LRO;
9726 if (features & NETIF_F_HW_TLS_TX) {
9727 bool ip_csum = (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) ==
9728 (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
9729 bool hw_csum = features & NETIF_F_HW_CSUM;
9731 if (!ip_csum && !hw_csum) {
9732 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
9733 features &= ~NETIF_F_HW_TLS_TX;
9737 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
9738 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
9739 features &= ~NETIF_F_HW_TLS_RX;
9745 int __netdev_update_features(struct net_device *dev)
9747 struct net_device *upper, *lower;
9748 netdev_features_t features;
9749 struct list_head *iter;
9754 features = netdev_get_wanted_features(dev);
9756 if (dev->netdev_ops->ndo_fix_features)
9757 features = dev->netdev_ops->ndo_fix_features(dev, features);
9759 /* driver might be less strict about feature dependencies */
9760 features = netdev_fix_features(dev, features);
9762 /* some features can't be enabled if they're off on an upper device */
9763 netdev_for_each_upper_dev_rcu(dev, upper, iter)
9764 features = netdev_sync_upper_features(dev, upper, features);
9766 if (dev->features == features)
9769 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9770 &dev->features, &features);
9772 if (dev->netdev_ops->ndo_set_features)
9773 err = dev->netdev_ops->ndo_set_features(dev, features);
9777 if (unlikely(err < 0)) {
9779 "set_features() failed (%d); wanted %pNF, left %pNF\n",
9780 err, &features, &dev->features);
9781 /* return non-0 since some features might have changed and
9782 * it's better to fire a spurious notification than miss it
9788 /* some features must be disabled on lower devices when disabled
9789 * on an upper device (think: bonding master or bridge)
9791 netdev_for_each_lower_dev(dev, lower, iter)
9792 netdev_sync_lower_features(dev, lower, features);
9795 netdev_features_t diff = features ^ dev->features;
9797 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9798 /* udp_tunnel_{get,drop}_rx_info both need
9799 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9800 * device, or they won't do anything.
9801 * Thus we need to update dev->features
9802 * *before* calling udp_tunnel_get_rx_info,
9803 * but *after* calling udp_tunnel_drop_rx_info.
9805 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9806 dev->features = features;
9807 udp_tunnel_get_rx_info(dev);
9809 udp_tunnel_drop_rx_info(dev);
9813 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9814 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9815 dev->features = features;
9816 err |= vlan_get_rx_ctag_filter_info(dev);
9818 vlan_drop_rx_ctag_filter_info(dev);
9822 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9823 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9824 dev->features = features;
9825 err |= vlan_get_rx_stag_filter_info(dev);
9827 vlan_drop_rx_stag_filter_info(dev);
9831 dev->features = features;
9834 return err < 0 ? 0 : 1;
9838 * netdev_update_features - recalculate device features
9839 * @dev: the device to check
9841 * Recalculate dev->features set and send notifications if it
9842 * has changed. Should be called after driver or hardware dependent
9843 * conditions might have changed that influence the features.
9845 void netdev_update_features(struct net_device *dev)
9847 if (__netdev_update_features(dev))
9848 netdev_features_change(dev);
9850 EXPORT_SYMBOL(netdev_update_features);
9853 * netdev_change_features - recalculate device features
9854 * @dev: the device to check
9856 * Recalculate dev->features set and send notifications even
9857 * if they have not changed. Should be called instead of
9858 * netdev_update_features() if also dev->vlan_features might
9859 * have changed to allow the changes to be propagated to stacked
9862 void netdev_change_features(struct net_device *dev)
9864 __netdev_update_features(dev);
9865 netdev_features_change(dev);
9867 EXPORT_SYMBOL(netdev_change_features);
9870 * netif_stacked_transfer_operstate - transfer operstate
9871 * @rootdev: the root or lower level device to transfer state from
9872 * @dev: the device to transfer operstate to
9874 * Transfer operational state from root to device. This is normally
9875 * called when a stacking relationship exists between the root
9876 * device and the device(a leaf device).
9878 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9879 struct net_device *dev)
9881 if (rootdev->operstate == IF_OPER_DORMANT)
9882 netif_dormant_on(dev);
9884 netif_dormant_off(dev);
9886 if (rootdev->operstate == IF_OPER_TESTING)
9887 netif_testing_on(dev);
9889 netif_testing_off(dev);
9891 if (netif_carrier_ok(rootdev))
9892 netif_carrier_on(dev);
9894 netif_carrier_off(dev);
9896 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9898 static int netif_alloc_rx_queues(struct net_device *dev)
9900 unsigned int i, count = dev->num_rx_queues;
9901 struct netdev_rx_queue *rx;
9902 size_t sz = count * sizeof(*rx);
9907 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9913 for (i = 0; i < count; i++) {
9916 /* XDP RX-queue setup */
9917 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
9924 /* Rollback successful reg's and free other resources */
9926 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9932 static void netif_free_rx_queues(struct net_device *dev)
9934 unsigned int i, count = dev->num_rx_queues;
9936 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9940 for (i = 0; i < count; i++)
9941 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9946 static void netdev_init_one_queue(struct net_device *dev,
9947 struct netdev_queue *queue, void *_unused)
9949 /* Initialize queue lock */
9950 spin_lock_init(&queue->_xmit_lock);
9951 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
9952 queue->xmit_lock_owner = -1;
9953 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
9956 dql_init(&queue->dql, HZ);
9960 static void netif_free_tx_queues(struct net_device *dev)
9965 static int netif_alloc_netdev_queues(struct net_device *dev)
9967 unsigned int count = dev->num_tx_queues;
9968 struct netdev_queue *tx;
9969 size_t sz = count * sizeof(*tx);
9971 if (count < 1 || count > 0xffff)
9974 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9980 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
9981 spin_lock_init(&dev->tx_global_lock);
9986 void netif_tx_stop_all_queues(struct net_device *dev)
9990 for (i = 0; i < dev->num_tx_queues; i++) {
9991 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
9993 netif_tx_stop_queue(txq);
9996 EXPORT_SYMBOL(netif_tx_stop_all_queues);
9999 * register_netdevice() - register a network device
10000 * @dev: device to register
10002 * Take a prepared network device structure and make it externally accessible.
10003 * A %NETDEV_REGISTER message is sent to the netdev notifier chain.
10004 * Callers must hold the rtnl lock - you may want register_netdev()
10007 int register_netdevice(struct net_device *dev)
10010 struct net *net = dev_net(dev);
10012 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
10013 NETDEV_FEATURE_COUNT);
10014 BUG_ON(dev_boot_phase);
10019 /* When net_device's are persistent, this will be fatal. */
10020 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
10023 ret = ethtool_check_ops(dev->ethtool_ops);
10027 spin_lock_init(&dev->addr_list_lock);
10028 netdev_set_addr_lockdep_class(dev);
10030 ret = dev_get_valid_name(net, dev, dev->name);
10035 dev->name_node = netdev_name_node_head_alloc(dev);
10036 if (!dev->name_node)
10039 /* Init, if this function is available */
10040 if (dev->netdev_ops->ndo_init) {
10041 ret = dev->netdev_ops->ndo_init(dev);
10045 goto err_free_name;
10049 if (((dev->hw_features | dev->features) &
10050 NETIF_F_HW_VLAN_CTAG_FILTER) &&
10051 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
10052 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
10053 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
10060 dev->ifindex = dev_new_index(net);
10061 else if (__dev_get_by_index(net, dev->ifindex))
10064 /* Transfer changeable features to wanted_features and enable
10065 * software offloads (GSO and GRO).
10067 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
10068 dev->features |= NETIF_F_SOFT_FEATURES;
10070 if (dev->udp_tunnel_nic_info) {
10071 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10072 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10075 dev->wanted_features = dev->features & dev->hw_features;
10077 if (!(dev->flags & IFF_LOOPBACK))
10078 dev->hw_features |= NETIF_F_NOCACHE_COPY;
10080 /* If IPv4 TCP segmentation offload is supported we should also
10081 * allow the device to enable segmenting the frame with the option
10082 * of ignoring a static IP ID value. This doesn't enable the
10083 * feature itself but allows the user to enable it later.
10085 if (dev->hw_features & NETIF_F_TSO)
10086 dev->hw_features |= NETIF_F_TSO_MANGLEID;
10087 if (dev->vlan_features & NETIF_F_TSO)
10088 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
10089 if (dev->mpls_features & NETIF_F_TSO)
10090 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
10091 if (dev->hw_enc_features & NETIF_F_TSO)
10092 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
10094 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
10096 dev->vlan_features |= NETIF_F_HIGHDMA;
10098 /* Make NETIF_F_SG inheritable to tunnel devices.
10100 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
10102 /* Make NETIF_F_SG inheritable to MPLS.
10104 dev->mpls_features |= NETIF_F_SG;
10106 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
10107 ret = notifier_to_errno(ret);
10111 ret = netdev_register_kobject(dev);
10112 write_lock(&dev_base_lock);
10113 dev->reg_state = ret ? NETREG_UNREGISTERED : NETREG_REGISTERED;
10114 write_unlock(&dev_base_lock);
10116 goto err_uninit_notify;
10118 __netdev_update_features(dev);
10121 * Default initial state at registry is that the
10122 * device is present.
10125 set_bit(__LINK_STATE_PRESENT, &dev->state);
10127 linkwatch_init_dev(dev);
10129 dev_init_scheduler(dev);
10131 netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL);
10132 list_netdevice(dev);
10134 add_device_randomness(dev->dev_addr, dev->addr_len);
10136 /* If the device has permanent device address, driver should
10137 * set dev_addr and also addr_assign_type should be set to
10138 * NET_ADDR_PERM (default value).
10140 if (dev->addr_assign_type == NET_ADDR_PERM)
10141 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
10143 /* Notify protocols, that a new device appeared. */
10144 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
10145 ret = notifier_to_errno(ret);
10147 /* Expect explicit free_netdev() on failure */
10148 dev->needs_free_netdev = false;
10149 unregister_netdevice_queue(dev, NULL);
10153 * Prevent userspace races by waiting until the network
10154 * device is fully setup before sending notifications.
10156 if (!dev->rtnl_link_ops ||
10157 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10158 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
10164 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
10166 if (dev->netdev_ops->ndo_uninit)
10167 dev->netdev_ops->ndo_uninit(dev);
10168 if (dev->priv_destructor)
10169 dev->priv_destructor(dev);
10171 netdev_name_node_free(dev->name_node);
10174 EXPORT_SYMBOL(register_netdevice);
10177 * init_dummy_netdev - init a dummy network device for NAPI
10178 * @dev: device to init
10180 * This takes a network device structure and initialize the minimum
10181 * amount of fields so it can be used to schedule NAPI polls without
10182 * registering a full blown interface. This is to be used by drivers
10183 * that need to tie several hardware interfaces to a single NAPI
10184 * poll scheduler due to HW limitations.
10186 int init_dummy_netdev(struct net_device *dev)
10188 /* Clear everything. Note we don't initialize spinlocks
10189 * are they aren't supposed to be taken by any of the
10190 * NAPI code and this dummy netdev is supposed to be
10191 * only ever used for NAPI polls
10193 memset(dev, 0, sizeof(struct net_device));
10195 /* make sure we BUG if trying to hit standard
10196 * register/unregister code path
10198 dev->reg_state = NETREG_DUMMY;
10200 /* NAPI wants this */
10201 INIT_LIST_HEAD(&dev->napi_list);
10203 /* a dummy interface is started by default */
10204 set_bit(__LINK_STATE_PRESENT, &dev->state);
10205 set_bit(__LINK_STATE_START, &dev->state);
10207 /* napi_busy_loop stats accounting wants this */
10208 dev_net_set(dev, &init_net);
10210 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10211 * because users of this 'device' dont need to change
10217 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10221 * register_netdev - register a network device
10222 * @dev: device to register
10224 * Take a completed network device structure and add it to the kernel
10225 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10226 * chain. 0 is returned on success. A negative errno code is returned
10227 * on a failure to set up the device, or if the name is a duplicate.
10229 * This is a wrapper around register_netdevice that takes the rtnl semaphore
10230 * and expands the device name if you passed a format string to
10233 int register_netdev(struct net_device *dev)
10237 if (rtnl_lock_killable())
10239 err = register_netdevice(dev);
10243 EXPORT_SYMBOL(register_netdev);
10245 int netdev_refcnt_read(const struct net_device *dev)
10247 #ifdef CONFIG_PCPU_DEV_REFCNT
10250 for_each_possible_cpu(i)
10251 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10254 return refcount_read(&dev->dev_refcnt);
10257 EXPORT_SYMBOL(netdev_refcnt_read);
10259 int netdev_unregister_timeout_secs __read_mostly = 10;
10261 #define WAIT_REFS_MIN_MSECS 1
10262 #define WAIT_REFS_MAX_MSECS 250
10264 * netdev_wait_allrefs_any - wait until all references are gone.
10265 * @list: list of net_devices to wait on
10267 * This is called when unregistering network devices.
10269 * Any protocol or device that holds a reference should register
10270 * for netdevice notification, and cleanup and put back the
10271 * reference if they receive an UNREGISTER event.
10272 * We can get stuck here if buggy protocols don't correctly
10275 static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
10277 unsigned long rebroadcast_time, warning_time;
10278 struct net_device *dev;
10281 rebroadcast_time = warning_time = jiffies;
10283 list_for_each_entry(dev, list, todo_list)
10284 if (netdev_refcnt_read(dev) == 1)
10288 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10291 /* Rebroadcast unregister notification */
10292 list_for_each_entry(dev, list, todo_list)
10293 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10299 list_for_each_entry(dev, list, todo_list)
10300 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10302 /* We must not have linkwatch events
10303 * pending on unregister. If this
10304 * happens, we simply run the queue
10305 * unscheduled, resulting in a noop
10308 linkwatch_run_queue();
10314 rebroadcast_time = jiffies;
10319 wait = WAIT_REFS_MIN_MSECS;
10322 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10325 list_for_each_entry(dev, list, todo_list)
10326 if (netdev_refcnt_read(dev) == 1)
10329 if (time_after(jiffies, warning_time +
10330 READ_ONCE(netdev_unregister_timeout_secs) * HZ)) {
10331 list_for_each_entry(dev, list, todo_list) {
10332 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10333 dev->name, netdev_refcnt_read(dev));
10334 ref_tracker_dir_print(&dev->refcnt_tracker, 10);
10337 warning_time = jiffies;
10342 /* The sequence is:
10346 * register_netdevice(x1);
10347 * register_netdevice(x2);
10349 * unregister_netdevice(y1);
10350 * unregister_netdevice(y2);
10356 * We are invoked by rtnl_unlock().
10357 * This allows us to deal with problems:
10358 * 1) We can delete sysfs objects which invoke hotplug
10359 * without deadlocking with linkwatch via keventd.
10360 * 2) Since we run with the RTNL semaphore not held, we can sleep
10361 * safely in order to wait for the netdev refcnt to drop to zero.
10363 * We must not return until all unregister events added during
10364 * the interval the lock was held have been completed.
10366 void netdev_run_todo(void)
10368 struct net_device *dev, *tmp;
10369 struct list_head list;
10370 #ifdef CONFIG_LOCKDEP
10371 struct list_head unlink_list;
10373 list_replace_init(&net_unlink_list, &unlink_list);
10375 while (!list_empty(&unlink_list)) {
10376 struct net_device *dev = list_first_entry(&unlink_list,
10379 list_del_init(&dev->unlink_list);
10380 dev->nested_level = dev->lower_level - 1;
10384 /* Snapshot list, allow later requests */
10385 list_replace_init(&net_todo_list, &list);
10389 /* Wait for rcu callbacks to finish before next phase */
10390 if (!list_empty(&list))
10393 list_for_each_entry_safe(dev, tmp, &list, todo_list) {
10394 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10395 netdev_WARN(dev, "run_todo but not unregistering\n");
10396 list_del(&dev->todo_list);
10400 write_lock(&dev_base_lock);
10401 dev->reg_state = NETREG_UNREGISTERED;
10402 write_unlock(&dev_base_lock);
10403 linkwatch_forget_dev(dev);
10406 while (!list_empty(&list)) {
10407 dev = netdev_wait_allrefs_any(&list);
10408 list_del(&dev->todo_list);
10411 BUG_ON(netdev_refcnt_read(dev) != 1);
10412 BUG_ON(!list_empty(&dev->ptype_all));
10413 BUG_ON(!list_empty(&dev->ptype_specific));
10414 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10415 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10417 if (dev->priv_destructor)
10418 dev->priv_destructor(dev);
10419 if (dev->needs_free_netdev)
10422 if (atomic_dec_and_test(&dev_net(dev)->dev_unreg_count))
10423 wake_up(&netdev_unregistering_wq);
10425 /* Free network device */
10426 kobject_put(&dev->dev.kobj);
10430 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10431 * all the same fields in the same order as net_device_stats, with only
10432 * the type differing, but rtnl_link_stats64 may have additional fields
10433 * at the end for newer counters.
10435 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10436 const struct net_device_stats *netdev_stats)
10438 size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t);
10439 const atomic_long_t *src = (atomic_long_t *)netdev_stats;
10440 u64 *dst = (u64 *)stats64;
10442 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10443 for (i = 0; i < n; i++)
10444 dst[i] = (unsigned long)atomic_long_read(&src[i]);
10445 /* zero out counters that only exist in rtnl_link_stats64 */
10446 memset((char *)stats64 + n * sizeof(u64), 0,
10447 sizeof(*stats64) - n * sizeof(u64));
10449 EXPORT_SYMBOL(netdev_stats_to_stats64);
10451 struct net_device_core_stats __percpu *netdev_core_stats_alloc(struct net_device *dev)
10453 struct net_device_core_stats __percpu *p;
10455 p = alloc_percpu_gfp(struct net_device_core_stats,
10456 GFP_ATOMIC | __GFP_NOWARN);
10458 if (p && cmpxchg(&dev->core_stats, NULL, p))
10461 /* This READ_ONCE() pairs with the cmpxchg() above */
10462 return READ_ONCE(dev->core_stats);
10464 EXPORT_SYMBOL(netdev_core_stats_alloc);
10467 * dev_get_stats - get network device statistics
10468 * @dev: device to get statistics from
10469 * @storage: place to store stats
10471 * Get network statistics from device. Return @storage.
10472 * The device driver may provide its own method by setting
10473 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10474 * otherwise the internal statistics structure is used.
10476 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10477 struct rtnl_link_stats64 *storage)
10479 const struct net_device_ops *ops = dev->netdev_ops;
10480 const struct net_device_core_stats __percpu *p;
10482 if (ops->ndo_get_stats64) {
10483 memset(storage, 0, sizeof(*storage));
10484 ops->ndo_get_stats64(dev, storage);
10485 } else if (ops->ndo_get_stats) {
10486 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10488 netdev_stats_to_stats64(storage, &dev->stats);
10491 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10492 p = READ_ONCE(dev->core_stats);
10494 const struct net_device_core_stats *core_stats;
10497 for_each_possible_cpu(i) {
10498 core_stats = per_cpu_ptr(p, i);
10499 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
10500 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
10501 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
10502 storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped);
10507 EXPORT_SYMBOL(dev_get_stats);
10510 * dev_fetch_sw_netstats - get per-cpu network device statistics
10511 * @s: place to store stats
10512 * @netstats: per-cpu network stats to read from
10514 * Read per-cpu network statistics and populate the related fields in @s.
10516 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10517 const struct pcpu_sw_netstats __percpu *netstats)
10521 for_each_possible_cpu(cpu) {
10522 u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
10523 const struct pcpu_sw_netstats *stats;
10524 unsigned int start;
10526 stats = per_cpu_ptr(netstats, cpu);
10528 start = u64_stats_fetch_begin(&stats->syncp);
10529 rx_packets = u64_stats_read(&stats->rx_packets);
10530 rx_bytes = u64_stats_read(&stats->rx_bytes);
10531 tx_packets = u64_stats_read(&stats->tx_packets);
10532 tx_bytes = u64_stats_read(&stats->tx_bytes);
10533 } while (u64_stats_fetch_retry(&stats->syncp, start));
10535 s->rx_packets += rx_packets;
10536 s->rx_bytes += rx_bytes;
10537 s->tx_packets += tx_packets;
10538 s->tx_bytes += tx_bytes;
10541 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10544 * dev_get_tstats64 - ndo_get_stats64 implementation
10545 * @dev: device to get statistics from
10546 * @s: place to store stats
10548 * Populate @s from dev->stats and dev->tstats. Can be used as
10549 * ndo_get_stats64() callback.
10551 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
10553 netdev_stats_to_stats64(s, &dev->stats);
10554 dev_fetch_sw_netstats(s, dev->tstats);
10556 EXPORT_SYMBOL_GPL(dev_get_tstats64);
10558 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10560 struct netdev_queue *queue = dev_ingress_queue(dev);
10562 #ifdef CONFIG_NET_CLS_ACT
10565 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10568 netdev_init_one_queue(dev, queue, NULL);
10569 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10570 RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc);
10571 rcu_assign_pointer(dev->ingress_queue, queue);
10576 static const struct ethtool_ops default_ethtool_ops;
10578 void netdev_set_default_ethtool_ops(struct net_device *dev,
10579 const struct ethtool_ops *ops)
10581 if (dev->ethtool_ops == &default_ethtool_ops)
10582 dev->ethtool_ops = ops;
10584 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10587 * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default
10588 * @dev: netdev to enable the IRQ coalescing on
10590 * Sets a conservative default for SW IRQ coalescing. Users can use
10591 * sysfs attributes to override the default values.
10593 void netdev_sw_irq_coalesce_default_on(struct net_device *dev)
10595 WARN_ON(dev->reg_state == NETREG_REGISTERED);
10597 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
10598 dev->gro_flush_timeout = 20000;
10599 dev->napi_defer_hard_irqs = 1;
10602 EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on);
10604 void netdev_freemem(struct net_device *dev)
10606 char *addr = (char *)dev - dev->padded;
10612 * alloc_netdev_mqs - allocate network device
10613 * @sizeof_priv: size of private data to allocate space for
10614 * @name: device name format string
10615 * @name_assign_type: origin of device name
10616 * @setup: callback to initialize device
10617 * @txqs: the number of TX subqueues to allocate
10618 * @rxqs: the number of RX subqueues to allocate
10620 * Allocates a struct net_device with private data area for driver use
10621 * and performs basic initialization. Also allocates subqueue structs
10622 * for each queue on the device.
10624 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10625 unsigned char name_assign_type,
10626 void (*setup)(struct net_device *),
10627 unsigned int txqs, unsigned int rxqs)
10629 struct net_device *dev;
10630 unsigned int alloc_size;
10631 struct net_device *p;
10633 BUG_ON(strlen(name) >= sizeof(dev->name));
10636 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10641 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10645 alloc_size = sizeof(struct net_device);
10647 /* ensure 32-byte alignment of private area */
10648 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10649 alloc_size += sizeof_priv;
10651 /* ensure 32-byte alignment of whole construct */
10652 alloc_size += NETDEV_ALIGN - 1;
10654 p = kvzalloc(alloc_size, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10658 dev = PTR_ALIGN(p, NETDEV_ALIGN);
10659 dev->padded = (char *)dev - (char *)p;
10661 ref_tracker_dir_init(&dev->refcnt_tracker, 128, name);
10662 #ifdef CONFIG_PCPU_DEV_REFCNT
10663 dev->pcpu_refcnt = alloc_percpu(int);
10664 if (!dev->pcpu_refcnt)
10668 refcount_set(&dev->dev_refcnt, 1);
10671 if (dev_addr_init(dev))
10677 dev_net_set(dev, &init_net);
10679 dev->gso_max_size = GSO_LEGACY_MAX_SIZE;
10680 dev->xdp_zc_max_segs = 1;
10681 dev->gso_max_segs = GSO_MAX_SEGS;
10682 dev->gro_max_size = GRO_LEGACY_MAX_SIZE;
10683 dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE;
10684 dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE;
10685 dev->tso_max_size = TSO_LEGACY_MAX_SIZE;
10686 dev->tso_max_segs = TSO_MAX_SEGS;
10687 dev->upper_level = 1;
10688 dev->lower_level = 1;
10689 #ifdef CONFIG_LOCKDEP
10690 dev->nested_level = 0;
10691 INIT_LIST_HEAD(&dev->unlink_list);
10694 INIT_LIST_HEAD(&dev->napi_list);
10695 INIT_LIST_HEAD(&dev->unreg_list);
10696 INIT_LIST_HEAD(&dev->close_list);
10697 INIT_LIST_HEAD(&dev->link_watch_list);
10698 INIT_LIST_HEAD(&dev->adj_list.upper);
10699 INIT_LIST_HEAD(&dev->adj_list.lower);
10700 INIT_LIST_HEAD(&dev->ptype_all);
10701 INIT_LIST_HEAD(&dev->ptype_specific);
10702 INIT_LIST_HEAD(&dev->net_notifier_list);
10703 #ifdef CONFIG_NET_SCHED
10704 hash_init(dev->qdisc_hash);
10706 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10709 if (!dev->tx_queue_len) {
10710 dev->priv_flags |= IFF_NO_QUEUE;
10711 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10714 dev->num_tx_queues = txqs;
10715 dev->real_num_tx_queues = txqs;
10716 if (netif_alloc_netdev_queues(dev))
10719 dev->num_rx_queues = rxqs;
10720 dev->real_num_rx_queues = rxqs;
10721 if (netif_alloc_rx_queues(dev))
10724 strcpy(dev->name, name);
10725 dev->name_assign_type = name_assign_type;
10726 dev->group = INIT_NETDEV_GROUP;
10727 if (!dev->ethtool_ops)
10728 dev->ethtool_ops = &default_ethtool_ops;
10730 nf_hook_netdev_init(dev);
10739 #ifdef CONFIG_PCPU_DEV_REFCNT
10740 free_percpu(dev->pcpu_refcnt);
10743 netdev_freemem(dev);
10746 EXPORT_SYMBOL(alloc_netdev_mqs);
10749 * free_netdev - free network device
10752 * This function does the last stage of destroying an allocated device
10753 * interface. The reference to the device object is released. If this
10754 * is the last reference then it will be freed.Must be called in process
10757 void free_netdev(struct net_device *dev)
10759 struct napi_struct *p, *n;
10763 /* When called immediately after register_netdevice() failed the unwind
10764 * handling may still be dismantling the device. Handle that case by
10765 * deferring the free.
10767 if (dev->reg_state == NETREG_UNREGISTERING) {
10769 dev->needs_free_netdev = true;
10773 netif_free_tx_queues(dev);
10774 netif_free_rx_queues(dev);
10776 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10778 /* Flush device addresses */
10779 dev_addr_flush(dev);
10781 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10784 ref_tracker_dir_exit(&dev->refcnt_tracker);
10785 #ifdef CONFIG_PCPU_DEV_REFCNT
10786 free_percpu(dev->pcpu_refcnt);
10787 dev->pcpu_refcnt = NULL;
10789 free_percpu(dev->core_stats);
10790 dev->core_stats = NULL;
10791 free_percpu(dev->xdp_bulkq);
10792 dev->xdp_bulkq = NULL;
10794 /* Compatibility with error handling in drivers */
10795 if (dev->reg_state == NETREG_UNINITIALIZED) {
10796 netdev_freemem(dev);
10800 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
10801 dev->reg_state = NETREG_RELEASED;
10803 /* will free via device release */
10804 put_device(&dev->dev);
10806 EXPORT_SYMBOL(free_netdev);
10809 * synchronize_net - Synchronize with packet receive processing
10811 * Wait for packets currently being received to be done.
10812 * Does not block later packets from starting.
10814 void synchronize_net(void)
10817 if (rtnl_is_locked())
10818 synchronize_rcu_expedited();
10822 EXPORT_SYMBOL(synchronize_net);
10825 * unregister_netdevice_queue - remove device from the kernel
10829 * This function shuts down a device interface and removes it
10830 * from the kernel tables.
10831 * If head not NULL, device is queued to be unregistered later.
10833 * Callers must hold the rtnl semaphore. You may want
10834 * unregister_netdev() instead of this.
10837 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
10842 list_move_tail(&dev->unreg_list, head);
10846 list_add(&dev->unreg_list, &single);
10847 unregister_netdevice_many(&single);
10850 EXPORT_SYMBOL(unregister_netdevice_queue);
10852 void unregister_netdevice_many_notify(struct list_head *head,
10853 u32 portid, const struct nlmsghdr *nlh)
10855 struct net_device *dev, *tmp;
10856 LIST_HEAD(close_head);
10858 BUG_ON(dev_boot_phase);
10861 if (list_empty(head))
10864 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
10865 /* Some devices call without registering
10866 * for initialization unwind. Remove those
10867 * devices and proceed with the remaining.
10869 if (dev->reg_state == NETREG_UNINITIALIZED) {
10870 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
10874 list_del(&dev->unreg_list);
10877 dev->dismantle = true;
10878 BUG_ON(dev->reg_state != NETREG_REGISTERED);
10881 /* If device is running, close it first. */
10882 list_for_each_entry(dev, head, unreg_list)
10883 list_add_tail(&dev->close_list, &close_head);
10884 dev_close_many(&close_head, true);
10886 list_for_each_entry(dev, head, unreg_list) {
10887 /* And unlink it from device chain. */
10888 write_lock(&dev_base_lock);
10889 unlist_netdevice(dev, false);
10890 dev->reg_state = NETREG_UNREGISTERING;
10891 write_unlock(&dev_base_lock);
10893 flush_all_backlogs();
10897 list_for_each_entry(dev, head, unreg_list) {
10898 struct sk_buff *skb = NULL;
10900 /* Shutdown queueing discipline. */
10902 dev_tcx_uninstall(dev);
10903 dev_xdp_uninstall(dev);
10904 bpf_dev_bound_netdev_unregister(dev);
10906 netdev_offload_xstats_disable_all(dev);
10908 /* Notify protocols, that we are about to destroy
10909 * this device. They should clean all the things.
10911 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10913 if (!dev->rtnl_link_ops ||
10914 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10915 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
10916 GFP_KERNEL, NULL, 0,
10920 * Flush the unicast and multicast chains
10925 netdev_name_node_alt_flush(dev);
10926 netdev_name_node_free(dev->name_node);
10928 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
10930 if (dev->netdev_ops->ndo_uninit)
10931 dev->netdev_ops->ndo_uninit(dev);
10934 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh);
10936 /* Notifier chain MUST detach us all upper devices. */
10937 WARN_ON(netdev_has_any_upper_dev(dev));
10938 WARN_ON(netdev_has_any_lower_dev(dev));
10940 /* Remove entries from kobject tree */
10941 netdev_unregister_kobject(dev);
10943 /* Remove XPS queueing entries */
10944 netif_reset_xps_queues_gt(dev, 0);
10950 list_for_each_entry(dev, head, unreg_list) {
10951 netdev_put(dev, &dev->dev_registered_tracker);
10959 * unregister_netdevice_many - unregister many devices
10960 * @head: list of devices
10962 * Note: As most callers use a stack allocated list_head,
10963 * we force a list_del() to make sure stack wont be corrupted later.
10965 void unregister_netdevice_many(struct list_head *head)
10967 unregister_netdevice_many_notify(head, 0, NULL);
10969 EXPORT_SYMBOL(unregister_netdevice_many);
10972 * unregister_netdev - remove device from the kernel
10975 * This function shuts down a device interface and removes it
10976 * from the kernel tables.
10978 * This is just a wrapper for unregister_netdevice that takes
10979 * the rtnl semaphore. In general you want to use this and not
10980 * unregister_netdevice.
10982 void unregister_netdev(struct net_device *dev)
10985 unregister_netdevice(dev);
10988 EXPORT_SYMBOL(unregister_netdev);
10991 * __dev_change_net_namespace - move device to different nethost namespace
10993 * @net: network namespace
10994 * @pat: If not NULL name pattern to try if the current device name
10995 * is already taken in the destination network namespace.
10996 * @new_ifindex: If not zero, specifies device index in the target
10999 * This function shuts down a device interface and moves it
11000 * to a new network namespace. On success 0 is returned, on
11001 * a failure a netagive errno code is returned.
11003 * Callers must hold the rtnl semaphore.
11006 int __dev_change_net_namespace(struct net_device *dev, struct net *net,
11007 const char *pat, int new_ifindex)
11009 struct net *net_old = dev_net(dev);
11014 /* Don't allow namespace local devices to be moved. */
11016 if (dev->features & NETIF_F_NETNS_LOCAL)
11019 /* Ensure the device has been registrered */
11020 if (dev->reg_state != NETREG_REGISTERED)
11023 /* Get out if there is nothing todo */
11025 if (net_eq(net_old, net))
11028 /* Pick the destination device name, and ensure
11029 * we can use it in the destination network namespace.
11032 if (netdev_name_in_use(net, dev->name)) {
11033 /* We get here if we can't use the current device name */
11036 err = dev_get_valid_name(net, dev, pat);
11041 /* Check that new_ifindex isn't used yet. */
11043 if (new_ifindex && __dev_get_by_index(net, new_ifindex))
11047 * And now a mini version of register_netdevice unregister_netdevice.
11050 /* If device is running close it first. */
11053 /* And unlink it from device chain */
11054 unlist_netdevice(dev, true);
11058 /* Shutdown queueing discipline. */
11061 /* Notify protocols, that we are about to destroy
11062 * this device. They should clean all the things.
11064 * Note that dev->reg_state stays at NETREG_REGISTERED.
11065 * This is wanted because this way 8021q and macvlan know
11066 * the device is just moving and can keep their slaves up.
11068 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11071 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
11072 /* If there is an ifindex conflict assign a new one */
11073 if (!new_ifindex) {
11074 if (__dev_get_by_index(net, dev->ifindex))
11075 new_ifindex = dev_new_index(net);
11077 new_ifindex = dev->ifindex;
11080 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
11084 * Flush the unicast and multicast chains
11089 /* Send a netdev-removed uevent to the old namespace */
11090 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
11091 netdev_adjacent_del_links(dev);
11093 /* Move per-net netdevice notifiers that are following the netdevice */
11094 move_netdevice_notifiers_dev_net(dev, net);
11096 /* Actually switch the network namespace */
11097 dev_net_set(dev, net);
11098 dev->ifindex = new_ifindex;
11100 /* Send a netdev-add uevent to the new namespace */
11101 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
11102 netdev_adjacent_add_links(dev);
11104 /* Fixup kobjects */
11105 err = device_rename(&dev->dev, dev->name);
11108 /* Adapt owner in case owning user namespace of target network
11109 * namespace is different from the original one.
11111 err = netdev_change_owner(dev, net_old, net);
11114 /* Add the device back in the hashes */
11115 list_netdevice(dev);
11117 /* Notify protocols, that a new device appeared. */
11118 call_netdevice_notifiers(NETDEV_REGISTER, dev);
11121 * Prevent userspace races by waiting until the network
11122 * device is fully setup before sending notifications.
11124 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
11131 EXPORT_SYMBOL_GPL(__dev_change_net_namespace);
11133 static int dev_cpu_dead(unsigned int oldcpu)
11135 struct sk_buff **list_skb;
11136 struct sk_buff *skb;
11138 struct softnet_data *sd, *oldsd, *remsd = NULL;
11140 local_irq_disable();
11141 cpu = smp_processor_id();
11142 sd = &per_cpu(softnet_data, cpu);
11143 oldsd = &per_cpu(softnet_data, oldcpu);
11145 /* Find end of our completion_queue. */
11146 list_skb = &sd->completion_queue;
11148 list_skb = &(*list_skb)->next;
11149 /* Append completion queue from offline CPU. */
11150 *list_skb = oldsd->completion_queue;
11151 oldsd->completion_queue = NULL;
11153 /* Append output queue from offline CPU. */
11154 if (oldsd->output_queue) {
11155 *sd->output_queue_tailp = oldsd->output_queue;
11156 sd->output_queue_tailp = oldsd->output_queue_tailp;
11157 oldsd->output_queue = NULL;
11158 oldsd->output_queue_tailp = &oldsd->output_queue;
11160 /* Append NAPI poll list from offline CPU, with one exception :
11161 * process_backlog() must be called by cpu owning percpu backlog.
11162 * We properly handle process_queue & input_pkt_queue later.
11164 while (!list_empty(&oldsd->poll_list)) {
11165 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
11166 struct napi_struct,
11169 list_del_init(&napi->poll_list);
11170 if (napi->poll == process_backlog)
11173 ____napi_schedule(sd, napi);
11176 raise_softirq_irqoff(NET_TX_SOFTIRQ);
11177 local_irq_enable();
11180 remsd = oldsd->rps_ipi_list;
11181 oldsd->rps_ipi_list = NULL;
11183 /* send out pending IPI's on offline CPU */
11184 net_rps_send_ipi(remsd);
11186 /* Process offline CPU's input_pkt_queue */
11187 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
11189 input_queue_head_incr(oldsd);
11191 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
11193 input_queue_head_incr(oldsd);
11200 * netdev_increment_features - increment feature set by one
11201 * @all: current feature set
11202 * @one: new feature set
11203 * @mask: mask feature set
11205 * Computes a new feature set after adding a device with feature set
11206 * @one to the master device with current feature set @all. Will not
11207 * enable anything that is off in @mask. Returns the new feature set.
11209 netdev_features_t netdev_increment_features(netdev_features_t all,
11210 netdev_features_t one, netdev_features_t mask)
11212 if (mask & NETIF_F_HW_CSUM)
11213 mask |= NETIF_F_CSUM_MASK;
11214 mask |= NETIF_F_VLAN_CHALLENGED;
11216 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11217 all &= one | ~NETIF_F_ALL_FOR_ALL;
11219 /* If one device supports hw checksumming, set for all. */
11220 if (all & NETIF_F_HW_CSUM)
11221 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11225 EXPORT_SYMBOL(netdev_increment_features);
11227 static struct hlist_head * __net_init netdev_create_hash(void)
11230 struct hlist_head *hash;
11232 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11234 for (i = 0; i < NETDEV_HASHENTRIES; i++)
11235 INIT_HLIST_HEAD(&hash[i]);
11240 /* Initialize per network namespace state */
11241 static int __net_init netdev_init(struct net *net)
11243 BUILD_BUG_ON(GRO_HASH_BUCKETS >
11244 8 * sizeof_field(struct napi_struct, gro_bitmask));
11246 INIT_LIST_HEAD(&net->dev_base_head);
11248 net->dev_name_head = netdev_create_hash();
11249 if (net->dev_name_head == NULL)
11252 net->dev_index_head = netdev_create_hash();
11253 if (net->dev_index_head == NULL)
11256 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11261 kfree(net->dev_name_head);
11267 * netdev_drivername - network driver for the device
11268 * @dev: network device
11270 * Determine network driver for device.
11272 const char *netdev_drivername(const struct net_device *dev)
11274 const struct device_driver *driver;
11275 const struct device *parent;
11276 const char *empty = "";
11278 parent = dev->dev.parent;
11282 driver = parent->driver;
11283 if (driver && driver->name)
11284 return driver->name;
11288 static void __netdev_printk(const char *level, const struct net_device *dev,
11289 struct va_format *vaf)
11291 if (dev && dev->dev.parent) {
11292 dev_printk_emit(level[1] - '0',
11295 dev_driver_string(dev->dev.parent),
11296 dev_name(dev->dev.parent),
11297 netdev_name(dev), netdev_reg_state(dev),
11300 printk("%s%s%s: %pV",
11301 level, netdev_name(dev), netdev_reg_state(dev), vaf);
11303 printk("%s(NULL net_device): %pV", level, vaf);
11307 void netdev_printk(const char *level, const struct net_device *dev,
11308 const char *format, ...)
11310 struct va_format vaf;
11313 va_start(args, format);
11318 __netdev_printk(level, dev, &vaf);
11322 EXPORT_SYMBOL(netdev_printk);
11324 #define define_netdev_printk_level(func, level) \
11325 void func(const struct net_device *dev, const char *fmt, ...) \
11327 struct va_format vaf; \
11330 va_start(args, fmt); \
11335 __netdev_printk(level, dev, &vaf); \
11339 EXPORT_SYMBOL(func);
11341 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11342 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11343 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11344 define_netdev_printk_level(netdev_err, KERN_ERR);
11345 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11346 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11347 define_netdev_printk_level(netdev_info, KERN_INFO);
11349 static void __net_exit netdev_exit(struct net *net)
11351 kfree(net->dev_name_head);
11352 kfree(net->dev_index_head);
11353 if (net != &init_net)
11354 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11357 static struct pernet_operations __net_initdata netdev_net_ops = {
11358 .init = netdev_init,
11359 .exit = netdev_exit,
11362 static void __net_exit default_device_exit_net(struct net *net)
11364 struct net_device *dev, *aux;
11366 * Push all migratable network devices back to the
11367 * initial network namespace
11370 for_each_netdev_safe(net, dev, aux) {
11372 char fb_name[IFNAMSIZ];
11374 /* Ignore unmoveable devices (i.e. loopback) */
11375 if (dev->features & NETIF_F_NETNS_LOCAL)
11378 /* Leave virtual devices for the generic cleanup */
11379 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11382 /* Push remaining network devices to init_net */
11383 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11384 if (netdev_name_in_use(&init_net, fb_name))
11385 snprintf(fb_name, IFNAMSIZ, "dev%%d");
11386 err = dev_change_net_namespace(dev, &init_net, fb_name);
11388 pr_emerg("%s: failed to move %s to init_net: %d\n",
11389 __func__, dev->name, err);
11395 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11397 /* At exit all network devices most be removed from a network
11398 * namespace. Do this in the reverse order of registration.
11399 * Do this across as many network namespaces as possible to
11400 * improve batching efficiency.
11402 struct net_device *dev;
11404 LIST_HEAD(dev_kill_list);
11407 list_for_each_entry(net, net_list, exit_list) {
11408 default_device_exit_net(net);
11412 list_for_each_entry(net, net_list, exit_list) {
11413 for_each_netdev_reverse(net, dev) {
11414 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11415 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11417 unregister_netdevice_queue(dev, &dev_kill_list);
11420 unregister_netdevice_many(&dev_kill_list);
11424 static struct pernet_operations __net_initdata default_device_ops = {
11425 .exit_batch = default_device_exit_batch,
11429 * Initialize the DEV module. At boot time this walks the device list and
11430 * unhooks any devices that fail to initialise (normally hardware not
11431 * present) and leaves us with a valid list of present and active devices.
11436 * This is called single threaded during boot, so no need
11437 * to take the rtnl semaphore.
11439 static int __init net_dev_init(void)
11441 int i, rc = -ENOMEM;
11443 BUG_ON(!dev_boot_phase);
11445 if (dev_proc_init())
11448 if (netdev_kobject_init())
11451 INIT_LIST_HEAD(&ptype_all);
11452 for (i = 0; i < PTYPE_HASH_SIZE; i++)
11453 INIT_LIST_HEAD(&ptype_base[i]);
11455 if (register_pernet_subsys(&netdev_net_ops))
11459 * Initialise the packet receive queues.
11462 for_each_possible_cpu(i) {
11463 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
11464 struct softnet_data *sd = &per_cpu(softnet_data, i);
11466 INIT_WORK(flush, flush_backlog);
11468 skb_queue_head_init(&sd->input_pkt_queue);
11469 skb_queue_head_init(&sd->process_queue);
11470 #ifdef CONFIG_XFRM_OFFLOAD
11471 skb_queue_head_init(&sd->xfrm_backlog);
11473 INIT_LIST_HEAD(&sd->poll_list);
11474 sd->output_queue_tailp = &sd->output_queue;
11476 INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
11479 INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd);
11480 spin_lock_init(&sd->defer_lock);
11482 init_gro_hash(&sd->backlog);
11483 sd->backlog.poll = process_backlog;
11484 sd->backlog.weight = weight_p;
11487 dev_boot_phase = 0;
11489 /* The loopback device is special if any other network devices
11490 * is present in a network namespace the loopback device must
11491 * be present. Since we now dynamically allocate and free the
11492 * loopback device ensure this invariant is maintained by
11493 * keeping the loopback device as the first device on the
11494 * list of network devices. Ensuring the loopback devices
11495 * is the first device that appears and the last network device
11498 if (register_pernet_device(&loopback_net_ops))
11501 if (register_pernet_device(&default_device_ops))
11504 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11505 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11507 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11508 NULL, dev_cpu_dead);
11515 subsys_initcall(net_dev_init);