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>
110 #include <linux/highmem.h>
111 #include <linux/init.h>
112 #include <linux/module.h>
113 #include <linux/netpoll.h>
114 #include <linux/rcupdate.h>
115 #include <linux/delay.h>
116 #include <net/iw_handler.h>
117 #include <asm/current.h>
118 #include <linux/audit.h>
119 #include <linux/dmaengine.h>
120 #include <linux/err.h>
121 #include <linux/ctype.h>
122 #include <linux/if_arp.h>
123 #include <linux/if_vlan.h>
124 #include <linux/ip.h>
126 #include <net/mpls.h>
127 #include <linux/ipv6.h>
128 #include <linux/in.h>
129 #include <linux/jhash.h>
130 #include <linux/random.h>
131 #include <trace/events/napi.h>
132 #include <trace/events/net.h>
133 #include <trace/events/skb.h>
134 #include <trace/events/qdisc.h>
135 #include <linux/inetdevice.h>
136 #include <linux/cpu_rmap.h>
137 #include <linux/static_key.h>
138 #include <linux/hashtable.h>
139 #include <linux/vmalloc.h>
140 #include <linux/if_macvlan.h>
141 #include <linux/errqueue.h>
142 #include <linux/hrtimer.h>
143 #include <linux/netfilter_netdev.h>
144 #include <linux/crash_dump.h>
145 #include <linux/sctp.h>
146 #include <net/udp_tunnel.h>
147 #include <linux/net_namespace.h>
148 #include <linux/indirect_call_wrapper.h>
149 #include <net/devlink.h>
150 #include <linux/pm_runtime.h>
151 #include <linux/prandom.h>
152 #include <linux/once_lite.h>
154 #include "net-sysfs.h"
157 static DEFINE_SPINLOCK(ptype_lock);
158 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
159 struct list_head ptype_all __read_mostly; /* Taps */
161 static int netif_rx_internal(struct sk_buff *skb);
162 static int call_netdevice_notifiers_info(unsigned long val,
163 struct netdev_notifier_info *info);
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)
403 /* Unlink dev from the device chain */
404 write_lock(&dev_base_lock);
405 list_del_rcu(&dev->dev_list);
406 netdev_name_node_del(dev->name_node);
407 hlist_del_rcu(&dev->index_hlist);
408 write_unlock(&dev_base_lock);
410 dev_base_seq_inc(dev_net(dev));
417 static RAW_NOTIFIER_HEAD(netdev_chain);
420 * Device drivers call our routines to queue packets here. We empty the
421 * queue in the local softnet handler.
424 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
425 EXPORT_PER_CPU_SYMBOL(softnet_data);
427 #ifdef CONFIG_LOCKDEP
429 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
430 * according to dev->type
432 static const unsigned short netdev_lock_type[] = {
433 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
434 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
435 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
436 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
437 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
438 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
439 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
440 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
441 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
442 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
443 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
444 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
445 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
446 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
447 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
449 static const char *const netdev_lock_name[] = {
450 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
451 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
452 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
453 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
454 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
455 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
456 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
457 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
458 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
459 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
460 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
461 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
462 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
463 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
464 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
466 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
467 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
469 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
473 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
474 if (netdev_lock_type[i] == dev_type)
476 /* the last key is used by default */
477 return ARRAY_SIZE(netdev_lock_type) - 1;
480 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
481 unsigned short dev_type)
485 i = netdev_lock_pos(dev_type);
486 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
487 netdev_lock_name[i]);
490 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
494 i = netdev_lock_pos(dev->type);
495 lockdep_set_class_and_name(&dev->addr_list_lock,
496 &netdev_addr_lock_key[i],
497 netdev_lock_name[i]);
500 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
501 unsigned short dev_type)
505 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
510 /*******************************************************************************
512 * Protocol management and registration routines
514 *******************************************************************************/
518 * Add a protocol ID to the list. Now that the input handler is
519 * smarter we can dispense with all the messy stuff that used to be
522 * BEWARE!!! Protocol handlers, mangling input packets,
523 * MUST BE last in hash buckets and checking protocol handlers
524 * MUST start from promiscuous ptype_all chain in net_bh.
525 * It is true now, do not change it.
526 * Explanation follows: if protocol handler, mangling packet, will
527 * be the first on list, it is not able to sense, that packet
528 * is cloned and should be copied-on-write, so that it will
529 * change it and subsequent readers will get broken packet.
533 static inline struct list_head *ptype_head(const struct packet_type *pt)
535 if (pt->type == htons(ETH_P_ALL))
536 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
538 return pt->dev ? &pt->dev->ptype_specific :
539 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
543 * dev_add_pack - add packet handler
544 * @pt: packet type declaration
546 * Add a protocol handler to the networking stack. The passed &packet_type
547 * is linked into kernel lists and may not be freed until it has been
548 * removed from the kernel lists.
550 * This call does not sleep therefore it can not
551 * guarantee all CPU's that are in middle of receiving packets
552 * will see the new packet type (until the next received packet).
555 void dev_add_pack(struct packet_type *pt)
557 struct list_head *head = ptype_head(pt);
559 spin_lock(&ptype_lock);
560 list_add_rcu(&pt->list, head);
561 spin_unlock(&ptype_lock);
563 EXPORT_SYMBOL(dev_add_pack);
566 * __dev_remove_pack - remove packet handler
567 * @pt: packet type declaration
569 * Remove a protocol handler that was previously added to the kernel
570 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
571 * from the kernel lists and can be freed or reused once this function
574 * The packet type might still be in use by receivers
575 * and must not be freed until after all the CPU's have gone
576 * through a quiescent state.
578 void __dev_remove_pack(struct packet_type *pt)
580 struct list_head *head = ptype_head(pt);
581 struct packet_type *pt1;
583 spin_lock(&ptype_lock);
585 list_for_each_entry(pt1, head, list) {
587 list_del_rcu(&pt->list);
592 pr_warn("dev_remove_pack: %p not found\n", pt);
594 spin_unlock(&ptype_lock);
596 EXPORT_SYMBOL(__dev_remove_pack);
599 * dev_remove_pack - remove packet handler
600 * @pt: packet type declaration
602 * Remove a protocol handler that was previously added to the kernel
603 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
604 * from the kernel lists and can be freed or reused once this function
607 * This call sleeps to guarantee that no CPU is looking at the packet
610 void dev_remove_pack(struct packet_type *pt)
612 __dev_remove_pack(pt);
616 EXPORT_SYMBOL(dev_remove_pack);
619 /*******************************************************************************
621 * Device Interface Subroutines
623 *******************************************************************************/
626 * dev_get_iflink - get 'iflink' value of a interface
627 * @dev: targeted interface
629 * Indicates the ifindex the interface is linked to.
630 * Physical interfaces have the same 'ifindex' and 'iflink' values.
633 int dev_get_iflink(const struct net_device *dev)
635 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
636 return dev->netdev_ops->ndo_get_iflink(dev);
640 EXPORT_SYMBOL(dev_get_iflink);
643 * dev_fill_metadata_dst - Retrieve tunnel egress information.
644 * @dev: targeted interface
647 * For better visibility of tunnel traffic OVS needs to retrieve
648 * egress tunnel information for a packet. Following API allows
649 * user to get this info.
651 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
653 struct ip_tunnel_info *info;
655 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
658 info = skb_tunnel_info_unclone(skb);
661 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
664 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
666 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
668 static struct net_device_path *dev_fwd_path(struct net_device_path_stack *stack)
670 int k = stack->num_paths++;
672 if (WARN_ON_ONCE(k >= NET_DEVICE_PATH_STACK_MAX))
675 return &stack->path[k];
678 int dev_fill_forward_path(const struct net_device *dev, const u8 *daddr,
679 struct net_device_path_stack *stack)
681 const struct net_device *last_dev;
682 struct net_device_path_ctx ctx = {
686 struct net_device_path *path;
689 stack->num_paths = 0;
690 while (ctx.dev && ctx.dev->netdev_ops->ndo_fill_forward_path) {
692 path = dev_fwd_path(stack);
696 memset(path, 0, sizeof(struct net_device_path));
697 ret = ctx.dev->netdev_ops->ndo_fill_forward_path(&ctx, path);
701 if (WARN_ON_ONCE(last_dev == ctx.dev))
704 path = dev_fwd_path(stack);
707 path->type = DEV_PATH_ETHERNET;
712 EXPORT_SYMBOL_GPL(dev_fill_forward_path);
715 * __dev_get_by_name - find a device by its name
716 * @net: the applicable net namespace
717 * @name: name to find
719 * Find an interface by name. Must be called under RTNL semaphore
720 * or @dev_base_lock. If the name is found a pointer to the device
721 * is returned. If the name is not found then %NULL is returned. The
722 * reference counters are not incremented so the caller must be
723 * careful with locks.
726 struct net_device *__dev_get_by_name(struct net *net, const char *name)
728 struct netdev_name_node *node_name;
730 node_name = netdev_name_node_lookup(net, name);
731 return node_name ? node_name->dev : NULL;
733 EXPORT_SYMBOL(__dev_get_by_name);
736 * dev_get_by_name_rcu - find a device by its name
737 * @net: the applicable net namespace
738 * @name: name to find
740 * Find an interface by name.
741 * If the name is found a pointer to the device is returned.
742 * If the name is not found then %NULL is returned.
743 * The reference counters are not incremented so the caller must be
744 * careful with locks. The caller must hold RCU lock.
747 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
749 struct netdev_name_node *node_name;
751 node_name = netdev_name_node_lookup_rcu(net, name);
752 return node_name ? node_name->dev : NULL;
754 EXPORT_SYMBOL(dev_get_by_name_rcu);
757 * dev_get_by_name - find a device by its name
758 * @net: the applicable net namespace
759 * @name: name to find
761 * Find an interface by name. This can be called from any
762 * context and does its own locking. The returned handle has
763 * the usage count incremented and the caller must use dev_put() to
764 * release it when it is no longer needed. %NULL is returned if no
765 * matching device is found.
768 struct net_device *dev_get_by_name(struct net *net, const char *name)
770 struct net_device *dev;
773 dev = dev_get_by_name_rcu(net, name);
778 EXPORT_SYMBOL(dev_get_by_name);
781 * __dev_get_by_index - find a device by its ifindex
782 * @net: the applicable net namespace
783 * @ifindex: index of device
785 * Search for an interface by index. Returns %NULL if the device
786 * is not found or a pointer to the device. The device has not
787 * had its reference counter increased so the caller must be careful
788 * about locking. The caller must hold either the RTNL semaphore
792 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
794 struct net_device *dev;
795 struct hlist_head *head = dev_index_hash(net, ifindex);
797 hlist_for_each_entry(dev, head, index_hlist)
798 if (dev->ifindex == ifindex)
803 EXPORT_SYMBOL(__dev_get_by_index);
806 * dev_get_by_index_rcu - find a device by its ifindex
807 * @net: the applicable net namespace
808 * @ifindex: index of device
810 * Search for an interface by index. Returns %NULL if the device
811 * is not found or a pointer to the device. The device has not
812 * had its reference counter increased so the caller must be careful
813 * about locking. The caller must hold RCU lock.
816 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
818 struct net_device *dev;
819 struct hlist_head *head = dev_index_hash(net, ifindex);
821 hlist_for_each_entry_rcu(dev, head, index_hlist)
822 if (dev->ifindex == ifindex)
827 EXPORT_SYMBOL(dev_get_by_index_rcu);
831 * dev_get_by_index - find a device by its ifindex
832 * @net: the applicable net namespace
833 * @ifindex: index of device
835 * Search for an interface by index. Returns NULL if the device
836 * is not found or a pointer to the device. The device returned has
837 * had a reference added and the pointer is safe until the user calls
838 * dev_put to indicate they have finished with it.
841 struct net_device *dev_get_by_index(struct net *net, int ifindex)
843 struct net_device *dev;
846 dev = dev_get_by_index_rcu(net, ifindex);
851 EXPORT_SYMBOL(dev_get_by_index);
854 * dev_get_by_napi_id - find a device by napi_id
855 * @napi_id: ID of the NAPI struct
857 * Search for an interface by NAPI ID. Returns %NULL if the device
858 * is not found or a pointer to the device. The device has not had
859 * its reference counter increased so the caller must be careful
860 * about locking. The caller must hold RCU lock.
863 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
865 struct napi_struct *napi;
867 WARN_ON_ONCE(!rcu_read_lock_held());
869 if (napi_id < MIN_NAPI_ID)
872 napi = napi_by_id(napi_id);
874 return napi ? napi->dev : NULL;
876 EXPORT_SYMBOL(dev_get_by_napi_id);
879 * netdev_get_name - get a netdevice name, knowing its ifindex.
880 * @net: network namespace
881 * @name: a pointer to the buffer where the name will be stored.
882 * @ifindex: the ifindex of the interface to get the name from.
884 int netdev_get_name(struct net *net, char *name, int ifindex)
886 struct net_device *dev;
889 down_read(&devnet_rename_sem);
892 dev = dev_get_by_index_rcu(net, ifindex);
898 strcpy(name, dev->name);
903 up_read(&devnet_rename_sem);
908 * dev_getbyhwaddr_rcu - find a device by its hardware address
909 * @net: the applicable net namespace
910 * @type: media type of device
911 * @ha: hardware address
913 * Search for an interface by MAC address. Returns NULL if the device
914 * is not found or a pointer to the device.
915 * The caller must hold RCU or RTNL.
916 * The returned device has not had its ref count increased
917 * and the caller must therefore be careful about locking
921 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
924 struct net_device *dev;
926 for_each_netdev_rcu(net, dev)
927 if (dev->type == type &&
928 !memcmp(dev->dev_addr, ha, dev->addr_len))
933 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
935 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
937 struct net_device *dev, *ret = NULL;
940 for_each_netdev_rcu(net, dev)
941 if (dev->type == type) {
949 EXPORT_SYMBOL(dev_getfirstbyhwtype);
952 * __dev_get_by_flags - find any device with given flags
953 * @net: the applicable net namespace
954 * @if_flags: IFF_* values
955 * @mask: bitmask of bits in if_flags to check
957 * Search for any interface with the given flags. Returns NULL if a device
958 * is not found or a pointer to the device. Must be called inside
959 * rtnl_lock(), and result refcount is unchanged.
962 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
965 struct net_device *dev, *ret;
970 for_each_netdev(net, dev) {
971 if (((dev->flags ^ if_flags) & mask) == 0) {
978 EXPORT_SYMBOL(__dev_get_by_flags);
981 * dev_valid_name - check if name is okay for network device
984 * Network device names need to be valid file names to
985 * allow sysfs to work. We also disallow any kind of
988 bool dev_valid_name(const char *name)
992 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
994 if (!strcmp(name, ".") || !strcmp(name, ".."))
998 if (*name == '/' || *name == ':' || isspace(*name))
1004 EXPORT_SYMBOL(dev_valid_name);
1007 * __dev_alloc_name - allocate a name for a device
1008 * @net: network namespace to allocate the device name in
1009 * @name: name format string
1010 * @buf: scratch buffer and result name string
1012 * Passed a format string - eg "lt%d" it will try and find a suitable
1013 * id. It scans list of devices to build up a free map, then chooses
1014 * the first empty slot. The caller must hold the dev_base or rtnl lock
1015 * while allocating the name and adding the device in order to avoid
1017 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1018 * Returns the number of the unit assigned or a negative errno code.
1021 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1025 const int max_netdevices = 8*PAGE_SIZE;
1026 unsigned long *inuse;
1027 struct net_device *d;
1029 if (!dev_valid_name(name))
1032 p = strchr(name, '%');
1035 * Verify the string as this thing may have come from
1036 * the user. There must be either one "%d" and no other "%"
1039 if (p[1] != 'd' || strchr(p + 2, '%'))
1042 /* Use one page as a bit array of possible slots */
1043 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1047 for_each_netdev(net, d) {
1048 struct netdev_name_node *name_node;
1049 list_for_each_entry(name_node, &d->name_node->list, list) {
1050 if (!sscanf(name_node->name, name, &i))
1052 if (i < 0 || i >= max_netdevices)
1055 /* avoid cases where sscanf is not exact inverse of printf */
1056 snprintf(buf, IFNAMSIZ, name, i);
1057 if (!strncmp(buf, name_node->name, IFNAMSIZ))
1058 __set_bit(i, inuse);
1060 if (!sscanf(d->name, name, &i))
1062 if (i < 0 || i >= max_netdevices)
1065 /* avoid cases where sscanf is not exact inverse of printf */
1066 snprintf(buf, IFNAMSIZ, name, i);
1067 if (!strncmp(buf, d->name, IFNAMSIZ))
1068 __set_bit(i, inuse);
1071 i = find_first_zero_bit(inuse, max_netdevices);
1072 free_page((unsigned long) inuse);
1075 snprintf(buf, IFNAMSIZ, name, i);
1076 if (!netdev_name_in_use(net, buf))
1079 /* It is possible to run out of possible slots
1080 * when the name is long and there isn't enough space left
1081 * for the digits, or if all bits are used.
1086 static int dev_alloc_name_ns(struct net *net,
1087 struct net_device *dev,
1094 ret = __dev_alloc_name(net, name, buf);
1096 strlcpy(dev->name, buf, IFNAMSIZ);
1101 * dev_alloc_name - allocate a name for a device
1103 * @name: name format string
1105 * Passed a format string - eg "lt%d" it will try and find a suitable
1106 * id. It scans list of devices to build up a free map, then chooses
1107 * the first empty slot. The caller must hold the dev_base or rtnl lock
1108 * while allocating the name and adding the device in order to avoid
1110 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1111 * Returns the number of the unit assigned or a negative errno code.
1114 int dev_alloc_name(struct net_device *dev, const char *name)
1116 return dev_alloc_name_ns(dev_net(dev), dev, name);
1118 EXPORT_SYMBOL(dev_alloc_name);
1120 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1125 if (!dev_valid_name(name))
1128 if (strchr(name, '%'))
1129 return dev_alloc_name_ns(net, dev, name);
1130 else if (netdev_name_in_use(net, name))
1132 else if (dev->name != name)
1133 strlcpy(dev->name, name, IFNAMSIZ);
1139 * dev_change_name - change name of a device
1141 * @newname: name (or format string) must be at least IFNAMSIZ
1143 * Change name of a device, can pass format strings "eth%d".
1146 int dev_change_name(struct net_device *dev, const char *newname)
1148 unsigned char old_assign_type;
1149 char oldname[IFNAMSIZ];
1155 BUG_ON(!dev_net(dev));
1159 /* Some auto-enslaved devices e.g. failover slaves are
1160 * special, as userspace might rename the device after
1161 * the interface had been brought up and running since
1162 * the point kernel initiated auto-enslavement. Allow
1163 * live name change even when these slave devices are
1166 * Typically, users of these auto-enslaving devices
1167 * don't actually care about slave name change, as
1168 * they are supposed to operate on master interface
1171 if (dev->flags & IFF_UP &&
1172 likely(!(dev->priv_flags & IFF_LIVE_RENAME_OK)))
1175 down_write(&devnet_rename_sem);
1177 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1178 up_write(&devnet_rename_sem);
1182 memcpy(oldname, dev->name, IFNAMSIZ);
1184 err = dev_get_valid_name(net, dev, newname);
1186 up_write(&devnet_rename_sem);
1190 if (oldname[0] && !strchr(oldname, '%'))
1191 netdev_info(dev, "renamed from %s\n", oldname);
1193 old_assign_type = dev->name_assign_type;
1194 dev->name_assign_type = NET_NAME_RENAMED;
1197 ret = device_rename(&dev->dev, dev->name);
1199 memcpy(dev->name, oldname, IFNAMSIZ);
1200 dev->name_assign_type = old_assign_type;
1201 up_write(&devnet_rename_sem);
1205 up_write(&devnet_rename_sem);
1207 netdev_adjacent_rename_links(dev, oldname);
1209 write_lock(&dev_base_lock);
1210 netdev_name_node_del(dev->name_node);
1211 write_unlock(&dev_base_lock);
1215 write_lock(&dev_base_lock);
1216 netdev_name_node_add(net, dev->name_node);
1217 write_unlock(&dev_base_lock);
1219 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1220 ret = notifier_to_errno(ret);
1223 /* err >= 0 after dev_alloc_name() or stores the first errno */
1226 down_write(&devnet_rename_sem);
1227 memcpy(dev->name, oldname, IFNAMSIZ);
1228 memcpy(oldname, newname, IFNAMSIZ);
1229 dev->name_assign_type = old_assign_type;
1230 old_assign_type = NET_NAME_RENAMED;
1233 netdev_err(dev, "name change rollback failed: %d\n",
1242 * dev_set_alias - change ifalias of a device
1244 * @alias: name up to IFALIASZ
1245 * @len: limit of bytes to copy from info
1247 * Set ifalias for a device,
1249 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1251 struct dev_ifalias *new_alias = NULL;
1253 if (len >= IFALIASZ)
1257 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1261 memcpy(new_alias->ifalias, alias, len);
1262 new_alias->ifalias[len] = 0;
1265 mutex_lock(&ifalias_mutex);
1266 new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1267 mutex_is_locked(&ifalias_mutex));
1268 mutex_unlock(&ifalias_mutex);
1271 kfree_rcu(new_alias, rcuhead);
1275 EXPORT_SYMBOL(dev_set_alias);
1278 * dev_get_alias - get ifalias of a device
1280 * @name: buffer to store name of ifalias
1281 * @len: size of buffer
1283 * get ifalias for a device. Caller must make sure dev cannot go
1284 * away, e.g. rcu read lock or own a reference count to device.
1286 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1288 const struct dev_ifalias *alias;
1292 alias = rcu_dereference(dev->ifalias);
1294 ret = snprintf(name, len, "%s", alias->ifalias);
1301 * netdev_features_change - device changes features
1302 * @dev: device to cause notification
1304 * Called to indicate a device has changed features.
1306 void netdev_features_change(struct net_device *dev)
1308 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1310 EXPORT_SYMBOL(netdev_features_change);
1313 * netdev_state_change - device changes state
1314 * @dev: device to cause notification
1316 * Called to indicate a device has changed state. This function calls
1317 * the notifier chains for netdev_chain and sends a NEWLINK message
1318 * to the routing socket.
1320 void netdev_state_change(struct net_device *dev)
1322 if (dev->flags & IFF_UP) {
1323 struct netdev_notifier_change_info change_info = {
1327 call_netdevice_notifiers_info(NETDEV_CHANGE,
1329 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
1332 EXPORT_SYMBOL(netdev_state_change);
1335 * __netdev_notify_peers - notify network peers about existence of @dev,
1336 * to be called when rtnl lock is already held.
1337 * @dev: network device
1339 * Generate traffic such that interested network peers are aware of
1340 * @dev, such as by generating a gratuitous ARP. This may be used when
1341 * a device wants to inform the rest of the network about some sort of
1342 * reconfiguration such as a failover event or virtual machine
1345 void __netdev_notify_peers(struct net_device *dev)
1348 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1349 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1351 EXPORT_SYMBOL(__netdev_notify_peers);
1354 * netdev_notify_peers - notify network peers about existence of @dev
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 __netdev_notify_peers(dev);
1369 EXPORT_SYMBOL(netdev_notify_peers);
1371 static int napi_threaded_poll(void *data);
1373 static int napi_kthread_create(struct napi_struct *n)
1377 /* Create and wake up the kthread once to put it in
1378 * TASK_INTERRUPTIBLE mode to avoid the blocked task
1379 * warning and work with loadavg.
1381 n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d",
1382 n->dev->name, n->napi_id);
1383 if (IS_ERR(n->thread)) {
1384 err = PTR_ERR(n->thread);
1385 pr_err("kthread_run failed with err %d\n", err);
1392 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1394 const struct net_device_ops *ops = dev->netdev_ops;
1398 dev_addr_check(dev);
1400 if (!netif_device_present(dev)) {
1401 /* may be detached because parent is runtime-suspended */
1402 if (dev->dev.parent)
1403 pm_runtime_resume(dev->dev.parent);
1404 if (!netif_device_present(dev))
1408 /* Block netpoll from trying to do any rx path servicing.
1409 * If we don't do this there is a chance ndo_poll_controller
1410 * or ndo_poll may be running while we open the device
1412 netpoll_poll_disable(dev);
1414 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1415 ret = notifier_to_errno(ret);
1419 set_bit(__LINK_STATE_START, &dev->state);
1421 if (ops->ndo_validate_addr)
1422 ret = ops->ndo_validate_addr(dev);
1424 if (!ret && ops->ndo_open)
1425 ret = ops->ndo_open(dev);
1427 netpoll_poll_enable(dev);
1430 clear_bit(__LINK_STATE_START, &dev->state);
1432 dev->flags |= IFF_UP;
1433 dev_set_rx_mode(dev);
1435 add_device_randomness(dev->dev_addr, dev->addr_len);
1442 * dev_open - prepare an interface for use.
1443 * @dev: device to open
1444 * @extack: netlink extended ack
1446 * Takes a device from down to up state. The device's private open
1447 * function is invoked and then the multicast lists are loaded. Finally
1448 * the device is moved into the up state and a %NETDEV_UP message is
1449 * sent to the netdev notifier chain.
1451 * Calling this function on an active interface is a nop. On a failure
1452 * a negative errno code is returned.
1454 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1458 if (dev->flags & IFF_UP)
1461 ret = __dev_open(dev, extack);
1465 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1466 call_netdevice_notifiers(NETDEV_UP, dev);
1470 EXPORT_SYMBOL(dev_open);
1472 static void __dev_close_many(struct list_head *head)
1474 struct net_device *dev;
1479 list_for_each_entry(dev, head, close_list) {
1480 /* Temporarily disable netpoll until the interface is down */
1481 netpoll_poll_disable(dev);
1483 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1485 clear_bit(__LINK_STATE_START, &dev->state);
1487 /* Synchronize to scheduled poll. We cannot touch poll list, it
1488 * can be even on different cpu. So just clear netif_running().
1490 * dev->stop() will invoke napi_disable() on all of it's
1491 * napi_struct instances on this device.
1493 smp_mb__after_atomic(); /* Commit netif_running(). */
1496 dev_deactivate_many(head);
1498 list_for_each_entry(dev, head, close_list) {
1499 const struct net_device_ops *ops = dev->netdev_ops;
1502 * Call the device specific close. This cannot fail.
1503 * Only if device is UP
1505 * We allow it to be called even after a DETACH hot-plug
1511 dev->flags &= ~IFF_UP;
1512 netpoll_poll_enable(dev);
1516 static void __dev_close(struct net_device *dev)
1520 list_add(&dev->close_list, &single);
1521 __dev_close_many(&single);
1525 void dev_close_many(struct list_head *head, bool unlink)
1527 struct net_device *dev, *tmp;
1529 /* Remove the devices that don't need to be closed */
1530 list_for_each_entry_safe(dev, tmp, head, close_list)
1531 if (!(dev->flags & IFF_UP))
1532 list_del_init(&dev->close_list);
1534 __dev_close_many(head);
1536 list_for_each_entry_safe(dev, tmp, head, close_list) {
1537 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1538 call_netdevice_notifiers(NETDEV_DOWN, dev);
1540 list_del_init(&dev->close_list);
1543 EXPORT_SYMBOL(dev_close_many);
1546 * dev_close - shutdown an interface.
1547 * @dev: device to shutdown
1549 * This function moves an active device into down state. A
1550 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1551 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1554 void dev_close(struct net_device *dev)
1556 if (dev->flags & IFF_UP) {
1559 list_add(&dev->close_list, &single);
1560 dev_close_many(&single, true);
1564 EXPORT_SYMBOL(dev_close);
1568 * dev_disable_lro - disable Large Receive Offload on a device
1571 * Disable Large Receive Offload (LRO) on a net device. Must be
1572 * called under RTNL. This is needed if received packets may be
1573 * forwarded to another interface.
1575 void dev_disable_lro(struct net_device *dev)
1577 struct net_device *lower_dev;
1578 struct list_head *iter;
1580 dev->wanted_features &= ~NETIF_F_LRO;
1581 netdev_update_features(dev);
1583 if (unlikely(dev->features & NETIF_F_LRO))
1584 netdev_WARN(dev, "failed to disable LRO!\n");
1586 netdev_for_each_lower_dev(dev, lower_dev, iter)
1587 dev_disable_lro(lower_dev);
1589 EXPORT_SYMBOL(dev_disable_lro);
1592 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1595 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1596 * called under RTNL. This is needed if Generic XDP is installed on
1599 static void dev_disable_gro_hw(struct net_device *dev)
1601 dev->wanted_features &= ~NETIF_F_GRO_HW;
1602 netdev_update_features(dev);
1604 if (unlikely(dev->features & NETIF_F_GRO_HW))
1605 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1608 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1611 case NETDEV_##val: \
1612 return "NETDEV_" __stringify(val);
1614 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1615 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1616 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1617 N(POST_INIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN) N(CHANGEUPPER)
1618 N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA) N(BONDING_INFO)
1619 N(PRECHANGEUPPER) N(CHANGELOWERSTATE) N(UDP_TUNNEL_PUSH_INFO)
1620 N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1621 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1622 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1623 N(PRE_CHANGEADDR) N(OFFLOAD_XSTATS_ENABLE) N(OFFLOAD_XSTATS_DISABLE)
1624 N(OFFLOAD_XSTATS_REPORT_USED) N(OFFLOAD_XSTATS_REPORT_DELTA)
1627 return "UNKNOWN_NETDEV_EVENT";
1629 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1631 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1632 struct net_device *dev)
1634 struct netdev_notifier_info info = {
1638 return nb->notifier_call(nb, val, &info);
1641 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1642 struct net_device *dev)
1646 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1647 err = notifier_to_errno(err);
1651 if (!(dev->flags & IFF_UP))
1654 call_netdevice_notifier(nb, NETDEV_UP, dev);
1658 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1659 struct net_device *dev)
1661 if (dev->flags & IFF_UP) {
1662 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1664 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1666 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1669 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1672 struct net_device *dev;
1675 for_each_netdev(net, dev) {
1676 err = call_netdevice_register_notifiers(nb, dev);
1683 for_each_netdev_continue_reverse(net, dev)
1684 call_netdevice_unregister_notifiers(nb, dev);
1688 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1691 struct net_device *dev;
1693 for_each_netdev(net, dev)
1694 call_netdevice_unregister_notifiers(nb, dev);
1697 static int dev_boot_phase = 1;
1700 * register_netdevice_notifier - register a network notifier block
1703 * Register a notifier to be called when network device events occur.
1704 * The notifier passed is linked into the kernel structures and must
1705 * not be reused until it has been unregistered. A negative errno code
1706 * is returned on a failure.
1708 * When registered all registration and up events are replayed
1709 * to the new notifier to allow device to have a race free
1710 * view of the network device list.
1713 int register_netdevice_notifier(struct notifier_block *nb)
1718 /* Close race with setup_net() and cleanup_net() */
1719 down_write(&pernet_ops_rwsem);
1721 err = raw_notifier_chain_register(&netdev_chain, nb);
1727 err = call_netdevice_register_net_notifiers(nb, net);
1734 up_write(&pernet_ops_rwsem);
1738 for_each_net_continue_reverse(net)
1739 call_netdevice_unregister_net_notifiers(nb, net);
1741 raw_notifier_chain_unregister(&netdev_chain, nb);
1744 EXPORT_SYMBOL(register_netdevice_notifier);
1747 * unregister_netdevice_notifier - unregister a network notifier block
1750 * Unregister a notifier previously registered by
1751 * register_netdevice_notifier(). The notifier is unlinked into the
1752 * kernel structures and may then be reused. A negative errno code
1753 * is returned on a failure.
1755 * After unregistering unregister and down device events are synthesized
1756 * for all devices on the device list to the removed notifier to remove
1757 * the need for special case cleanup code.
1760 int unregister_netdevice_notifier(struct notifier_block *nb)
1765 /* Close race with setup_net() and cleanup_net() */
1766 down_write(&pernet_ops_rwsem);
1768 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1773 call_netdevice_unregister_net_notifiers(nb, net);
1777 up_write(&pernet_ops_rwsem);
1780 EXPORT_SYMBOL(unregister_netdevice_notifier);
1782 static int __register_netdevice_notifier_net(struct net *net,
1783 struct notifier_block *nb,
1784 bool ignore_call_fail)
1788 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1794 err = call_netdevice_register_net_notifiers(nb, net);
1795 if (err && !ignore_call_fail)
1796 goto chain_unregister;
1801 raw_notifier_chain_unregister(&net->netdev_chain, nb);
1805 static int __unregister_netdevice_notifier_net(struct net *net,
1806 struct notifier_block *nb)
1810 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1814 call_netdevice_unregister_net_notifiers(nb, net);
1819 * register_netdevice_notifier_net - register a per-netns network notifier block
1820 * @net: network namespace
1823 * Register a notifier to be called when network device events occur.
1824 * The notifier passed is linked into the kernel structures and must
1825 * not be reused until it has been unregistered. A negative errno code
1826 * is returned on a failure.
1828 * When registered all registration and up events are replayed
1829 * to the new notifier to allow device to have a race free
1830 * view of the network device list.
1833 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1838 err = __register_netdevice_notifier_net(net, nb, false);
1842 EXPORT_SYMBOL(register_netdevice_notifier_net);
1845 * unregister_netdevice_notifier_net - unregister a per-netns
1846 * network notifier block
1847 * @net: network namespace
1850 * Unregister a notifier previously registered by
1851 * register_netdevice_notifier(). The notifier is unlinked into the
1852 * kernel structures and may then be reused. A negative errno code
1853 * is returned on a failure.
1855 * After unregistering unregister and down device events are synthesized
1856 * for all devices on the device list to the removed notifier to remove
1857 * the need for special case cleanup code.
1860 int unregister_netdevice_notifier_net(struct net *net,
1861 struct notifier_block *nb)
1866 err = __unregister_netdevice_notifier_net(net, nb);
1870 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1872 int register_netdevice_notifier_dev_net(struct net_device *dev,
1873 struct notifier_block *nb,
1874 struct netdev_net_notifier *nn)
1879 err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
1882 list_add(&nn->list, &dev->net_notifier_list);
1887 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
1889 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
1890 struct notifier_block *nb,
1891 struct netdev_net_notifier *nn)
1896 list_del(&nn->list);
1897 err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
1901 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
1903 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
1906 struct netdev_net_notifier *nn;
1908 list_for_each_entry(nn, &dev->net_notifier_list, list) {
1909 __unregister_netdevice_notifier_net(dev_net(dev), nn->nb);
1910 __register_netdevice_notifier_net(net, nn->nb, true);
1915 * call_netdevice_notifiers_info - call all network notifier blocks
1916 * @val: value passed unmodified to notifier function
1917 * @info: notifier information data
1919 * Call all network notifier blocks. Parameters and return value
1920 * are as for raw_notifier_call_chain().
1923 static int call_netdevice_notifiers_info(unsigned long val,
1924 struct netdev_notifier_info *info)
1926 struct net *net = dev_net(info->dev);
1931 /* Run per-netns notifier block chain first, then run the global one.
1932 * Hopefully, one day, the global one is going to be removed after
1933 * all notifier block registrators get converted to be per-netns.
1935 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
1936 if (ret & NOTIFY_STOP_MASK)
1938 return raw_notifier_call_chain(&netdev_chain, val, info);
1942 * call_netdevice_notifiers_info_robust - call per-netns notifier blocks
1943 * for and rollback on error
1944 * @val_up: value passed unmodified to notifier function
1945 * @val_down: value passed unmodified to the notifier function when
1946 * recovering from an error on @val_up
1947 * @info: notifier information data
1949 * Call all per-netns network notifier blocks, but not notifier blocks on
1950 * the global notifier chain. Parameters and return value are as for
1951 * raw_notifier_call_chain_robust().
1955 call_netdevice_notifiers_info_robust(unsigned long val_up,
1956 unsigned long val_down,
1957 struct netdev_notifier_info *info)
1959 struct net *net = dev_net(info->dev);
1963 return raw_notifier_call_chain_robust(&net->netdev_chain,
1964 val_up, val_down, info);
1967 static int call_netdevice_notifiers_extack(unsigned long val,
1968 struct net_device *dev,
1969 struct netlink_ext_ack *extack)
1971 struct netdev_notifier_info info = {
1976 return call_netdevice_notifiers_info(val, &info);
1980 * call_netdevice_notifiers - call all network notifier blocks
1981 * @val: value passed unmodified to notifier function
1982 * @dev: net_device pointer passed unmodified to notifier function
1984 * Call all network notifier blocks. Parameters and return value
1985 * are as for raw_notifier_call_chain().
1988 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
1990 return call_netdevice_notifiers_extack(val, dev, NULL);
1992 EXPORT_SYMBOL(call_netdevice_notifiers);
1995 * call_netdevice_notifiers_mtu - call all network notifier blocks
1996 * @val: value passed unmodified to notifier function
1997 * @dev: net_device pointer passed unmodified to notifier function
1998 * @arg: additional u32 argument passed to the notifier function
2000 * Call all network notifier blocks. Parameters and return value
2001 * are as for raw_notifier_call_chain().
2003 static int call_netdevice_notifiers_mtu(unsigned long val,
2004 struct net_device *dev, u32 arg)
2006 struct netdev_notifier_info_ext info = {
2011 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2013 return call_netdevice_notifiers_info(val, &info.info);
2016 #ifdef CONFIG_NET_INGRESS
2017 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2019 void net_inc_ingress_queue(void)
2021 static_branch_inc(&ingress_needed_key);
2023 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2025 void net_dec_ingress_queue(void)
2027 static_branch_dec(&ingress_needed_key);
2029 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2032 #ifdef CONFIG_NET_EGRESS
2033 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2035 void net_inc_egress_queue(void)
2037 static_branch_inc(&egress_needed_key);
2039 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2041 void net_dec_egress_queue(void)
2043 static_branch_dec(&egress_needed_key);
2045 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2048 DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2049 EXPORT_SYMBOL(netstamp_needed_key);
2050 #ifdef CONFIG_JUMP_LABEL
2051 static atomic_t netstamp_needed_deferred;
2052 static atomic_t netstamp_wanted;
2053 static void netstamp_clear(struct work_struct *work)
2055 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2058 wanted = atomic_add_return(deferred, &netstamp_wanted);
2060 static_branch_enable(&netstamp_needed_key);
2062 static_branch_disable(&netstamp_needed_key);
2064 static DECLARE_WORK(netstamp_work, netstamp_clear);
2067 void net_enable_timestamp(void)
2069 #ifdef CONFIG_JUMP_LABEL
2073 wanted = atomic_read(&netstamp_wanted);
2076 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
2079 atomic_inc(&netstamp_needed_deferred);
2080 schedule_work(&netstamp_work);
2082 static_branch_inc(&netstamp_needed_key);
2085 EXPORT_SYMBOL(net_enable_timestamp);
2087 void net_disable_timestamp(void)
2089 #ifdef CONFIG_JUMP_LABEL
2093 wanted = atomic_read(&netstamp_wanted);
2096 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
2099 atomic_dec(&netstamp_needed_deferred);
2100 schedule_work(&netstamp_work);
2102 static_branch_dec(&netstamp_needed_key);
2105 EXPORT_SYMBOL(net_disable_timestamp);
2107 static inline void net_timestamp_set(struct sk_buff *skb)
2110 skb->mono_delivery_time = 0;
2111 if (static_branch_unlikely(&netstamp_needed_key))
2112 skb->tstamp = ktime_get_real();
2115 #define net_timestamp_check(COND, SKB) \
2116 if (static_branch_unlikely(&netstamp_needed_key)) { \
2117 if ((COND) && !(SKB)->tstamp) \
2118 (SKB)->tstamp = ktime_get_real(); \
2121 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2123 return __is_skb_forwardable(dev, skb, true);
2125 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2127 static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb,
2130 int ret = ____dev_forward_skb(dev, skb, check_mtu);
2133 skb->protocol = eth_type_trans(skb, dev);
2134 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2140 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2142 return __dev_forward_skb2(dev, skb, true);
2144 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2147 * dev_forward_skb - loopback an skb to another netif
2149 * @dev: destination network device
2150 * @skb: buffer to forward
2153 * NET_RX_SUCCESS (no congestion)
2154 * NET_RX_DROP (packet was dropped, but freed)
2156 * dev_forward_skb can be used for injecting an skb from the
2157 * start_xmit function of one device into the receive queue
2158 * of another device.
2160 * The receiving device may be in another namespace, so
2161 * we have to clear all information in the skb that could
2162 * impact namespace isolation.
2164 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2166 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2168 EXPORT_SYMBOL_GPL(dev_forward_skb);
2170 int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb)
2172 return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb);
2175 static inline int deliver_skb(struct sk_buff *skb,
2176 struct packet_type *pt_prev,
2177 struct net_device *orig_dev)
2179 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2181 refcount_inc(&skb->users);
2182 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2185 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2186 struct packet_type **pt,
2187 struct net_device *orig_dev,
2189 struct list_head *ptype_list)
2191 struct packet_type *ptype, *pt_prev = *pt;
2193 list_for_each_entry_rcu(ptype, ptype_list, list) {
2194 if (ptype->type != type)
2197 deliver_skb(skb, pt_prev, orig_dev);
2203 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2205 if (!ptype->af_packet_priv || !skb->sk)
2208 if (ptype->id_match)
2209 return ptype->id_match(ptype, skb->sk);
2210 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2217 * dev_nit_active - return true if any network interface taps are in use
2219 * @dev: network device to check for the presence of taps
2221 bool dev_nit_active(struct net_device *dev)
2223 return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2225 EXPORT_SYMBOL_GPL(dev_nit_active);
2228 * Support routine. Sends outgoing frames to any network
2229 * taps currently in use.
2232 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2234 struct packet_type *ptype;
2235 struct sk_buff *skb2 = NULL;
2236 struct packet_type *pt_prev = NULL;
2237 struct list_head *ptype_list = &ptype_all;
2241 list_for_each_entry_rcu(ptype, ptype_list, list) {
2242 if (ptype->ignore_outgoing)
2245 /* Never send packets back to the socket
2246 * they originated from - MvS (miquels@drinkel.ow.org)
2248 if (skb_loop_sk(ptype, skb))
2252 deliver_skb(skb2, pt_prev, skb->dev);
2257 /* need to clone skb, done only once */
2258 skb2 = skb_clone(skb, GFP_ATOMIC);
2262 net_timestamp_set(skb2);
2264 /* skb->nh should be correctly
2265 * set by sender, so that the second statement is
2266 * just protection against buggy protocols.
2268 skb_reset_mac_header(skb2);
2270 if (skb_network_header(skb2) < skb2->data ||
2271 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2272 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2273 ntohs(skb2->protocol),
2275 skb_reset_network_header(skb2);
2278 skb2->transport_header = skb2->network_header;
2279 skb2->pkt_type = PACKET_OUTGOING;
2283 if (ptype_list == &ptype_all) {
2284 ptype_list = &dev->ptype_all;
2289 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2290 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2296 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2299 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2300 * @dev: Network device
2301 * @txq: number of queues available
2303 * If real_num_tx_queues is changed the tc mappings may no longer be
2304 * valid. To resolve this verify the tc mapping remains valid and if
2305 * not NULL the mapping. With no priorities mapping to this
2306 * offset/count pair it will no longer be used. In the worst case TC0
2307 * is invalid nothing can be done so disable priority mappings. If is
2308 * expected that drivers will fix this mapping if they can before
2309 * calling netif_set_real_num_tx_queues.
2311 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2314 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2316 /* If TC0 is invalidated disable TC mapping */
2317 if (tc->offset + tc->count > txq) {
2318 netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2323 /* Invalidated prio to tc mappings set to TC0 */
2324 for (i = 1; i < TC_BITMASK + 1; i++) {
2325 int q = netdev_get_prio_tc_map(dev, i);
2327 tc = &dev->tc_to_txq[q];
2328 if (tc->offset + tc->count > txq) {
2329 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",
2331 netdev_set_prio_tc_map(dev, i, 0);
2336 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2339 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2342 /* walk through the TCs and see if it falls into any of them */
2343 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2344 if ((txq - tc->offset) < tc->count)
2348 /* didn't find it, just return -1 to indicate no match */
2354 EXPORT_SYMBOL(netdev_txq_to_tc);
2357 static struct static_key xps_needed __read_mostly;
2358 static struct static_key xps_rxqs_needed __read_mostly;
2359 static DEFINE_MUTEX(xps_map_mutex);
2360 #define xmap_dereference(P) \
2361 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2363 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2364 struct xps_dev_maps *old_maps, int tci, u16 index)
2366 struct xps_map *map = NULL;
2370 map = xmap_dereference(dev_maps->attr_map[tci]);
2374 for (pos = map->len; pos--;) {
2375 if (map->queues[pos] != index)
2379 map->queues[pos] = map->queues[--map->len];
2384 RCU_INIT_POINTER(old_maps->attr_map[tci], NULL);
2385 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2386 kfree_rcu(map, rcu);
2393 static bool remove_xps_queue_cpu(struct net_device *dev,
2394 struct xps_dev_maps *dev_maps,
2395 int cpu, u16 offset, u16 count)
2397 int num_tc = dev_maps->num_tc;
2398 bool active = false;
2401 for (tci = cpu * num_tc; num_tc--; tci++) {
2404 for (i = count, j = offset; i--; j++) {
2405 if (!remove_xps_queue(dev_maps, NULL, tci, j))
2415 static void reset_xps_maps(struct net_device *dev,
2416 struct xps_dev_maps *dev_maps,
2417 enum xps_map_type type)
2419 static_key_slow_dec_cpuslocked(&xps_needed);
2420 if (type == XPS_RXQS)
2421 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2423 RCU_INIT_POINTER(dev->xps_maps[type], NULL);
2425 kfree_rcu(dev_maps, rcu);
2428 static void clean_xps_maps(struct net_device *dev, enum xps_map_type type,
2429 u16 offset, u16 count)
2431 struct xps_dev_maps *dev_maps;
2432 bool active = false;
2435 dev_maps = xmap_dereference(dev->xps_maps[type]);
2439 for (j = 0; j < dev_maps->nr_ids; j++)
2440 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count);
2442 reset_xps_maps(dev, dev_maps, type);
2444 if (type == XPS_CPUS) {
2445 for (i = offset + (count - 1); count--; i--)
2446 netdev_queue_numa_node_write(
2447 netdev_get_tx_queue(dev, i), NUMA_NO_NODE);
2451 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2454 if (!static_key_false(&xps_needed))
2458 mutex_lock(&xps_map_mutex);
2460 if (static_key_false(&xps_rxqs_needed))
2461 clean_xps_maps(dev, XPS_RXQS, offset, count);
2463 clean_xps_maps(dev, XPS_CPUS, offset, count);
2465 mutex_unlock(&xps_map_mutex);
2469 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2471 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2474 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2475 u16 index, bool is_rxqs_map)
2477 struct xps_map *new_map;
2478 int alloc_len = XPS_MIN_MAP_ALLOC;
2481 for (pos = 0; map && pos < map->len; pos++) {
2482 if (map->queues[pos] != index)
2487 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2489 if (pos < map->alloc_len)
2492 alloc_len = map->alloc_len * 2;
2495 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2499 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2501 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2502 cpu_to_node(attr_index));
2506 for (i = 0; i < pos; i++)
2507 new_map->queues[i] = map->queues[i];
2508 new_map->alloc_len = alloc_len;
2514 /* Copy xps maps at a given index */
2515 static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps,
2516 struct xps_dev_maps *new_dev_maps, int index,
2517 int tc, bool skip_tc)
2519 int i, tci = index * dev_maps->num_tc;
2520 struct xps_map *map;
2522 /* copy maps belonging to foreign traffic classes */
2523 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2524 if (i == tc && skip_tc)
2527 /* fill in the new device map from the old device map */
2528 map = xmap_dereference(dev_maps->attr_map[tci]);
2529 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2533 /* Must be called under cpus_read_lock */
2534 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2535 u16 index, enum xps_map_type type)
2537 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL;
2538 const unsigned long *online_mask = NULL;
2539 bool active = false, copy = false;
2540 int i, j, tci, numa_node_id = -2;
2541 int maps_sz, num_tc = 1, tc = 0;
2542 struct xps_map *map, *new_map;
2543 unsigned int nr_ids;
2546 /* Do not allow XPS on subordinate device directly */
2547 num_tc = dev->num_tc;
2551 /* If queue belongs to subordinate dev use its map */
2552 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2554 tc = netdev_txq_to_tc(dev, index);
2559 mutex_lock(&xps_map_mutex);
2561 dev_maps = xmap_dereference(dev->xps_maps[type]);
2562 if (type == XPS_RXQS) {
2563 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2564 nr_ids = dev->num_rx_queues;
2566 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2567 if (num_possible_cpus() > 1)
2568 online_mask = cpumask_bits(cpu_online_mask);
2569 nr_ids = nr_cpu_ids;
2572 if (maps_sz < L1_CACHE_BYTES)
2573 maps_sz = L1_CACHE_BYTES;
2575 /* The old dev_maps could be larger or smaller than the one we're
2576 * setting up now, as dev->num_tc or nr_ids could have been updated in
2577 * between. We could try to be smart, but let's be safe instead and only
2578 * copy foreign traffic classes if the two map sizes match.
2581 dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids)
2584 /* allocate memory for queue storage */
2585 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2587 if (!new_dev_maps) {
2588 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2589 if (!new_dev_maps) {
2590 mutex_unlock(&xps_map_mutex);
2594 new_dev_maps->nr_ids = nr_ids;
2595 new_dev_maps->num_tc = num_tc;
2598 tci = j * num_tc + tc;
2599 map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL;
2601 map = expand_xps_map(map, j, index, type == XPS_RXQS);
2605 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2609 goto out_no_new_maps;
2612 /* Increment static keys at most once per type */
2613 static_key_slow_inc_cpuslocked(&xps_needed);
2614 if (type == XPS_RXQS)
2615 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2618 for (j = 0; j < nr_ids; j++) {
2619 bool skip_tc = false;
2621 tci = j * num_tc + tc;
2622 if (netif_attr_test_mask(j, mask, nr_ids) &&
2623 netif_attr_test_online(j, online_mask, nr_ids)) {
2624 /* add tx-queue to CPU/rx-queue maps */
2629 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2630 while ((pos < map->len) && (map->queues[pos] != index))
2633 if (pos == map->len)
2634 map->queues[map->len++] = index;
2636 if (type == XPS_CPUS) {
2637 if (numa_node_id == -2)
2638 numa_node_id = cpu_to_node(j);
2639 else if (numa_node_id != cpu_to_node(j))
2646 xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc,
2650 rcu_assign_pointer(dev->xps_maps[type], new_dev_maps);
2652 /* Cleanup old maps */
2654 goto out_no_old_maps;
2656 for (j = 0; j < dev_maps->nr_ids; j++) {
2657 for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
2658 map = xmap_dereference(dev_maps->attr_map[tci]);
2663 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2668 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2669 kfree_rcu(map, rcu);
2673 old_dev_maps = dev_maps;
2676 dev_maps = new_dev_maps;
2680 if (type == XPS_CPUS)
2681 /* update Tx queue numa node */
2682 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2683 (numa_node_id >= 0) ?
2684 numa_node_id : NUMA_NO_NODE);
2689 /* removes tx-queue from unused CPUs/rx-queues */
2690 for (j = 0; j < dev_maps->nr_ids; j++) {
2691 tci = j * dev_maps->num_tc;
2693 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2695 netif_attr_test_mask(j, mask, dev_maps->nr_ids) &&
2696 netif_attr_test_online(j, online_mask, dev_maps->nr_ids))
2699 active |= remove_xps_queue(dev_maps,
2700 copy ? old_dev_maps : NULL,
2706 kfree_rcu(old_dev_maps, rcu);
2708 /* free map if not active */
2710 reset_xps_maps(dev, dev_maps, type);
2713 mutex_unlock(&xps_map_mutex);
2717 /* remove any maps that we added */
2718 for (j = 0; j < nr_ids; j++) {
2719 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2720 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2722 xmap_dereference(dev_maps->attr_map[tci]) :
2724 if (new_map && new_map != map)
2729 mutex_unlock(&xps_map_mutex);
2731 kfree(new_dev_maps);
2734 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2736 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2742 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS);
2747 EXPORT_SYMBOL(netif_set_xps_queue);
2750 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2752 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2754 /* Unbind any subordinate channels */
2755 while (txq-- != &dev->_tx[0]) {
2757 netdev_unbind_sb_channel(dev, txq->sb_dev);
2761 void netdev_reset_tc(struct net_device *dev)
2764 netif_reset_xps_queues_gt(dev, 0);
2766 netdev_unbind_all_sb_channels(dev);
2768 /* Reset TC configuration of device */
2770 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2771 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2773 EXPORT_SYMBOL(netdev_reset_tc);
2775 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2777 if (tc >= dev->num_tc)
2781 netif_reset_xps_queues(dev, offset, count);
2783 dev->tc_to_txq[tc].count = count;
2784 dev->tc_to_txq[tc].offset = offset;
2787 EXPORT_SYMBOL(netdev_set_tc_queue);
2789 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2791 if (num_tc > TC_MAX_QUEUE)
2795 netif_reset_xps_queues_gt(dev, 0);
2797 netdev_unbind_all_sb_channels(dev);
2799 dev->num_tc = num_tc;
2802 EXPORT_SYMBOL(netdev_set_num_tc);
2804 void netdev_unbind_sb_channel(struct net_device *dev,
2805 struct net_device *sb_dev)
2807 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2810 netif_reset_xps_queues_gt(sb_dev, 0);
2812 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2813 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2815 while (txq-- != &dev->_tx[0]) {
2816 if (txq->sb_dev == sb_dev)
2820 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2822 int netdev_bind_sb_channel_queue(struct net_device *dev,
2823 struct net_device *sb_dev,
2824 u8 tc, u16 count, u16 offset)
2826 /* Make certain the sb_dev and dev are already configured */
2827 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2830 /* We cannot hand out queues we don't have */
2831 if ((offset + count) > dev->real_num_tx_queues)
2834 /* Record the mapping */
2835 sb_dev->tc_to_txq[tc].count = count;
2836 sb_dev->tc_to_txq[tc].offset = offset;
2838 /* Provide a way for Tx queue to find the tc_to_txq map or
2839 * XPS map for itself.
2842 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2846 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2848 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2850 /* Do not use a multiqueue device to represent a subordinate channel */
2851 if (netif_is_multiqueue(dev))
2854 /* We allow channels 1 - 32767 to be used for subordinate channels.
2855 * Channel 0 is meant to be "native" mode and used only to represent
2856 * the main root device. We allow writing 0 to reset the device back
2857 * to normal mode after being used as a subordinate channel.
2859 if (channel > S16_MAX)
2862 dev->num_tc = -channel;
2866 EXPORT_SYMBOL(netdev_set_sb_channel);
2869 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2870 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2872 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2877 disabling = txq < dev->real_num_tx_queues;
2879 if (txq < 1 || txq > dev->num_tx_queues)
2882 if (dev->reg_state == NETREG_REGISTERED ||
2883 dev->reg_state == NETREG_UNREGISTERING) {
2886 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2892 netif_setup_tc(dev, txq);
2894 dev_qdisc_change_real_num_tx(dev, txq);
2896 dev->real_num_tx_queues = txq;
2900 qdisc_reset_all_tx_gt(dev, txq);
2902 netif_reset_xps_queues_gt(dev, txq);
2906 dev->real_num_tx_queues = txq;
2911 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2915 * netif_set_real_num_rx_queues - set actual number of RX queues used
2916 * @dev: Network device
2917 * @rxq: Actual number of RX queues
2919 * This must be called either with the rtnl_lock held or before
2920 * registration of the net device. Returns 0 on success, or a
2921 * negative error code. If called before registration, it always
2924 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2928 if (rxq < 1 || rxq > dev->num_rx_queues)
2931 if (dev->reg_state == NETREG_REGISTERED) {
2934 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2940 dev->real_num_rx_queues = rxq;
2943 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2947 * netif_set_real_num_queues - set actual number of RX and TX queues used
2948 * @dev: Network device
2949 * @txq: Actual number of TX queues
2950 * @rxq: Actual number of RX queues
2952 * Set the real number of both TX and RX queues.
2953 * Does nothing if the number of queues is already correct.
2955 int netif_set_real_num_queues(struct net_device *dev,
2956 unsigned int txq, unsigned int rxq)
2958 unsigned int old_rxq = dev->real_num_rx_queues;
2961 if (txq < 1 || txq > dev->num_tx_queues ||
2962 rxq < 1 || rxq > dev->num_rx_queues)
2965 /* Start from increases, so the error path only does decreases -
2966 * decreases can't fail.
2968 if (rxq > dev->real_num_rx_queues) {
2969 err = netif_set_real_num_rx_queues(dev, rxq);
2973 if (txq > dev->real_num_tx_queues) {
2974 err = netif_set_real_num_tx_queues(dev, txq);
2978 if (rxq < dev->real_num_rx_queues)
2979 WARN_ON(netif_set_real_num_rx_queues(dev, rxq));
2980 if (txq < dev->real_num_tx_queues)
2981 WARN_ON(netif_set_real_num_tx_queues(dev, txq));
2985 WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq));
2988 EXPORT_SYMBOL(netif_set_real_num_queues);
2991 * netif_get_num_default_rss_queues - default number of RSS queues
2993 * Default value is the number of physical cores if there are only 1 or 2, or
2994 * divided by 2 if there are more.
2996 int netif_get_num_default_rss_queues(void)
3001 if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL)))
3004 cpumask_copy(cpus, cpu_online_mask);
3005 for_each_cpu(cpu, cpus) {
3007 cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu));
3009 free_cpumask_var(cpus);
3011 return count > 2 ? DIV_ROUND_UP(count, 2) : count;
3013 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3015 static void __netif_reschedule(struct Qdisc *q)
3017 struct softnet_data *sd;
3018 unsigned long flags;
3020 local_irq_save(flags);
3021 sd = this_cpu_ptr(&softnet_data);
3022 q->next_sched = NULL;
3023 *sd->output_queue_tailp = q;
3024 sd->output_queue_tailp = &q->next_sched;
3025 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3026 local_irq_restore(flags);
3029 void __netif_schedule(struct Qdisc *q)
3031 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3032 __netif_reschedule(q);
3034 EXPORT_SYMBOL(__netif_schedule);
3036 struct dev_kfree_skb_cb {
3037 enum skb_free_reason reason;
3040 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3042 return (struct dev_kfree_skb_cb *)skb->cb;
3045 void netif_schedule_queue(struct netdev_queue *txq)
3048 if (!netif_xmit_stopped(txq)) {
3049 struct Qdisc *q = rcu_dereference(txq->qdisc);
3051 __netif_schedule(q);
3055 EXPORT_SYMBOL(netif_schedule_queue);
3057 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3059 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3063 q = rcu_dereference(dev_queue->qdisc);
3064 __netif_schedule(q);
3068 EXPORT_SYMBOL(netif_tx_wake_queue);
3070 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
3072 unsigned long flags;
3077 if (likely(refcount_read(&skb->users) == 1)) {
3079 refcount_set(&skb->users, 0);
3080 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3083 get_kfree_skb_cb(skb)->reason = reason;
3084 local_irq_save(flags);
3085 skb->next = __this_cpu_read(softnet_data.completion_queue);
3086 __this_cpu_write(softnet_data.completion_queue, skb);
3087 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3088 local_irq_restore(flags);
3090 EXPORT_SYMBOL(__dev_kfree_skb_irq);
3092 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
3094 if (in_hardirq() || irqs_disabled())
3095 __dev_kfree_skb_irq(skb, reason);
3099 EXPORT_SYMBOL(__dev_kfree_skb_any);
3103 * netif_device_detach - mark device as removed
3104 * @dev: network device
3106 * Mark device as removed from system and therefore no longer available.
3108 void netif_device_detach(struct net_device *dev)
3110 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3111 netif_running(dev)) {
3112 netif_tx_stop_all_queues(dev);
3115 EXPORT_SYMBOL(netif_device_detach);
3118 * netif_device_attach - mark device as attached
3119 * @dev: network device
3121 * Mark device as attached from system and restart if needed.
3123 void netif_device_attach(struct net_device *dev)
3125 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3126 netif_running(dev)) {
3127 netif_tx_wake_all_queues(dev);
3128 __netdev_watchdog_up(dev);
3131 EXPORT_SYMBOL(netif_device_attach);
3134 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3135 * to be used as a distribution range.
3137 static u16 skb_tx_hash(const struct net_device *dev,
3138 const struct net_device *sb_dev,
3139 struct sk_buff *skb)
3143 u16 qcount = dev->real_num_tx_queues;
3146 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3148 qoffset = sb_dev->tc_to_txq[tc].offset;
3149 qcount = sb_dev->tc_to_txq[tc].count;
3150 if (unlikely(!qcount)) {
3151 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3152 sb_dev->name, qoffset, tc);
3154 qcount = dev->real_num_tx_queues;
3158 if (skb_rx_queue_recorded(skb)) {
3159 hash = skb_get_rx_queue(skb);
3160 if (hash >= qoffset)
3162 while (unlikely(hash >= qcount))
3164 return hash + qoffset;
3167 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3170 static void skb_warn_bad_offload(const struct sk_buff *skb)
3172 static const netdev_features_t null_features;
3173 struct net_device *dev = skb->dev;
3174 const char *name = "";
3176 if (!net_ratelimit())
3180 if (dev->dev.parent)
3181 name = dev_driver_string(dev->dev.parent);
3183 name = netdev_name(dev);
3185 skb_dump(KERN_WARNING, skb, false);
3186 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3187 name, dev ? &dev->features : &null_features,
3188 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3192 * Invalidate hardware checksum when packet is to be mangled, and
3193 * complete checksum manually on outgoing path.
3195 int skb_checksum_help(struct sk_buff *skb)
3198 int ret = 0, offset;
3200 if (skb->ip_summed == CHECKSUM_COMPLETE)
3201 goto out_set_summed;
3203 if (unlikely(skb_is_gso(skb))) {
3204 skb_warn_bad_offload(skb);
3208 /* Before computing a checksum, we should make sure no frag could
3209 * be modified by an external entity : checksum could be wrong.
3211 if (skb_has_shared_frag(skb)) {
3212 ret = __skb_linearize(skb);
3217 offset = skb_checksum_start_offset(skb);
3218 BUG_ON(offset >= skb_headlen(skb));
3219 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3221 offset += skb->csum_offset;
3222 BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
3224 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3228 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3230 skb->ip_summed = CHECKSUM_NONE;
3234 EXPORT_SYMBOL(skb_checksum_help);
3236 int skb_crc32c_csum_help(struct sk_buff *skb)
3239 int ret = 0, offset, start;
3241 if (skb->ip_summed != CHECKSUM_PARTIAL)
3244 if (unlikely(skb_is_gso(skb)))
3247 /* Before computing a checksum, we should make sure no frag could
3248 * be modified by an external entity : checksum could be wrong.
3250 if (unlikely(skb_has_shared_frag(skb))) {
3251 ret = __skb_linearize(skb);
3255 start = skb_checksum_start_offset(skb);
3256 offset = start + offsetof(struct sctphdr, checksum);
3257 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3262 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3266 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3267 skb->len - start, ~(__u32)0,
3269 *(__le32 *)(skb->data + offset) = crc32c_csum;
3270 skb->ip_summed = CHECKSUM_NONE;
3271 skb->csum_not_inet = 0;
3276 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3278 __be16 type = skb->protocol;
3280 /* Tunnel gso handlers can set protocol to ethernet. */
3281 if (type == htons(ETH_P_TEB)) {
3284 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3287 eth = (struct ethhdr *)skb->data;
3288 type = eth->h_proto;
3291 return __vlan_get_protocol(skb, type, depth);
3294 /* openvswitch calls this on rx path, so we need a different check.
3296 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
3299 return skb->ip_summed != CHECKSUM_PARTIAL &&
3300 skb->ip_summed != CHECKSUM_UNNECESSARY;
3302 return skb->ip_summed == CHECKSUM_NONE;
3306 * __skb_gso_segment - Perform segmentation on skb.
3307 * @skb: buffer to segment
3308 * @features: features for the output path (see dev->features)
3309 * @tx_path: whether it is called in TX path
3311 * This function segments the given skb and returns a list of segments.
3313 * It may return NULL if the skb requires no segmentation. This is
3314 * only possible when GSO is used for verifying header integrity.
3316 * Segmentation preserves SKB_GSO_CB_OFFSET bytes of previous skb cb.
3318 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
3319 netdev_features_t features, bool tx_path)
3321 struct sk_buff *segs;
3323 if (unlikely(skb_needs_check(skb, tx_path))) {
3326 /* We're going to init ->check field in TCP or UDP header */
3327 err = skb_cow_head(skb, 0);
3329 return ERR_PTR(err);
3332 /* Only report GSO partial support if it will enable us to
3333 * support segmentation on this frame without needing additional
3336 if (features & NETIF_F_GSO_PARTIAL) {
3337 netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
3338 struct net_device *dev = skb->dev;
3340 partial_features |= dev->features & dev->gso_partial_features;
3341 if (!skb_gso_ok(skb, features | partial_features))
3342 features &= ~NETIF_F_GSO_PARTIAL;
3345 BUILD_BUG_ON(SKB_GSO_CB_OFFSET +
3346 sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
3348 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
3349 SKB_GSO_CB(skb)->encap_level = 0;
3351 skb_reset_mac_header(skb);
3352 skb_reset_mac_len(skb);
3354 segs = skb_mac_gso_segment(skb, features);
3356 if (segs != skb && unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
3357 skb_warn_bad_offload(skb);
3361 EXPORT_SYMBOL(__skb_gso_segment);
3363 /* Take action when hardware reception checksum errors are detected. */
3365 static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3367 netdev_err(dev, "hw csum failure\n");
3368 skb_dump(KERN_ERR, skb, true);
3372 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3374 DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb);
3376 EXPORT_SYMBOL(netdev_rx_csum_fault);
3379 /* XXX: check that highmem exists at all on the given machine. */
3380 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3382 #ifdef CONFIG_HIGHMEM
3385 if (!(dev->features & NETIF_F_HIGHDMA)) {
3386 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3387 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3389 if (PageHighMem(skb_frag_page(frag)))
3397 /* If MPLS offload request, verify we are testing hardware MPLS features
3398 * instead of standard features for the netdev.
3400 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3401 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3402 netdev_features_t features,
3405 if (eth_p_mpls(type))
3406 features &= skb->dev->mpls_features;
3411 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3412 netdev_features_t features,
3419 static netdev_features_t harmonize_features(struct sk_buff *skb,
3420 netdev_features_t features)
3424 type = skb_network_protocol(skb, NULL);
3425 features = net_mpls_features(skb, features, type);
3427 if (skb->ip_summed != CHECKSUM_NONE &&
3428 !can_checksum_protocol(features, type)) {
3429 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3431 if (illegal_highdma(skb->dev, skb))
3432 features &= ~NETIF_F_SG;
3437 netdev_features_t passthru_features_check(struct sk_buff *skb,
3438 struct net_device *dev,
3439 netdev_features_t features)
3443 EXPORT_SYMBOL(passthru_features_check);
3445 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3446 struct net_device *dev,
3447 netdev_features_t features)
3449 return vlan_features_check(skb, features);
3452 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3453 struct net_device *dev,
3454 netdev_features_t features)
3456 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3458 if (gso_segs > READ_ONCE(dev->gso_max_segs))
3459 return features & ~NETIF_F_GSO_MASK;
3461 if (!skb_shinfo(skb)->gso_type) {
3462 skb_warn_bad_offload(skb);
3463 return features & ~NETIF_F_GSO_MASK;
3466 /* Support for GSO partial features requires software
3467 * intervention before we can actually process the packets
3468 * so we need to strip support for any partial features now
3469 * and we can pull them back in after we have partially
3470 * segmented the frame.
3472 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3473 features &= ~dev->gso_partial_features;
3475 /* Make sure to clear the IPv4 ID mangling feature if the
3476 * IPv4 header has the potential to be fragmented.
3478 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3479 struct iphdr *iph = skb->encapsulation ?
3480 inner_ip_hdr(skb) : ip_hdr(skb);
3482 if (!(iph->frag_off & htons(IP_DF)))
3483 features &= ~NETIF_F_TSO_MANGLEID;
3489 netdev_features_t netif_skb_features(struct sk_buff *skb)
3491 struct net_device *dev = skb->dev;
3492 netdev_features_t features = dev->features;
3494 if (skb_is_gso(skb))
3495 features = gso_features_check(skb, dev, features);
3497 /* If encapsulation offload request, verify we are testing
3498 * hardware encapsulation features instead of standard
3499 * features for the netdev
3501 if (skb->encapsulation)
3502 features &= dev->hw_enc_features;
3504 if (skb_vlan_tagged(skb))
3505 features = netdev_intersect_features(features,
3506 dev->vlan_features |
3507 NETIF_F_HW_VLAN_CTAG_TX |
3508 NETIF_F_HW_VLAN_STAG_TX);
3510 if (dev->netdev_ops->ndo_features_check)
3511 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3514 features &= dflt_features_check(skb, dev, features);
3516 return harmonize_features(skb, features);
3518 EXPORT_SYMBOL(netif_skb_features);
3520 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3521 struct netdev_queue *txq, bool more)
3526 if (dev_nit_active(dev))
3527 dev_queue_xmit_nit(skb, dev);
3530 PRANDOM_ADD_NOISE(skb, dev, txq, len + jiffies);
3531 trace_net_dev_start_xmit(skb, dev);
3532 rc = netdev_start_xmit(skb, dev, txq, more);
3533 trace_net_dev_xmit(skb, rc, dev, len);
3538 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3539 struct netdev_queue *txq, int *ret)
3541 struct sk_buff *skb = first;
3542 int rc = NETDEV_TX_OK;
3545 struct sk_buff *next = skb->next;
3547 skb_mark_not_on_list(skb);
3548 rc = xmit_one(skb, dev, txq, next != NULL);
3549 if (unlikely(!dev_xmit_complete(rc))) {
3555 if (netif_tx_queue_stopped(txq) && skb) {
3556 rc = NETDEV_TX_BUSY;
3566 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3567 netdev_features_t features)
3569 if (skb_vlan_tag_present(skb) &&
3570 !vlan_hw_offload_capable(features, skb->vlan_proto))
3571 skb = __vlan_hwaccel_push_inside(skb);
3575 int skb_csum_hwoffload_help(struct sk_buff *skb,
3576 const netdev_features_t features)
3578 if (unlikely(skb_csum_is_sctp(skb)))
3579 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3580 skb_crc32c_csum_help(skb);
3582 if (features & NETIF_F_HW_CSUM)
3585 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
3586 switch (skb->csum_offset) {
3587 case offsetof(struct tcphdr, check):
3588 case offsetof(struct udphdr, check):
3593 return skb_checksum_help(skb);
3595 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3597 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3599 netdev_features_t features;
3601 features = netif_skb_features(skb);
3602 skb = validate_xmit_vlan(skb, features);
3606 skb = sk_validate_xmit_skb(skb, dev);
3610 if (netif_needs_gso(skb, features)) {
3611 struct sk_buff *segs;
3613 segs = skb_gso_segment(skb, features);
3621 if (skb_needs_linearize(skb, features) &&
3622 __skb_linearize(skb))
3625 /* If packet is not checksummed and device does not
3626 * support checksumming for this protocol, complete
3627 * checksumming here.
3629 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3630 if (skb->encapsulation)
3631 skb_set_inner_transport_header(skb,
3632 skb_checksum_start_offset(skb));
3634 skb_set_transport_header(skb,
3635 skb_checksum_start_offset(skb));
3636 if (skb_csum_hwoffload_help(skb, features))
3641 skb = validate_xmit_xfrm(skb, features, again);
3648 dev_core_stats_tx_dropped_inc(dev);
3652 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3654 struct sk_buff *next, *head = NULL, *tail;
3656 for (; skb != NULL; skb = next) {
3658 skb_mark_not_on_list(skb);
3660 /* in case skb wont be segmented, point to itself */
3663 skb = validate_xmit_skb(skb, dev, again);
3671 /* If skb was segmented, skb->prev points to
3672 * the last segment. If not, it still contains skb.
3678 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3680 static void qdisc_pkt_len_init(struct sk_buff *skb)
3682 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3684 qdisc_skb_cb(skb)->pkt_len = skb->len;
3686 /* To get more precise estimation of bytes sent on wire,
3687 * we add to pkt_len the headers size of all segments
3689 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3690 unsigned int hdr_len;
3691 u16 gso_segs = shinfo->gso_segs;
3693 /* mac layer + network layer */
3694 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3696 /* + transport layer */
3697 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3698 const struct tcphdr *th;
3699 struct tcphdr _tcphdr;
3701 th = skb_header_pointer(skb, skb_transport_offset(skb),
3702 sizeof(_tcphdr), &_tcphdr);
3704 hdr_len += __tcp_hdrlen(th);
3706 struct udphdr _udphdr;
3708 if (skb_header_pointer(skb, skb_transport_offset(skb),
3709 sizeof(_udphdr), &_udphdr))
3710 hdr_len += sizeof(struct udphdr);
3713 if (shinfo->gso_type & SKB_GSO_DODGY)
3714 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3717 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3721 static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q,
3722 struct sk_buff **to_free,
3723 struct netdev_queue *txq)
3727 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK;
3728 if (rc == NET_XMIT_SUCCESS)
3729 trace_qdisc_enqueue(q, txq, skb);
3733 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3734 struct net_device *dev,
3735 struct netdev_queue *txq)
3737 spinlock_t *root_lock = qdisc_lock(q);
3738 struct sk_buff *to_free = NULL;
3742 qdisc_calculate_pkt_len(skb, q);
3744 if (q->flags & TCQ_F_NOLOCK) {
3745 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) &&
3746 qdisc_run_begin(q)) {
3747 /* Retest nolock_qdisc_is_empty() within the protection
3748 * of q->seqlock to protect from racing with requeuing.
3750 if (unlikely(!nolock_qdisc_is_empty(q))) {
3751 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3758 qdisc_bstats_cpu_update(q, skb);
3759 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) &&
3760 !nolock_qdisc_is_empty(q))
3764 return NET_XMIT_SUCCESS;
3767 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3771 if (unlikely(to_free))
3772 kfree_skb_list_reason(to_free,
3773 SKB_DROP_REASON_QDISC_DROP);
3778 * Heuristic to force contended enqueues to serialize on a
3779 * separate lock before trying to get qdisc main lock.
3780 * This permits qdisc->running owner to get the lock more
3781 * often and dequeue packets faster.
3782 * On PREEMPT_RT it is possible to preempt the qdisc owner during xmit
3783 * and then other tasks will only enqueue packets. The packets will be
3784 * sent after the qdisc owner is scheduled again. To prevent this
3785 * scenario the task always serialize on the lock.
3787 contended = qdisc_is_running(q) || IS_ENABLED(CONFIG_PREEMPT_RT);
3788 if (unlikely(contended))
3789 spin_lock(&q->busylock);
3791 spin_lock(root_lock);
3792 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3793 __qdisc_drop(skb, &to_free);
3795 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3796 qdisc_run_begin(q)) {
3798 * This is a work-conserving queue; there are no old skbs
3799 * waiting to be sent out; and the qdisc is not running -
3800 * xmit the skb directly.
3803 qdisc_bstats_update(q, skb);
3805 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3806 if (unlikely(contended)) {
3807 spin_unlock(&q->busylock);
3814 rc = NET_XMIT_SUCCESS;
3816 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3817 if (qdisc_run_begin(q)) {
3818 if (unlikely(contended)) {
3819 spin_unlock(&q->busylock);
3826 spin_unlock(root_lock);
3827 if (unlikely(to_free))
3828 kfree_skb_list_reason(to_free, SKB_DROP_REASON_QDISC_DROP);
3829 if (unlikely(contended))
3830 spin_unlock(&q->busylock);
3834 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3835 static void skb_update_prio(struct sk_buff *skb)
3837 const struct netprio_map *map;
3838 const struct sock *sk;
3839 unsigned int prioidx;
3843 map = rcu_dereference_bh(skb->dev->priomap);
3846 sk = skb_to_full_sk(skb);
3850 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3852 if (prioidx < map->priomap_len)
3853 skb->priority = map->priomap[prioidx];
3856 #define skb_update_prio(skb)
3860 * dev_loopback_xmit - loop back @skb
3861 * @net: network namespace this loopback is happening in
3862 * @sk: sk needed to be a netfilter okfn
3863 * @skb: buffer to transmit
3865 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3867 skb_reset_mac_header(skb);
3868 __skb_pull(skb, skb_network_offset(skb));
3869 skb->pkt_type = PACKET_LOOPBACK;
3870 if (skb->ip_summed == CHECKSUM_NONE)
3871 skb->ip_summed = CHECKSUM_UNNECESSARY;
3872 WARN_ON(!skb_dst(skb));
3877 EXPORT_SYMBOL(dev_loopback_xmit);
3879 #ifdef CONFIG_NET_EGRESS
3880 static struct sk_buff *
3881 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3883 #ifdef CONFIG_NET_CLS_ACT
3884 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3885 struct tcf_result cl_res;
3890 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3891 tc_skb_cb(skb)->mru = 0;
3892 tc_skb_cb(skb)->post_ct = false;
3893 mini_qdisc_bstats_cpu_update(miniq, skb);
3895 switch (tcf_classify(skb, miniq->block, miniq->filter_list, &cl_res, false)) {
3897 case TC_ACT_RECLASSIFY:
3898 skb->tc_index = TC_H_MIN(cl_res.classid);
3901 mini_qdisc_qstats_cpu_drop(miniq);
3902 *ret = NET_XMIT_DROP;
3903 kfree_skb_reason(skb, SKB_DROP_REASON_TC_EGRESS);
3908 *ret = NET_XMIT_SUCCESS;
3911 case TC_ACT_REDIRECT:
3912 /* No need to push/pop skb's mac_header here on egress! */
3913 skb_do_redirect(skb);
3914 *ret = NET_XMIT_SUCCESS;
3919 #endif /* CONFIG_NET_CLS_ACT */
3923 #endif /* CONFIG_NET_EGRESS */
3926 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3927 struct xps_dev_maps *dev_maps, unsigned int tci)
3929 int tc = netdev_get_prio_tc_map(dev, skb->priority);
3930 struct xps_map *map;
3931 int queue_index = -1;
3933 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids)
3936 tci *= dev_maps->num_tc;
3939 map = rcu_dereference(dev_maps->attr_map[tci]);
3942 queue_index = map->queues[0];
3944 queue_index = map->queues[reciprocal_scale(
3945 skb_get_hash(skb), map->len)];
3946 if (unlikely(queue_index >= dev->real_num_tx_queues))
3953 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3954 struct sk_buff *skb)
3957 struct xps_dev_maps *dev_maps;
3958 struct sock *sk = skb->sk;
3959 int queue_index = -1;
3961 if (!static_key_false(&xps_needed))
3965 if (!static_key_false(&xps_rxqs_needed))
3968 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]);
3970 int tci = sk_rx_queue_get(sk);
3973 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3978 if (queue_index < 0) {
3979 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]);
3981 unsigned int tci = skb->sender_cpu - 1;
3983 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3995 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3996 struct net_device *sb_dev)
4000 EXPORT_SYMBOL(dev_pick_tx_zero);
4002 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
4003 struct net_device *sb_dev)
4005 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
4007 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
4009 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4010 struct net_device *sb_dev)
4012 struct sock *sk = skb->sk;
4013 int queue_index = sk_tx_queue_get(sk);
4015 sb_dev = sb_dev ? : dev;
4017 if (queue_index < 0 || skb->ooo_okay ||
4018 queue_index >= dev->real_num_tx_queues) {
4019 int new_index = get_xps_queue(dev, sb_dev, skb);
4022 new_index = skb_tx_hash(dev, sb_dev, skb);
4024 if (queue_index != new_index && sk &&
4026 rcu_access_pointer(sk->sk_dst_cache))
4027 sk_tx_queue_set(sk, new_index);
4029 queue_index = new_index;
4034 EXPORT_SYMBOL(netdev_pick_tx);
4036 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4037 struct sk_buff *skb,
4038 struct net_device *sb_dev)
4040 int queue_index = 0;
4043 u32 sender_cpu = skb->sender_cpu - 1;
4045 if (sender_cpu >= (u32)NR_CPUS)
4046 skb->sender_cpu = raw_smp_processor_id() + 1;
4049 if (dev->real_num_tx_queues != 1) {
4050 const struct net_device_ops *ops = dev->netdev_ops;
4052 if (ops->ndo_select_queue)
4053 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4055 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4057 queue_index = netdev_cap_txqueue(dev, queue_index);
4060 skb_set_queue_mapping(skb, queue_index);
4061 return netdev_get_tx_queue(dev, queue_index);
4065 * __dev_queue_xmit - transmit a buffer
4066 * @skb: buffer to transmit
4067 * @sb_dev: suboordinate device used for L2 forwarding offload
4069 * Queue a buffer for transmission to a network device. The caller must
4070 * have set the device and priority and built the buffer before calling
4071 * this function. The function can be called from an interrupt.
4073 * A negative errno code is returned on a failure. A success does not
4074 * guarantee the frame will be transmitted as it may be dropped due
4075 * to congestion or traffic shaping.
4077 * -----------------------------------------------------------------------------------
4078 * I notice this method can also return errors from the queue disciplines,
4079 * including NET_XMIT_DROP, which is a positive value. So, errors can also
4082 * Regardless of the return value, the skb is consumed, so it is currently
4083 * difficult to retry a send to this method. (You can bump the ref count
4084 * before sending to hold a reference for retry if you are careful.)
4086 * When calling this method, interrupts MUST be enabled. This is because
4087 * the BH enable code must have IRQs enabled so that it will not deadlock.
4090 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4092 struct net_device *dev = skb->dev;
4093 struct netdev_queue *txq;
4098 skb_reset_mac_header(skb);
4100 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4101 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED);
4103 /* Disable soft irqs for various locks below. Also
4104 * stops preemption for RCU.
4108 skb_update_prio(skb);
4110 qdisc_pkt_len_init(skb);
4111 #ifdef CONFIG_NET_CLS_ACT
4112 skb->tc_at_ingress = 0;
4114 #ifdef CONFIG_NET_EGRESS
4115 if (static_branch_unlikely(&egress_needed_key)) {
4116 if (nf_hook_egress_active()) {
4117 skb = nf_hook_egress(skb, &rc, dev);
4121 nf_skip_egress(skb, true);
4122 skb = sch_handle_egress(skb, &rc, dev);
4125 nf_skip_egress(skb, false);
4128 /* If device/qdisc don't need skb->dst, release it right now while
4129 * its hot in this cpu cache.
4131 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4136 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4137 q = rcu_dereference_bh(txq->qdisc);
4139 trace_net_dev_queue(skb);
4141 rc = __dev_xmit_skb(skb, q, dev, txq);
4145 /* The device has no queue. Common case for software devices:
4146 * loopback, all the sorts of tunnels...
4148 * Really, it is unlikely that netif_tx_lock protection is necessary
4149 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4151 * However, it is possible, that they rely on protection
4154 * Check this and shot the lock. It is not prone from deadlocks.
4155 *Either shot noqueue qdisc, it is even simpler 8)
4157 if (dev->flags & IFF_UP) {
4158 int cpu = smp_processor_id(); /* ok because BHs are off */
4160 /* Other cpus might concurrently change txq->xmit_lock_owner
4161 * to -1 or to their cpu id, but not to our id.
4163 if (READ_ONCE(txq->xmit_lock_owner) != cpu) {
4164 if (dev_xmit_recursion())
4165 goto recursion_alert;
4167 skb = validate_xmit_skb(skb, dev, &again);
4171 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4172 HARD_TX_LOCK(dev, txq, cpu);
4174 if (!netif_xmit_stopped(txq)) {
4175 dev_xmit_recursion_inc();
4176 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4177 dev_xmit_recursion_dec();
4178 if (dev_xmit_complete(rc)) {
4179 HARD_TX_UNLOCK(dev, txq);
4183 HARD_TX_UNLOCK(dev, txq);
4184 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4187 /* Recursion is detected! It is possible,
4191 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4197 rcu_read_unlock_bh();
4199 dev_core_stats_tx_dropped_inc(dev);
4200 kfree_skb_list(skb);
4203 rcu_read_unlock_bh();
4207 int dev_queue_xmit(struct sk_buff *skb)
4209 return __dev_queue_xmit(skb, NULL);
4211 EXPORT_SYMBOL(dev_queue_xmit);
4213 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
4215 return __dev_queue_xmit(skb, sb_dev);
4217 EXPORT_SYMBOL(dev_queue_xmit_accel);
4219 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4221 struct net_device *dev = skb->dev;
4222 struct sk_buff *orig_skb = skb;
4223 struct netdev_queue *txq;
4224 int ret = NETDEV_TX_BUSY;
4227 if (unlikely(!netif_running(dev) ||
4228 !netif_carrier_ok(dev)))
4231 skb = validate_xmit_skb_list(skb, dev, &again);
4232 if (skb != orig_skb)
4235 skb_set_queue_mapping(skb, queue_id);
4236 txq = skb_get_tx_queue(dev, skb);
4237 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4241 dev_xmit_recursion_inc();
4242 HARD_TX_LOCK(dev, txq, smp_processor_id());
4243 if (!netif_xmit_frozen_or_drv_stopped(txq))
4244 ret = netdev_start_xmit(skb, dev, txq, false);
4245 HARD_TX_UNLOCK(dev, txq);
4246 dev_xmit_recursion_dec();
4251 dev_core_stats_tx_dropped_inc(dev);
4252 kfree_skb_list(skb);
4253 return NET_XMIT_DROP;
4255 EXPORT_SYMBOL(__dev_direct_xmit);
4257 /*************************************************************************
4259 *************************************************************************/
4261 int netdev_max_backlog __read_mostly = 1000;
4262 EXPORT_SYMBOL(netdev_max_backlog);
4264 int netdev_tstamp_prequeue __read_mostly = 1;
4265 int netdev_budget __read_mostly = 300;
4266 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4267 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4268 int weight_p __read_mostly = 64; /* old backlog weight */
4269 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4270 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4271 int dev_rx_weight __read_mostly = 64;
4272 int dev_tx_weight __read_mostly = 64;
4274 /* Called with irq disabled */
4275 static inline void ____napi_schedule(struct softnet_data *sd,
4276 struct napi_struct *napi)
4278 struct task_struct *thread;
4280 lockdep_assert_irqs_disabled();
4282 if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
4283 /* Paired with smp_mb__before_atomic() in
4284 * napi_enable()/dev_set_threaded().
4285 * Use READ_ONCE() to guarantee a complete
4286 * read on napi->thread. Only call
4287 * wake_up_process() when it's not NULL.
4289 thread = READ_ONCE(napi->thread);
4291 /* Avoid doing set_bit() if the thread is in
4292 * INTERRUPTIBLE state, cause napi_thread_wait()
4293 * makes sure to proceed with napi polling
4294 * if the thread is explicitly woken from here.
4296 if (READ_ONCE(thread->__state) != TASK_INTERRUPTIBLE)
4297 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
4298 wake_up_process(thread);
4303 list_add_tail(&napi->poll_list, &sd->poll_list);
4304 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4309 /* One global table that all flow-based protocols share. */
4310 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4311 EXPORT_SYMBOL(rps_sock_flow_table);
4312 u32 rps_cpu_mask __read_mostly;
4313 EXPORT_SYMBOL(rps_cpu_mask);
4315 struct static_key_false rps_needed __read_mostly;
4316 EXPORT_SYMBOL(rps_needed);
4317 struct static_key_false rfs_needed __read_mostly;
4318 EXPORT_SYMBOL(rfs_needed);
4320 static struct rps_dev_flow *
4321 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4322 struct rps_dev_flow *rflow, u16 next_cpu)
4324 if (next_cpu < nr_cpu_ids) {
4325 #ifdef CONFIG_RFS_ACCEL
4326 struct netdev_rx_queue *rxqueue;
4327 struct rps_dev_flow_table *flow_table;
4328 struct rps_dev_flow *old_rflow;
4333 /* Should we steer this flow to a different hardware queue? */
4334 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4335 !(dev->features & NETIF_F_NTUPLE))
4337 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4338 if (rxq_index == skb_get_rx_queue(skb))
4341 rxqueue = dev->_rx + rxq_index;
4342 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4345 flow_id = skb_get_hash(skb) & flow_table->mask;
4346 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4347 rxq_index, flow_id);
4351 rflow = &flow_table->flows[flow_id];
4353 if (old_rflow->filter == rflow->filter)
4354 old_rflow->filter = RPS_NO_FILTER;
4358 per_cpu(softnet_data, next_cpu).input_queue_head;
4361 rflow->cpu = next_cpu;
4366 * get_rps_cpu is called from netif_receive_skb and returns the target
4367 * CPU from the RPS map of the receiving queue for a given skb.
4368 * rcu_read_lock must be held on entry.
4370 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4371 struct rps_dev_flow **rflowp)
4373 const struct rps_sock_flow_table *sock_flow_table;
4374 struct netdev_rx_queue *rxqueue = dev->_rx;
4375 struct rps_dev_flow_table *flow_table;
4376 struct rps_map *map;
4381 if (skb_rx_queue_recorded(skb)) {
4382 u16 index = skb_get_rx_queue(skb);
4384 if (unlikely(index >= dev->real_num_rx_queues)) {
4385 WARN_ONCE(dev->real_num_rx_queues > 1,
4386 "%s received packet on queue %u, but number "
4387 "of RX queues is %u\n",
4388 dev->name, index, dev->real_num_rx_queues);
4394 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4396 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4397 map = rcu_dereference(rxqueue->rps_map);
4398 if (!flow_table && !map)
4401 skb_reset_network_header(skb);
4402 hash = skb_get_hash(skb);
4406 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4407 if (flow_table && sock_flow_table) {
4408 struct rps_dev_flow *rflow;
4412 /* First check into global flow table if there is a match */
4413 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4414 if ((ident ^ hash) & ~rps_cpu_mask)
4417 next_cpu = ident & rps_cpu_mask;
4419 /* OK, now we know there is a match,
4420 * we can look at the local (per receive queue) flow table
4422 rflow = &flow_table->flows[hash & flow_table->mask];
4426 * If the desired CPU (where last recvmsg was done) is
4427 * different from current CPU (one in the rx-queue flow
4428 * table entry), switch if one of the following holds:
4429 * - Current CPU is unset (>= nr_cpu_ids).
4430 * - Current CPU is offline.
4431 * - The current CPU's queue tail has advanced beyond the
4432 * last packet that was enqueued using this table entry.
4433 * This guarantees that all previous packets for the flow
4434 * have been dequeued, thus preserving in order delivery.
4436 if (unlikely(tcpu != next_cpu) &&
4437 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4438 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4439 rflow->last_qtail)) >= 0)) {
4441 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4444 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4454 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4455 if (cpu_online(tcpu)) {
4465 #ifdef CONFIG_RFS_ACCEL
4468 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4469 * @dev: Device on which the filter was set
4470 * @rxq_index: RX queue index
4471 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4472 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4474 * Drivers that implement ndo_rx_flow_steer() should periodically call
4475 * this function for each installed filter and remove the filters for
4476 * which it returns %true.
4478 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4479 u32 flow_id, u16 filter_id)
4481 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4482 struct rps_dev_flow_table *flow_table;
4483 struct rps_dev_flow *rflow;
4488 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4489 if (flow_table && flow_id <= flow_table->mask) {
4490 rflow = &flow_table->flows[flow_id];
4491 cpu = READ_ONCE(rflow->cpu);
4492 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4493 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4494 rflow->last_qtail) <
4495 (int)(10 * flow_table->mask)))
4501 EXPORT_SYMBOL(rps_may_expire_flow);
4503 #endif /* CONFIG_RFS_ACCEL */
4505 /* Called from hardirq (IPI) context */
4506 static void rps_trigger_softirq(void *data)
4508 struct softnet_data *sd = data;
4510 ____napi_schedule(sd, &sd->backlog);
4514 #endif /* CONFIG_RPS */
4517 * Check if this softnet_data structure is another cpu one
4518 * If yes, queue it to our IPI list and return 1
4521 static int napi_schedule_rps(struct softnet_data *sd)
4523 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4527 sd->rps_ipi_next = mysd->rps_ipi_list;
4528 mysd->rps_ipi_list = sd;
4530 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4533 #endif /* CONFIG_RPS */
4534 __napi_schedule_irqoff(&mysd->backlog);
4538 #ifdef CONFIG_NET_FLOW_LIMIT
4539 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4542 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4544 #ifdef CONFIG_NET_FLOW_LIMIT
4545 struct sd_flow_limit *fl;
4546 struct softnet_data *sd;
4547 unsigned int old_flow, new_flow;
4549 if (qlen < (netdev_max_backlog >> 1))
4552 sd = this_cpu_ptr(&softnet_data);
4555 fl = rcu_dereference(sd->flow_limit);
4557 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4558 old_flow = fl->history[fl->history_head];
4559 fl->history[fl->history_head] = new_flow;
4562 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4564 if (likely(fl->buckets[old_flow]))
4565 fl->buckets[old_flow]--;
4567 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4579 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4580 * queue (may be a remote CPU queue).
4582 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4583 unsigned int *qtail)
4585 enum skb_drop_reason reason;
4586 struct softnet_data *sd;
4587 unsigned long flags;
4590 reason = SKB_DROP_REASON_NOT_SPECIFIED;
4591 sd = &per_cpu(softnet_data, cpu);
4593 rps_lock_irqsave(sd, &flags);
4594 if (!netif_running(skb->dev))
4596 qlen = skb_queue_len(&sd->input_pkt_queue);
4597 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
4600 __skb_queue_tail(&sd->input_pkt_queue, skb);
4601 input_queue_tail_incr_save(sd, qtail);
4602 rps_unlock_irq_restore(sd, &flags);
4603 return NET_RX_SUCCESS;
4606 /* Schedule NAPI for backlog device
4607 * We can use non atomic operation since we own the queue lock
4609 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state))
4610 napi_schedule_rps(sd);
4613 reason = SKB_DROP_REASON_CPU_BACKLOG;
4617 rps_unlock_irq_restore(sd, &flags);
4619 dev_core_stats_rx_dropped_inc(skb->dev);
4620 kfree_skb_reason(skb, reason);
4624 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4626 struct net_device *dev = skb->dev;
4627 struct netdev_rx_queue *rxqueue;
4631 if (skb_rx_queue_recorded(skb)) {
4632 u16 index = skb_get_rx_queue(skb);
4634 if (unlikely(index >= dev->real_num_rx_queues)) {
4635 WARN_ONCE(dev->real_num_rx_queues > 1,
4636 "%s received packet on queue %u, but number "
4637 "of RX queues is %u\n",
4638 dev->name, index, dev->real_num_rx_queues);
4640 return rxqueue; /* Return first rxqueue */
4647 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp,
4648 struct bpf_prog *xdp_prog)
4650 void *orig_data, *orig_data_end, *hard_start;
4651 struct netdev_rx_queue *rxqueue;
4652 bool orig_bcast, orig_host;
4653 u32 mac_len, frame_sz;
4654 __be16 orig_eth_type;
4659 /* The XDP program wants to see the packet starting at the MAC
4662 mac_len = skb->data - skb_mac_header(skb);
4663 hard_start = skb->data - skb_headroom(skb);
4665 /* SKB "head" area always have tailroom for skb_shared_info */
4666 frame_sz = (void *)skb_end_pointer(skb) - hard_start;
4667 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4669 rxqueue = netif_get_rxqueue(skb);
4670 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq);
4671 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len,
4672 skb_headlen(skb) + mac_len, true);
4674 orig_data_end = xdp->data_end;
4675 orig_data = xdp->data;
4676 eth = (struct ethhdr *)xdp->data;
4677 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr);
4678 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4679 orig_eth_type = eth->h_proto;
4681 act = bpf_prog_run_xdp(xdp_prog, xdp);
4683 /* check if bpf_xdp_adjust_head was used */
4684 off = xdp->data - orig_data;
4687 __skb_pull(skb, off);
4689 __skb_push(skb, -off);
4691 skb->mac_header += off;
4692 skb_reset_network_header(skb);
4695 /* check if bpf_xdp_adjust_tail was used */
4696 off = xdp->data_end - orig_data_end;
4698 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4699 skb->len += off; /* positive on grow, negative on shrink */
4702 /* check if XDP changed eth hdr such SKB needs update */
4703 eth = (struct ethhdr *)xdp->data;
4704 if ((orig_eth_type != eth->h_proto) ||
4705 (orig_host != ether_addr_equal_64bits(eth->h_dest,
4706 skb->dev->dev_addr)) ||
4707 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4708 __skb_push(skb, ETH_HLEN);
4709 skb->pkt_type = PACKET_HOST;
4710 skb->protocol = eth_type_trans(skb, skb->dev);
4713 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull
4714 * before calling us again on redirect path. We do not call do_redirect
4715 * as we leave that up to the caller.
4717 * Caller is responsible for managing lifetime of skb (i.e. calling
4718 * kfree_skb in response to actions it cannot handle/XDP_DROP).
4723 __skb_push(skb, mac_len);
4726 metalen = xdp->data - xdp->data_meta;
4728 skb_metadata_set(skb, metalen);
4735 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4736 struct xdp_buff *xdp,
4737 struct bpf_prog *xdp_prog)
4741 /* Reinjected packets coming from act_mirred or similar should
4742 * not get XDP generic processing.
4744 if (skb_is_redirected(skb))
4747 /* XDP packets must be linear and must have sufficient headroom
4748 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4749 * native XDP provides, thus we need to do it here as well.
4751 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4752 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4753 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4754 int troom = skb->tail + skb->data_len - skb->end;
4756 /* In case we have to go down the path and also linearize,
4757 * then lets do the pskb_expand_head() work just once here.
4759 if (pskb_expand_head(skb,
4760 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4761 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4763 if (skb_linearize(skb))
4767 act = bpf_prog_run_generic_xdp(skb, xdp, xdp_prog);
4774 bpf_warn_invalid_xdp_action(skb->dev, xdp_prog, act);
4777 trace_xdp_exception(skb->dev, xdp_prog, act);
4788 /* When doing generic XDP we have to bypass the qdisc layer and the
4789 * network taps in order to match in-driver-XDP behavior.
4791 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4793 struct net_device *dev = skb->dev;
4794 struct netdev_queue *txq;
4795 bool free_skb = true;
4798 txq = netdev_core_pick_tx(dev, skb, NULL);
4799 cpu = smp_processor_id();
4800 HARD_TX_LOCK(dev, txq, cpu);
4801 if (!netif_xmit_stopped(txq)) {
4802 rc = netdev_start_xmit(skb, dev, txq, 0);
4803 if (dev_xmit_complete(rc))
4806 HARD_TX_UNLOCK(dev, txq);
4808 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4813 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4815 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4818 struct xdp_buff xdp;
4822 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4823 if (act != XDP_PASS) {
4826 err = xdp_do_generic_redirect(skb->dev, skb,
4832 generic_xdp_tx(skb, xdp_prog);
4840 kfree_skb_reason(skb, SKB_DROP_REASON_XDP);
4843 EXPORT_SYMBOL_GPL(do_xdp_generic);
4845 static int netif_rx_internal(struct sk_buff *skb)
4849 net_timestamp_check(netdev_tstamp_prequeue, skb);
4851 trace_netif_rx(skb);
4854 if (static_branch_unlikely(&rps_needed)) {
4855 struct rps_dev_flow voidflow, *rflow = &voidflow;
4860 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4862 cpu = smp_processor_id();
4864 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4872 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail);
4878 * __netif_rx - Slightly optimized version of netif_rx
4879 * @skb: buffer to post
4881 * This behaves as netif_rx except that it does not disable bottom halves.
4882 * As a result this function may only be invoked from the interrupt context
4883 * (either hard or soft interrupt).
4885 int __netif_rx(struct sk_buff *skb)
4889 lockdep_assert_once(hardirq_count() | softirq_count());
4891 trace_netif_rx_entry(skb);
4892 ret = netif_rx_internal(skb);
4893 trace_netif_rx_exit(ret);
4896 EXPORT_SYMBOL(__netif_rx);
4899 * netif_rx - post buffer to the network code
4900 * @skb: buffer to post
4902 * This function receives a packet from a device driver and queues it for
4903 * the upper (protocol) levels to process via the backlog NAPI device. It
4904 * always succeeds. The buffer may be dropped during processing for
4905 * congestion control or by the protocol layers.
4906 * The network buffer is passed via the backlog NAPI device. Modern NIC
4907 * driver should use NAPI and GRO.
4908 * This function can used from interrupt and from process context. The
4909 * caller from process context must not disable interrupts before invoking
4913 * NET_RX_SUCCESS (no congestion)
4914 * NET_RX_DROP (packet was dropped)
4917 int netif_rx(struct sk_buff *skb)
4919 bool need_bh_off = !(hardirq_count() | softirq_count());
4924 trace_netif_rx_entry(skb);
4925 ret = netif_rx_internal(skb);
4926 trace_netif_rx_exit(ret);
4931 EXPORT_SYMBOL(netif_rx);
4933 static __latent_entropy void net_tx_action(struct softirq_action *h)
4935 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4937 if (sd->completion_queue) {
4938 struct sk_buff *clist;
4940 local_irq_disable();
4941 clist = sd->completion_queue;
4942 sd->completion_queue = NULL;
4946 struct sk_buff *skb = clist;
4948 clist = clist->next;
4950 WARN_ON(refcount_read(&skb->users));
4951 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4952 trace_consume_skb(skb);
4954 trace_kfree_skb(skb, net_tx_action,
4955 SKB_DROP_REASON_NOT_SPECIFIED);
4957 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4960 __kfree_skb_defer(skb);
4964 if (sd->output_queue) {
4967 local_irq_disable();
4968 head = sd->output_queue;
4969 sd->output_queue = NULL;
4970 sd->output_queue_tailp = &sd->output_queue;
4976 struct Qdisc *q = head;
4977 spinlock_t *root_lock = NULL;
4979 head = head->next_sched;
4981 /* We need to make sure head->next_sched is read
4982 * before clearing __QDISC_STATE_SCHED
4984 smp_mb__before_atomic();
4986 if (!(q->flags & TCQ_F_NOLOCK)) {
4987 root_lock = qdisc_lock(q);
4988 spin_lock(root_lock);
4989 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
4991 /* There is a synchronize_net() between
4992 * STATE_DEACTIVATED flag being set and
4993 * qdisc_reset()/some_qdisc_is_busy() in
4994 * dev_deactivate(), so we can safely bail out
4995 * early here to avoid data race between
4996 * qdisc_deactivate() and some_qdisc_is_busy()
4997 * for lockless qdisc.
4999 clear_bit(__QDISC_STATE_SCHED, &q->state);
5003 clear_bit(__QDISC_STATE_SCHED, &q->state);
5006 spin_unlock(root_lock);
5012 xfrm_dev_backlog(sd);
5015 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
5016 /* This hook is defined here for ATM LANE */
5017 int (*br_fdb_test_addr_hook)(struct net_device *dev,
5018 unsigned char *addr) __read_mostly;
5019 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
5022 static inline struct sk_buff *
5023 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
5024 struct net_device *orig_dev, bool *another)
5026 #ifdef CONFIG_NET_CLS_ACT
5027 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
5028 struct tcf_result cl_res;
5030 /* If there's at least one ingress present somewhere (so
5031 * we get here via enabled static key), remaining devices
5032 * that are not configured with an ingress qdisc will bail
5039 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5043 qdisc_skb_cb(skb)->pkt_len = skb->len;
5044 tc_skb_cb(skb)->mru = 0;
5045 tc_skb_cb(skb)->post_ct = false;
5046 skb->tc_at_ingress = 1;
5047 mini_qdisc_bstats_cpu_update(miniq, skb);
5049 switch (tcf_classify(skb, miniq->block, miniq->filter_list, &cl_res, false)) {
5051 case TC_ACT_RECLASSIFY:
5052 skb->tc_index = TC_H_MIN(cl_res.classid);
5055 mini_qdisc_qstats_cpu_drop(miniq);
5056 kfree_skb_reason(skb, SKB_DROP_REASON_TC_INGRESS);
5063 case TC_ACT_REDIRECT:
5064 /* skb_mac_header check was done by cls/act_bpf, so
5065 * we can safely push the L2 header back before
5066 * redirecting to another netdev
5068 __skb_push(skb, skb->mac_len);
5069 if (skb_do_redirect(skb) == -EAGAIN) {
5070 __skb_pull(skb, skb->mac_len);
5075 case TC_ACT_CONSUMED:
5080 #endif /* CONFIG_NET_CLS_ACT */
5085 * netdev_is_rx_handler_busy - check if receive handler is registered
5086 * @dev: device to check
5088 * Check if a receive handler is already registered for a given device.
5089 * Return true if there one.
5091 * The caller must hold the rtnl_mutex.
5093 bool netdev_is_rx_handler_busy(struct net_device *dev)
5096 return dev && rtnl_dereference(dev->rx_handler);
5098 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5101 * netdev_rx_handler_register - register receive handler
5102 * @dev: device to register a handler for
5103 * @rx_handler: receive handler to register
5104 * @rx_handler_data: data pointer that is used by rx handler
5106 * Register a receive handler for a device. This handler will then be
5107 * called from __netif_receive_skb. A negative errno code is returned
5110 * The caller must hold the rtnl_mutex.
5112 * For a general description of rx_handler, see enum rx_handler_result.
5114 int netdev_rx_handler_register(struct net_device *dev,
5115 rx_handler_func_t *rx_handler,
5116 void *rx_handler_data)
5118 if (netdev_is_rx_handler_busy(dev))
5121 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5124 /* Note: rx_handler_data must be set before rx_handler */
5125 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5126 rcu_assign_pointer(dev->rx_handler, rx_handler);
5130 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5133 * netdev_rx_handler_unregister - unregister receive handler
5134 * @dev: device to unregister a handler from
5136 * Unregister a receive handler from a device.
5138 * The caller must hold the rtnl_mutex.
5140 void netdev_rx_handler_unregister(struct net_device *dev)
5144 RCU_INIT_POINTER(dev->rx_handler, NULL);
5145 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5146 * section has a guarantee to see a non NULL rx_handler_data
5150 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5152 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5155 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5156 * the special handling of PFMEMALLOC skbs.
5158 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5160 switch (skb->protocol) {
5161 case htons(ETH_P_ARP):
5162 case htons(ETH_P_IP):
5163 case htons(ETH_P_IPV6):
5164 case htons(ETH_P_8021Q):
5165 case htons(ETH_P_8021AD):
5172 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5173 int *ret, struct net_device *orig_dev)
5175 if (nf_hook_ingress_active(skb)) {
5179 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5184 ingress_retval = nf_hook_ingress(skb);
5186 return ingress_retval;
5191 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5192 struct packet_type **ppt_prev)
5194 struct packet_type *ptype, *pt_prev;
5195 rx_handler_func_t *rx_handler;
5196 struct sk_buff *skb = *pskb;
5197 struct net_device *orig_dev;
5198 bool deliver_exact = false;
5199 int ret = NET_RX_DROP;
5202 net_timestamp_check(!netdev_tstamp_prequeue, skb);
5204 trace_netif_receive_skb(skb);
5206 orig_dev = skb->dev;
5208 skb_reset_network_header(skb);
5209 if (!skb_transport_header_was_set(skb))
5210 skb_reset_transport_header(skb);
5211 skb_reset_mac_len(skb);
5216 skb->skb_iif = skb->dev->ifindex;
5218 __this_cpu_inc(softnet_data.processed);
5220 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5224 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5227 if (ret2 != XDP_PASS) {
5233 if (eth_type_vlan(skb->protocol)) {
5234 skb = skb_vlan_untag(skb);
5239 if (skb_skip_tc_classify(skb))
5245 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5247 ret = deliver_skb(skb, pt_prev, orig_dev);
5251 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5253 ret = deliver_skb(skb, pt_prev, orig_dev);
5258 #ifdef CONFIG_NET_INGRESS
5259 if (static_branch_unlikely(&ingress_needed_key)) {
5260 bool another = false;
5262 nf_skip_egress(skb, true);
5263 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5270 nf_skip_egress(skb, false);
5271 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5275 skb_reset_redirect(skb);
5277 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5280 if (skb_vlan_tag_present(skb)) {
5282 ret = deliver_skb(skb, pt_prev, orig_dev);
5285 if (vlan_do_receive(&skb))
5287 else if (unlikely(!skb))
5291 rx_handler = rcu_dereference(skb->dev->rx_handler);
5294 ret = deliver_skb(skb, pt_prev, orig_dev);
5297 switch (rx_handler(&skb)) {
5298 case RX_HANDLER_CONSUMED:
5299 ret = NET_RX_SUCCESS;
5301 case RX_HANDLER_ANOTHER:
5303 case RX_HANDLER_EXACT:
5304 deliver_exact = true;
5306 case RX_HANDLER_PASS:
5313 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5315 if (skb_vlan_tag_get_id(skb)) {
5316 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5319 skb->pkt_type = PACKET_OTHERHOST;
5320 } else if (eth_type_vlan(skb->protocol)) {
5321 /* Outer header is 802.1P with vlan 0, inner header is
5322 * 802.1Q or 802.1AD and vlan_do_receive() above could
5323 * not find vlan dev for vlan id 0.
5325 __vlan_hwaccel_clear_tag(skb);
5326 skb = skb_vlan_untag(skb);
5329 if (vlan_do_receive(&skb))
5330 /* After stripping off 802.1P header with vlan 0
5331 * vlan dev is found for inner header.
5334 else if (unlikely(!skb))
5337 /* We have stripped outer 802.1P vlan 0 header.
5338 * But could not find vlan dev.
5339 * check again for vlan id to set OTHERHOST.
5343 /* Note: we might in the future use prio bits
5344 * and set skb->priority like in vlan_do_receive()
5345 * For the time being, just ignore Priority Code Point
5347 __vlan_hwaccel_clear_tag(skb);
5350 type = skb->protocol;
5352 /* deliver only exact match when indicated */
5353 if (likely(!deliver_exact)) {
5354 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5355 &ptype_base[ntohs(type) &
5359 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5360 &orig_dev->ptype_specific);
5362 if (unlikely(skb->dev != orig_dev)) {
5363 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5364 &skb->dev->ptype_specific);
5368 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5370 *ppt_prev = pt_prev;
5373 if (!deliver_exact) {
5374 dev_core_stats_rx_dropped_inc(skb->dev);
5375 kfree_skb_reason(skb, SKB_DROP_REASON_PTYPE_ABSENT);
5377 dev_core_stats_rx_nohandler_inc(skb->dev);
5380 /* Jamal, now you will not able to escape explaining
5381 * me how you were going to use this. :-)
5387 /* The invariant here is that if *ppt_prev is not NULL
5388 * then skb should also be non-NULL.
5390 * Apparently *ppt_prev assignment above holds this invariant due to
5391 * skb dereferencing near it.
5397 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5399 struct net_device *orig_dev = skb->dev;
5400 struct packet_type *pt_prev = NULL;
5403 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5405 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5406 skb->dev, pt_prev, orig_dev);
5411 * netif_receive_skb_core - special purpose version of netif_receive_skb
5412 * @skb: buffer to process
5414 * More direct receive version of netif_receive_skb(). It should
5415 * only be used by callers that have a need to skip RPS and Generic XDP.
5416 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5418 * This function may only be called from softirq context and interrupts
5419 * should be enabled.
5421 * Return values (usually ignored):
5422 * NET_RX_SUCCESS: no congestion
5423 * NET_RX_DROP: packet was dropped
5425 int netif_receive_skb_core(struct sk_buff *skb)
5430 ret = __netif_receive_skb_one_core(skb, false);
5435 EXPORT_SYMBOL(netif_receive_skb_core);
5437 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5438 struct packet_type *pt_prev,
5439 struct net_device *orig_dev)
5441 struct sk_buff *skb, *next;
5445 if (list_empty(head))
5447 if (pt_prev->list_func != NULL)
5448 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5449 ip_list_rcv, head, pt_prev, orig_dev);
5451 list_for_each_entry_safe(skb, next, head, list) {
5452 skb_list_del_init(skb);
5453 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5457 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5459 /* Fast-path assumptions:
5460 * - There is no RX handler.
5461 * - Only one packet_type matches.
5462 * If either of these fails, we will end up doing some per-packet
5463 * processing in-line, then handling the 'last ptype' for the whole
5464 * sublist. This can't cause out-of-order delivery to any single ptype,
5465 * because the 'last ptype' must be constant across the sublist, and all
5466 * other ptypes are handled per-packet.
5468 /* Current (common) ptype of sublist */
5469 struct packet_type *pt_curr = NULL;
5470 /* Current (common) orig_dev of sublist */
5471 struct net_device *od_curr = NULL;
5472 struct list_head sublist;
5473 struct sk_buff *skb, *next;
5475 INIT_LIST_HEAD(&sublist);
5476 list_for_each_entry_safe(skb, next, head, list) {
5477 struct net_device *orig_dev = skb->dev;
5478 struct packet_type *pt_prev = NULL;
5480 skb_list_del_init(skb);
5481 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5484 if (pt_curr != pt_prev || od_curr != orig_dev) {
5485 /* dispatch old sublist */
5486 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5487 /* start new sublist */
5488 INIT_LIST_HEAD(&sublist);
5492 list_add_tail(&skb->list, &sublist);
5495 /* dispatch final sublist */
5496 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5499 static int __netif_receive_skb(struct sk_buff *skb)
5503 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5504 unsigned int noreclaim_flag;
5507 * PFMEMALLOC skbs are special, they should
5508 * - be delivered to SOCK_MEMALLOC sockets only
5509 * - stay away from userspace
5510 * - have bounded memory usage
5512 * Use PF_MEMALLOC as this saves us from propagating the allocation
5513 * context down to all allocation sites.
5515 noreclaim_flag = memalloc_noreclaim_save();
5516 ret = __netif_receive_skb_one_core(skb, true);
5517 memalloc_noreclaim_restore(noreclaim_flag);
5519 ret = __netif_receive_skb_one_core(skb, false);
5524 static void __netif_receive_skb_list(struct list_head *head)
5526 unsigned long noreclaim_flag = 0;
5527 struct sk_buff *skb, *next;
5528 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5530 list_for_each_entry_safe(skb, next, head, list) {
5531 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5532 struct list_head sublist;
5534 /* Handle the previous sublist */
5535 list_cut_before(&sublist, head, &skb->list);
5536 if (!list_empty(&sublist))
5537 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5538 pfmemalloc = !pfmemalloc;
5539 /* See comments in __netif_receive_skb */
5541 noreclaim_flag = memalloc_noreclaim_save();
5543 memalloc_noreclaim_restore(noreclaim_flag);
5546 /* Handle the remaining sublist */
5547 if (!list_empty(head))
5548 __netif_receive_skb_list_core(head, pfmemalloc);
5549 /* Restore pflags */
5551 memalloc_noreclaim_restore(noreclaim_flag);
5554 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5556 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5557 struct bpf_prog *new = xdp->prog;
5560 switch (xdp->command) {
5561 case XDP_SETUP_PROG:
5562 rcu_assign_pointer(dev->xdp_prog, new);
5567 static_branch_dec(&generic_xdp_needed_key);
5568 } else if (new && !old) {
5569 static_branch_inc(&generic_xdp_needed_key);
5570 dev_disable_lro(dev);
5571 dev_disable_gro_hw(dev);
5583 static int netif_receive_skb_internal(struct sk_buff *skb)
5587 net_timestamp_check(netdev_tstamp_prequeue, skb);
5589 if (skb_defer_rx_timestamp(skb))
5590 return NET_RX_SUCCESS;
5594 if (static_branch_unlikely(&rps_needed)) {
5595 struct rps_dev_flow voidflow, *rflow = &voidflow;
5596 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5599 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5605 ret = __netif_receive_skb(skb);
5610 void netif_receive_skb_list_internal(struct list_head *head)
5612 struct sk_buff *skb, *next;
5613 struct list_head sublist;
5615 INIT_LIST_HEAD(&sublist);
5616 list_for_each_entry_safe(skb, next, head, list) {
5617 net_timestamp_check(netdev_tstamp_prequeue, skb);
5618 skb_list_del_init(skb);
5619 if (!skb_defer_rx_timestamp(skb))
5620 list_add_tail(&skb->list, &sublist);
5622 list_splice_init(&sublist, head);
5626 if (static_branch_unlikely(&rps_needed)) {
5627 list_for_each_entry_safe(skb, next, head, list) {
5628 struct rps_dev_flow voidflow, *rflow = &voidflow;
5629 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5632 /* Will be handled, remove from list */
5633 skb_list_del_init(skb);
5634 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5639 __netif_receive_skb_list(head);
5644 * netif_receive_skb - process receive buffer from network
5645 * @skb: buffer to process
5647 * netif_receive_skb() is the main receive data processing function.
5648 * It always succeeds. The buffer may be dropped during processing
5649 * for congestion control or by the protocol layers.
5651 * This function may only be called from softirq context and interrupts
5652 * should be enabled.
5654 * Return values (usually ignored):
5655 * NET_RX_SUCCESS: no congestion
5656 * NET_RX_DROP: packet was dropped
5658 int netif_receive_skb(struct sk_buff *skb)
5662 trace_netif_receive_skb_entry(skb);
5664 ret = netif_receive_skb_internal(skb);
5665 trace_netif_receive_skb_exit(ret);
5669 EXPORT_SYMBOL(netif_receive_skb);
5672 * netif_receive_skb_list - process many receive buffers from network
5673 * @head: list of skbs to process.
5675 * Since return value of netif_receive_skb() is normally ignored, and
5676 * wouldn't be meaningful for a list, this function returns void.
5678 * This function may only be called from softirq context and interrupts
5679 * should be enabled.
5681 void netif_receive_skb_list(struct list_head *head)
5683 struct sk_buff *skb;
5685 if (list_empty(head))
5687 if (trace_netif_receive_skb_list_entry_enabled()) {
5688 list_for_each_entry(skb, head, list)
5689 trace_netif_receive_skb_list_entry(skb);
5691 netif_receive_skb_list_internal(head);
5692 trace_netif_receive_skb_list_exit(0);
5694 EXPORT_SYMBOL(netif_receive_skb_list);
5696 static DEFINE_PER_CPU(struct work_struct, flush_works);
5698 /* Network device is going away, flush any packets still pending */
5699 static void flush_backlog(struct work_struct *work)
5701 struct sk_buff *skb, *tmp;
5702 struct softnet_data *sd;
5705 sd = this_cpu_ptr(&softnet_data);
5707 rps_lock_irq_disable(sd);
5708 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5709 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5710 __skb_unlink(skb, &sd->input_pkt_queue);
5711 dev_kfree_skb_irq(skb);
5712 input_queue_head_incr(sd);
5715 rps_unlock_irq_enable(sd);
5717 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5718 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5719 __skb_unlink(skb, &sd->process_queue);
5721 input_queue_head_incr(sd);
5727 static bool flush_required(int cpu)
5729 #if IS_ENABLED(CONFIG_RPS)
5730 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5733 rps_lock_irq_disable(sd);
5735 /* as insertion into process_queue happens with the rps lock held,
5736 * process_queue access may race only with dequeue
5738 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5739 !skb_queue_empty_lockless(&sd->process_queue);
5740 rps_unlock_irq_enable(sd);
5744 /* without RPS we can't safely check input_pkt_queue: during a
5745 * concurrent remote skb_queue_splice() we can detect as empty both
5746 * input_pkt_queue and process_queue even if the latter could end-up
5747 * containing a lot of packets.
5752 static void flush_all_backlogs(void)
5754 static cpumask_t flush_cpus;
5757 /* since we are under rtnl lock protection we can use static data
5758 * for the cpumask and avoid allocating on stack the possibly
5765 cpumask_clear(&flush_cpus);
5766 for_each_online_cpu(cpu) {
5767 if (flush_required(cpu)) {
5768 queue_work_on(cpu, system_highpri_wq,
5769 per_cpu_ptr(&flush_works, cpu));
5770 cpumask_set_cpu(cpu, &flush_cpus);
5774 /* we can have in flight packet[s] on the cpus we are not flushing,
5775 * synchronize_net() in unregister_netdevice_many() will take care of
5778 for_each_cpu(cpu, &flush_cpus)
5779 flush_work(per_cpu_ptr(&flush_works, cpu));
5784 static void net_rps_send_ipi(struct softnet_data *remsd)
5788 struct softnet_data *next = remsd->rps_ipi_next;
5790 if (cpu_online(remsd->cpu))
5791 smp_call_function_single_async(remsd->cpu, &remsd->csd);
5798 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
5799 * Note: called with local irq disabled, but exits with local irq enabled.
5801 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
5804 struct softnet_data *remsd = sd->rps_ipi_list;
5807 sd->rps_ipi_list = NULL;
5811 /* Send pending IPI's to kick RPS processing on remote cpus. */
5812 net_rps_send_ipi(remsd);
5818 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
5821 return sd->rps_ipi_list != NULL;
5827 static int process_backlog(struct napi_struct *napi, int quota)
5829 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
5833 /* Check if we have pending ipi, its better to send them now,
5834 * not waiting net_rx_action() end.
5836 if (sd_has_rps_ipi_waiting(sd)) {
5837 local_irq_disable();
5838 net_rps_action_and_irq_enable(sd);
5841 napi->weight = dev_rx_weight;
5843 struct sk_buff *skb;
5845 while ((skb = __skb_dequeue(&sd->process_queue))) {
5847 __netif_receive_skb(skb);
5849 input_queue_head_incr(sd);
5850 if (++work >= quota)
5855 rps_lock_irq_disable(sd);
5856 if (skb_queue_empty(&sd->input_pkt_queue)) {
5858 * Inline a custom version of __napi_complete().
5859 * only current cpu owns and manipulates this napi,
5860 * and NAPI_STATE_SCHED is the only possible flag set
5862 * We can use a plain write instead of clear_bit(),
5863 * and we dont need an smp_mb() memory barrier.
5868 skb_queue_splice_tail_init(&sd->input_pkt_queue,
5869 &sd->process_queue);
5871 rps_unlock_irq_enable(sd);
5878 * __napi_schedule - schedule for receive
5879 * @n: entry to schedule
5881 * The entry's receive function will be scheduled to run.
5882 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
5884 void __napi_schedule(struct napi_struct *n)
5886 unsigned long flags;
5888 local_irq_save(flags);
5889 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5890 local_irq_restore(flags);
5892 EXPORT_SYMBOL(__napi_schedule);
5895 * napi_schedule_prep - check if napi can be scheduled
5898 * Test if NAPI routine is already running, and if not mark
5899 * it as running. This is used as a condition variable to
5900 * insure only one NAPI poll instance runs. We also make
5901 * sure there is no pending NAPI disable.
5903 bool napi_schedule_prep(struct napi_struct *n)
5905 unsigned long val, new;
5908 val = READ_ONCE(n->state);
5909 if (unlikely(val & NAPIF_STATE_DISABLE))
5911 new = val | NAPIF_STATE_SCHED;
5913 /* Sets STATE_MISSED bit if STATE_SCHED was already set
5914 * This was suggested by Alexander Duyck, as compiler
5915 * emits better code than :
5916 * if (val & NAPIF_STATE_SCHED)
5917 * new |= NAPIF_STATE_MISSED;
5919 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
5921 } while (cmpxchg(&n->state, val, new) != val);
5923 return !(val & NAPIF_STATE_SCHED);
5925 EXPORT_SYMBOL(napi_schedule_prep);
5928 * __napi_schedule_irqoff - schedule for receive
5929 * @n: entry to schedule
5931 * Variant of __napi_schedule() assuming hard irqs are masked.
5933 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
5934 * because the interrupt disabled assumption might not be true
5935 * due to force-threaded interrupts and spinlock substitution.
5937 void __napi_schedule_irqoff(struct napi_struct *n)
5939 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
5940 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5944 EXPORT_SYMBOL(__napi_schedule_irqoff);
5946 bool napi_complete_done(struct napi_struct *n, int work_done)
5948 unsigned long flags, val, new, timeout = 0;
5952 * 1) Don't let napi dequeue from the cpu poll list
5953 * just in case its running on a different cpu.
5954 * 2) If we are busy polling, do nothing here, we have
5955 * the guarantee we will be called later.
5957 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
5958 NAPIF_STATE_IN_BUSY_POLL)))
5963 timeout = READ_ONCE(n->dev->gro_flush_timeout);
5964 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
5966 if (n->defer_hard_irqs_count > 0) {
5967 n->defer_hard_irqs_count--;
5968 timeout = READ_ONCE(n->dev->gro_flush_timeout);
5972 if (n->gro_bitmask) {
5973 /* When the NAPI instance uses a timeout and keeps postponing
5974 * it, we need to bound somehow the time packets are kept in
5977 napi_gro_flush(n, !!timeout);
5982 if (unlikely(!list_empty(&n->poll_list))) {
5983 /* If n->poll_list is not empty, we need to mask irqs */
5984 local_irq_save(flags);
5985 list_del_init(&n->poll_list);
5986 local_irq_restore(flags);
5990 val = READ_ONCE(n->state);
5992 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
5994 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
5995 NAPIF_STATE_SCHED_THREADED |
5996 NAPIF_STATE_PREFER_BUSY_POLL);
5998 /* If STATE_MISSED was set, leave STATE_SCHED set,
5999 * because we will call napi->poll() one more time.
6000 * This C code was suggested by Alexander Duyck to help gcc.
6002 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6004 } while (cmpxchg(&n->state, val, new) != val);
6006 if (unlikely(val & NAPIF_STATE_MISSED)) {
6012 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6013 HRTIMER_MODE_REL_PINNED);
6016 EXPORT_SYMBOL(napi_complete_done);
6018 /* must be called under rcu_read_lock(), as we dont take a reference */
6019 static struct napi_struct *napi_by_id(unsigned int napi_id)
6021 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6022 struct napi_struct *napi;
6024 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6025 if (napi->napi_id == napi_id)
6031 #if defined(CONFIG_NET_RX_BUSY_POLL)
6033 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
6035 if (!skip_schedule) {
6036 gro_normal_list(napi);
6037 __napi_schedule(napi);
6041 if (napi->gro_bitmask) {
6042 /* flush too old packets
6043 * If HZ < 1000, flush all packets.
6045 napi_gro_flush(napi, HZ >= 1000);
6048 gro_normal_list(napi);
6049 clear_bit(NAPI_STATE_SCHED, &napi->state);
6052 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, bool prefer_busy_poll,
6055 bool skip_schedule = false;
6056 unsigned long timeout;
6059 /* Busy polling means there is a high chance device driver hard irq
6060 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6061 * set in napi_schedule_prep().
6062 * Since we are about to call napi->poll() once more, we can safely
6063 * clear NAPI_STATE_MISSED.
6065 * Note: x86 could use a single "lock and ..." instruction
6066 * to perform these two clear_bit()
6068 clear_bit(NAPI_STATE_MISSED, &napi->state);
6069 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6073 if (prefer_busy_poll) {
6074 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
6075 timeout = READ_ONCE(napi->dev->gro_flush_timeout);
6076 if (napi->defer_hard_irqs_count && timeout) {
6077 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
6078 skip_schedule = true;
6082 /* All we really want here is to re-enable device interrupts.
6083 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6085 rc = napi->poll(napi, budget);
6086 /* We can't gro_normal_list() here, because napi->poll() might have
6087 * rearmed the napi (napi_complete_done()) in which case it could
6088 * already be running on another CPU.
6090 trace_napi_poll(napi, rc, budget);
6091 netpoll_poll_unlock(have_poll_lock);
6093 __busy_poll_stop(napi, skip_schedule);
6097 void napi_busy_loop(unsigned int napi_id,
6098 bool (*loop_end)(void *, unsigned long),
6099 void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6101 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6102 int (*napi_poll)(struct napi_struct *napi, int budget);
6103 void *have_poll_lock = NULL;
6104 struct napi_struct *napi;
6111 napi = napi_by_id(napi_id);
6121 unsigned long val = READ_ONCE(napi->state);
6123 /* If multiple threads are competing for this napi,
6124 * we avoid dirtying napi->state as much as we can.
6126 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6127 NAPIF_STATE_IN_BUSY_POLL)) {
6128 if (prefer_busy_poll)
6129 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6132 if (cmpxchg(&napi->state, val,
6133 val | NAPIF_STATE_IN_BUSY_POLL |
6134 NAPIF_STATE_SCHED) != val) {
6135 if (prefer_busy_poll)
6136 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6139 have_poll_lock = netpoll_poll_lock(napi);
6140 napi_poll = napi->poll;
6142 work = napi_poll(napi, budget);
6143 trace_napi_poll(napi, work, budget);
6144 gro_normal_list(napi);
6147 __NET_ADD_STATS(dev_net(napi->dev),
6148 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6151 if (!loop_end || loop_end(loop_end_arg, start_time))
6154 if (unlikely(need_resched())) {
6156 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6160 if (loop_end(loop_end_arg, start_time))
6167 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6172 EXPORT_SYMBOL(napi_busy_loop);
6174 #endif /* CONFIG_NET_RX_BUSY_POLL */
6176 static void napi_hash_add(struct napi_struct *napi)
6178 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6181 spin_lock(&napi_hash_lock);
6183 /* 0..NR_CPUS range is reserved for sender_cpu use */
6185 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6186 napi_gen_id = MIN_NAPI_ID;
6187 } while (napi_by_id(napi_gen_id));
6188 napi->napi_id = napi_gen_id;
6190 hlist_add_head_rcu(&napi->napi_hash_node,
6191 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6193 spin_unlock(&napi_hash_lock);
6196 /* Warning : caller is responsible to make sure rcu grace period
6197 * is respected before freeing memory containing @napi
6199 static void napi_hash_del(struct napi_struct *napi)
6201 spin_lock(&napi_hash_lock);
6203 hlist_del_init_rcu(&napi->napi_hash_node);
6205 spin_unlock(&napi_hash_lock);
6208 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6210 struct napi_struct *napi;
6212 napi = container_of(timer, struct napi_struct, timer);
6214 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6215 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6217 if (!napi_disable_pending(napi) &&
6218 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
6219 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6220 __napi_schedule_irqoff(napi);
6223 return HRTIMER_NORESTART;
6226 static void init_gro_hash(struct napi_struct *napi)
6230 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6231 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6232 napi->gro_hash[i].count = 0;
6234 napi->gro_bitmask = 0;
6237 int dev_set_threaded(struct net_device *dev, bool threaded)
6239 struct napi_struct *napi;
6242 if (dev->threaded == threaded)
6246 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6247 if (!napi->thread) {
6248 err = napi_kthread_create(napi);
6257 dev->threaded = threaded;
6259 /* Make sure kthread is created before THREADED bit
6262 smp_mb__before_atomic();
6264 /* Setting/unsetting threaded mode on a napi might not immediately
6265 * take effect, if the current napi instance is actively being
6266 * polled. In this case, the switch between threaded mode and
6267 * softirq mode will happen in the next round of napi_schedule().
6268 * This should not cause hiccups/stalls to the live traffic.
6270 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6272 set_bit(NAPI_STATE_THREADED, &napi->state);
6274 clear_bit(NAPI_STATE_THREADED, &napi->state);
6279 EXPORT_SYMBOL(dev_set_threaded);
6281 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
6282 int (*poll)(struct napi_struct *, int), int weight)
6284 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6287 INIT_LIST_HEAD(&napi->poll_list);
6288 INIT_HLIST_NODE(&napi->napi_hash_node);
6289 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6290 napi->timer.function = napi_watchdog;
6291 init_gro_hash(napi);
6293 INIT_LIST_HEAD(&napi->rx_list);
6296 if (weight > NAPI_POLL_WEIGHT)
6297 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6299 napi->weight = weight;
6301 #ifdef CONFIG_NETPOLL
6302 napi->poll_owner = -1;
6304 set_bit(NAPI_STATE_SCHED, &napi->state);
6305 set_bit(NAPI_STATE_NPSVC, &napi->state);
6306 list_add_rcu(&napi->dev_list, &dev->napi_list);
6307 napi_hash_add(napi);
6308 /* Create kthread for this napi if dev->threaded is set.
6309 * Clear dev->threaded if kthread creation failed so that
6310 * threaded mode will not be enabled in napi_enable().
6312 if (dev->threaded && napi_kthread_create(napi))
6315 EXPORT_SYMBOL(netif_napi_add);
6317 void napi_disable(struct napi_struct *n)
6319 unsigned long val, new;
6322 set_bit(NAPI_STATE_DISABLE, &n->state);
6325 val = READ_ONCE(n->state);
6326 if (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
6327 usleep_range(20, 200);
6331 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
6332 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
6334 if (cmpxchg(&n->state, val, new) == val)
6338 hrtimer_cancel(&n->timer);
6340 clear_bit(NAPI_STATE_DISABLE, &n->state);
6342 EXPORT_SYMBOL(napi_disable);
6345 * napi_enable - enable NAPI scheduling
6348 * Resume NAPI from being scheduled on this context.
6349 * Must be paired with napi_disable.
6351 void napi_enable(struct napi_struct *n)
6353 unsigned long val, new;
6356 val = READ_ONCE(n->state);
6357 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
6359 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
6360 if (n->dev->threaded && n->thread)
6361 new |= NAPIF_STATE_THREADED;
6362 } while (cmpxchg(&n->state, val, new) != val);
6364 EXPORT_SYMBOL(napi_enable);
6366 static void flush_gro_hash(struct napi_struct *napi)
6370 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6371 struct sk_buff *skb, *n;
6373 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6375 napi->gro_hash[i].count = 0;
6379 /* Must be called in process context */
6380 void __netif_napi_del(struct napi_struct *napi)
6382 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6385 napi_hash_del(napi);
6386 list_del_rcu(&napi->dev_list);
6387 napi_free_frags(napi);
6389 flush_gro_hash(napi);
6390 napi->gro_bitmask = 0;
6393 kthread_stop(napi->thread);
6394 napi->thread = NULL;
6397 EXPORT_SYMBOL(__netif_napi_del);
6399 static int __napi_poll(struct napi_struct *n, bool *repoll)
6405 /* This NAPI_STATE_SCHED test is for avoiding a race
6406 * with netpoll's poll_napi(). Only the entity which
6407 * obtains the lock and sees NAPI_STATE_SCHED set will
6408 * actually make the ->poll() call. Therefore we avoid
6409 * accidentally calling ->poll() when NAPI is not scheduled.
6412 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6413 work = n->poll(n, weight);
6414 trace_napi_poll(n, work, weight);
6417 if (unlikely(work > weight))
6418 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6419 n->poll, work, weight);
6421 if (likely(work < weight))
6424 /* Drivers must not modify the NAPI state if they
6425 * consume the entire weight. In such cases this code
6426 * still "owns" the NAPI instance and therefore can
6427 * move the instance around on the list at-will.
6429 if (unlikely(napi_disable_pending(n))) {
6434 /* The NAPI context has more processing work, but busy-polling
6435 * is preferred. Exit early.
6437 if (napi_prefer_busy_poll(n)) {
6438 if (napi_complete_done(n, work)) {
6439 /* If timeout is not set, we need to make sure
6440 * that the NAPI is re-scheduled.
6447 if (n->gro_bitmask) {
6448 /* flush too old packets
6449 * If HZ < 1000, flush all packets.
6451 napi_gro_flush(n, HZ >= 1000);
6456 /* Some drivers may have called napi_schedule
6457 * prior to exhausting their budget.
6459 if (unlikely(!list_empty(&n->poll_list))) {
6460 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6461 n->dev ? n->dev->name : "backlog");
6470 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6472 bool do_repoll = false;
6476 list_del_init(&n->poll_list);
6478 have = netpoll_poll_lock(n);
6480 work = __napi_poll(n, &do_repoll);
6483 list_add_tail(&n->poll_list, repoll);
6485 netpoll_poll_unlock(have);
6490 static int napi_thread_wait(struct napi_struct *napi)
6494 set_current_state(TASK_INTERRUPTIBLE);
6496 while (!kthread_should_stop()) {
6497 /* Testing SCHED_THREADED bit here to make sure the current
6498 * kthread owns this napi and could poll on this napi.
6499 * Testing SCHED bit is not enough because SCHED bit might be
6500 * set by some other busy poll thread or by napi_disable().
6502 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state) || woken) {
6503 WARN_ON(!list_empty(&napi->poll_list));
6504 __set_current_state(TASK_RUNNING);
6509 /* woken being true indicates this thread owns this napi. */
6511 set_current_state(TASK_INTERRUPTIBLE);
6513 __set_current_state(TASK_RUNNING);
6518 static int napi_threaded_poll(void *data)
6520 struct napi_struct *napi = data;
6523 while (!napi_thread_wait(napi)) {
6525 bool repoll = false;
6529 have = netpoll_poll_lock(napi);
6530 __napi_poll(napi, &repoll);
6531 netpoll_poll_unlock(have);
6544 static __latent_entropy void net_rx_action(struct softirq_action *h)
6546 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6547 unsigned long time_limit = jiffies +
6548 usecs_to_jiffies(netdev_budget_usecs);
6549 int budget = netdev_budget;
6553 local_irq_disable();
6554 list_splice_init(&sd->poll_list, &list);
6558 struct napi_struct *n;
6560 if (list_empty(&list)) {
6561 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
6566 n = list_first_entry(&list, struct napi_struct, poll_list);
6567 budget -= napi_poll(n, &repoll);
6569 /* If softirq window is exhausted then punt.
6570 * Allow this to run for 2 jiffies since which will allow
6571 * an average latency of 1.5/HZ.
6573 if (unlikely(budget <= 0 ||
6574 time_after_eq(jiffies, time_limit))) {
6580 local_irq_disable();
6582 list_splice_tail_init(&sd->poll_list, &list);
6583 list_splice_tail(&repoll, &list);
6584 list_splice(&list, &sd->poll_list);
6585 if (!list_empty(&sd->poll_list))
6586 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6588 net_rps_action_and_irq_enable(sd);
6591 struct netdev_adjacent {
6592 struct net_device *dev;
6593 netdevice_tracker dev_tracker;
6595 /* upper master flag, there can only be one master device per list */
6598 /* lookup ignore flag */
6601 /* counter for the number of times this device was added to us */
6604 /* private field for the users */
6607 struct list_head list;
6608 struct rcu_head rcu;
6611 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6612 struct list_head *adj_list)
6614 struct netdev_adjacent *adj;
6616 list_for_each_entry(adj, adj_list, list) {
6617 if (adj->dev == adj_dev)
6623 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6624 struct netdev_nested_priv *priv)
6626 struct net_device *dev = (struct net_device *)priv->data;
6628 return upper_dev == dev;
6632 * netdev_has_upper_dev - Check if device is linked to an upper device
6634 * @upper_dev: upper device to check
6636 * Find out if a device is linked to specified upper device and return true
6637 * in case it is. Note that this checks only immediate upper device,
6638 * not through a complete stack of devices. The caller must hold the RTNL lock.
6640 bool netdev_has_upper_dev(struct net_device *dev,
6641 struct net_device *upper_dev)
6643 struct netdev_nested_priv priv = {
6644 .data = (void *)upper_dev,
6649 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6652 EXPORT_SYMBOL(netdev_has_upper_dev);
6655 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
6657 * @upper_dev: upper device to check
6659 * Find out if a device is linked to specified upper device and return true
6660 * in case it is. Note that this checks the entire upper device chain.
6661 * The caller must hold rcu lock.
6664 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6665 struct net_device *upper_dev)
6667 struct netdev_nested_priv priv = {
6668 .data = (void *)upper_dev,
6671 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6674 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6677 * netdev_has_any_upper_dev - Check if device is linked to some device
6680 * Find out if a device is linked to an upper device and return true in case
6681 * it is. The caller must hold the RTNL lock.
6683 bool netdev_has_any_upper_dev(struct net_device *dev)
6687 return !list_empty(&dev->adj_list.upper);
6689 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6692 * netdev_master_upper_dev_get - Get master upper device
6695 * Find a master upper device and return pointer to it or NULL in case
6696 * it's not there. The caller must hold the RTNL lock.
6698 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6700 struct netdev_adjacent *upper;
6704 if (list_empty(&dev->adj_list.upper))
6707 upper = list_first_entry(&dev->adj_list.upper,
6708 struct netdev_adjacent, list);
6709 if (likely(upper->master))
6713 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6715 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
6717 struct netdev_adjacent *upper;
6721 if (list_empty(&dev->adj_list.upper))
6724 upper = list_first_entry(&dev->adj_list.upper,
6725 struct netdev_adjacent, list);
6726 if (likely(upper->master) && !upper->ignore)
6732 * netdev_has_any_lower_dev - Check if device is linked to some device
6735 * Find out if a device is linked to a lower device and return true in case
6736 * it is. The caller must hold the RTNL lock.
6738 static bool netdev_has_any_lower_dev(struct net_device *dev)
6742 return !list_empty(&dev->adj_list.lower);
6745 void *netdev_adjacent_get_private(struct list_head *adj_list)
6747 struct netdev_adjacent *adj;
6749 adj = list_entry(adj_list, struct netdev_adjacent, list);
6751 return adj->private;
6753 EXPORT_SYMBOL(netdev_adjacent_get_private);
6756 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
6758 * @iter: list_head ** of the current position
6760 * Gets the next device from the dev's upper list, starting from iter
6761 * position. The caller must hold RCU read lock.
6763 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
6764 struct list_head **iter)
6766 struct netdev_adjacent *upper;
6768 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6770 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6772 if (&upper->list == &dev->adj_list.upper)
6775 *iter = &upper->list;
6779 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
6781 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
6782 struct list_head **iter,
6785 struct netdev_adjacent *upper;
6787 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
6789 if (&upper->list == &dev->adj_list.upper)
6792 *iter = &upper->list;
6793 *ignore = upper->ignore;
6798 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
6799 struct list_head **iter)
6801 struct netdev_adjacent *upper;
6803 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6805 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6807 if (&upper->list == &dev->adj_list.upper)
6810 *iter = &upper->list;
6815 static int __netdev_walk_all_upper_dev(struct net_device *dev,
6816 int (*fn)(struct net_device *dev,
6817 struct netdev_nested_priv *priv),
6818 struct netdev_nested_priv *priv)
6820 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6821 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6826 iter = &dev->adj_list.upper;
6830 ret = fn(now, priv);
6837 udev = __netdev_next_upper_dev(now, &iter, &ignore);
6844 niter = &udev->adj_list.upper;
6845 dev_stack[cur] = now;
6846 iter_stack[cur++] = iter;
6853 next = dev_stack[--cur];
6854 niter = iter_stack[cur];
6864 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
6865 int (*fn)(struct net_device *dev,
6866 struct netdev_nested_priv *priv),
6867 struct netdev_nested_priv *priv)
6869 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6870 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6874 iter = &dev->adj_list.upper;
6878 ret = fn(now, priv);
6885 udev = netdev_next_upper_dev_rcu(now, &iter);
6890 niter = &udev->adj_list.upper;
6891 dev_stack[cur] = now;
6892 iter_stack[cur++] = iter;
6899 next = dev_stack[--cur];
6900 niter = iter_stack[cur];
6909 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
6911 static bool __netdev_has_upper_dev(struct net_device *dev,
6912 struct net_device *upper_dev)
6914 struct netdev_nested_priv priv = {
6916 .data = (void *)upper_dev,
6921 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
6926 * netdev_lower_get_next_private - Get the next ->private from the
6927 * lower neighbour list
6929 * @iter: list_head ** of the current position
6931 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6932 * list, starting from iter position. The caller must hold either hold the
6933 * RTNL lock or its own locking that guarantees that the neighbour lower
6934 * list will remain unchanged.
6936 void *netdev_lower_get_next_private(struct net_device *dev,
6937 struct list_head **iter)
6939 struct netdev_adjacent *lower;
6941 lower = list_entry(*iter, struct netdev_adjacent, list);
6943 if (&lower->list == &dev->adj_list.lower)
6946 *iter = lower->list.next;
6948 return lower->private;
6950 EXPORT_SYMBOL(netdev_lower_get_next_private);
6953 * netdev_lower_get_next_private_rcu - Get the next ->private from the
6954 * lower neighbour list, RCU
6957 * @iter: list_head ** of the current position
6959 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6960 * list, starting from iter position. The caller must hold RCU read lock.
6962 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
6963 struct list_head **iter)
6965 struct netdev_adjacent *lower;
6967 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
6969 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6971 if (&lower->list == &dev->adj_list.lower)
6974 *iter = &lower->list;
6976 return lower->private;
6978 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
6981 * netdev_lower_get_next - Get the next device from the lower neighbour
6984 * @iter: list_head ** of the current position
6986 * Gets the next netdev_adjacent from the dev's lower neighbour
6987 * list, starting from iter position. The caller must hold RTNL lock or
6988 * its own locking that guarantees that the neighbour lower
6989 * list will remain unchanged.
6991 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
6993 struct netdev_adjacent *lower;
6995 lower = list_entry(*iter, struct netdev_adjacent, list);
6997 if (&lower->list == &dev->adj_list.lower)
7000 *iter = lower->list.next;
7004 EXPORT_SYMBOL(netdev_lower_get_next);
7006 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7007 struct list_head **iter)
7009 struct netdev_adjacent *lower;
7011 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7013 if (&lower->list == &dev->adj_list.lower)
7016 *iter = &lower->list;
7021 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7022 struct list_head **iter,
7025 struct netdev_adjacent *lower;
7027 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7029 if (&lower->list == &dev->adj_list.lower)
7032 *iter = &lower->list;
7033 *ignore = lower->ignore;
7038 int netdev_walk_all_lower_dev(struct net_device *dev,
7039 int (*fn)(struct net_device *dev,
7040 struct netdev_nested_priv *priv),
7041 struct netdev_nested_priv *priv)
7043 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7044 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7048 iter = &dev->adj_list.lower;
7052 ret = fn(now, priv);
7059 ldev = netdev_next_lower_dev(now, &iter);
7064 niter = &ldev->adj_list.lower;
7065 dev_stack[cur] = now;
7066 iter_stack[cur++] = iter;
7073 next = dev_stack[--cur];
7074 niter = iter_stack[cur];
7083 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7085 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7086 int (*fn)(struct net_device *dev,
7087 struct netdev_nested_priv *priv),
7088 struct netdev_nested_priv *priv)
7090 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7091 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7096 iter = &dev->adj_list.lower;
7100 ret = fn(now, priv);
7107 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7114 niter = &ldev->adj_list.lower;
7115 dev_stack[cur] = now;
7116 iter_stack[cur++] = iter;
7123 next = dev_stack[--cur];
7124 niter = iter_stack[cur];
7134 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7135 struct list_head **iter)
7137 struct netdev_adjacent *lower;
7139 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7140 if (&lower->list == &dev->adj_list.lower)
7143 *iter = &lower->list;
7147 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7149 static u8 __netdev_upper_depth(struct net_device *dev)
7151 struct net_device *udev;
7152 struct list_head *iter;
7156 for (iter = &dev->adj_list.upper,
7157 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7159 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7162 if (max_depth < udev->upper_level)
7163 max_depth = udev->upper_level;
7169 static u8 __netdev_lower_depth(struct net_device *dev)
7171 struct net_device *ldev;
7172 struct list_head *iter;
7176 for (iter = &dev->adj_list.lower,
7177 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7179 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7182 if (max_depth < ldev->lower_level)
7183 max_depth = ldev->lower_level;
7189 static int __netdev_update_upper_level(struct net_device *dev,
7190 struct netdev_nested_priv *__unused)
7192 dev->upper_level = __netdev_upper_depth(dev) + 1;
7196 #ifdef CONFIG_LOCKDEP
7197 static LIST_HEAD(net_unlink_list);
7199 static void net_unlink_todo(struct net_device *dev)
7201 if (list_empty(&dev->unlink_list))
7202 list_add_tail(&dev->unlink_list, &net_unlink_list);
7206 static int __netdev_update_lower_level(struct net_device *dev,
7207 struct netdev_nested_priv *priv)
7209 dev->lower_level = __netdev_lower_depth(dev) + 1;
7211 #ifdef CONFIG_LOCKDEP
7215 if (priv->flags & NESTED_SYNC_IMM)
7216 dev->nested_level = dev->lower_level - 1;
7217 if (priv->flags & NESTED_SYNC_TODO)
7218 net_unlink_todo(dev);
7223 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7224 int (*fn)(struct net_device *dev,
7225 struct netdev_nested_priv *priv),
7226 struct netdev_nested_priv *priv)
7228 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7229 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7233 iter = &dev->adj_list.lower;
7237 ret = fn(now, priv);
7244 ldev = netdev_next_lower_dev_rcu(now, &iter);
7249 niter = &ldev->adj_list.lower;
7250 dev_stack[cur] = now;
7251 iter_stack[cur++] = iter;
7258 next = dev_stack[--cur];
7259 niter = iter_stack[cur];
7268 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7271 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7272 * lower neighbour list, RCU
7276 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7277 * list. The caller must hold RCU read lock.
7279 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7281 struct netdev_adjacent *lower;
7283 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7284 struct netdev_adjacent, list);
7286 return lower->private;
7289 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7292 * netdev_master_upper_dev_get_rcu - Get master upper device
7295 * Find a master upper device and return pointer to it or NULL in case
7296 * it's not there. The caller must hold the RCU read lock.
7298 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7300 struct netdev_adjacent *upper;
7302 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7303 struct netdev_adjacent, list);
7304 if (upper && likely(upper->master))
7308 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7310 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7311 struct net_device *adj_dev,
7312 struct list_head *dev_list)
7314 char linkname[IFNAMSIZ+7];
7316 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7317 "upper_%s" : "lower_%s", adj_dev->name);
7318 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7321 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7323 struct list_head *dev_list)
7325 char linkname[IFNAMSIZ+7];
7327 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7328 "upper_%s" : "lower_%s", name);
7329 sysfs_remove_link(&(dev->dev.kobj), linkname);
7332 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7333 struct net_device *adj_dev,
7334 struct list_head *dev_list)
7336 return (dev_list == &dev->adj_list.upper ||
7337 dev_list == &dev->adj_list.lower) &&
7338 net_eq(dev_net(dev), dev_net(adj_dev));
7341 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7342 struct net_device *adj_dev,
7343 struct list_head *dev_list,
7344 void *private, bool master)
7346 struct netdev_adjacent *adj;
7349 adj = __netdev_find_adj(adj_dev, dev_list);
7353 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7354 dev->name, adj_dev->name, adj->ref_nr);
7359 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7364 adj->master = master;
7366 adj->private = private;
7367 adj->ignore = false;
7368 dev_hold_track(adj_dev, &adj->dev_tracker, GFP_KERNEL);
7370 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7371 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7373 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7374 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7379 /* Ensure that master link is always the first item in list. */
7381 ret = sysfs_create_link(&(dev->dev.kobj),
7382 &(adj_dev->dev.kobj), "master");
7384 goto remove_symlinks;
7386 list_add_rcu(&adj->list, dev_list);
7388 list_add_tail_rcu(&adj->list, dev_list);
7394 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7395 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7397 dev_put_track(adj_dev, &adj->dev_tracker);
7403 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7404 struct net_device *adj_dev,
7406 struct list_head *dev_list)
7408 struct netdev_adjacent *adj;
7410 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7411 dev->name, adj_dev->name, ref_nr);
7413 adj = __netdev_find_adj(adj_dev, dev_list);
7416 pr_err("Adjacency does not exist for device %s from %s\n",
7417 dev->name, adj_dev->name);
7422 if (adj->ref_nr > ref_nr) {
7423 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7424 dev->name, adj_dev->name, ref_nr,
7425 adj->ref_nr - ref_nr);
7426 adj->ref_nr -= ref_nr;
7431 sysfs_remove_link(&(dev->dev.kobj), "master");
7433 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7434 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7436 list_del_rcu(&adj->list);
7437 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7438 adj_dev->name, dev->name, adj_dev->name);
7439 dev_put_track(adj_dev, &adj->dev_tracker);
7440 kfree_rcu(adj, rcu);
7443 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7444 struct net_device *upper_dev,
7445 struct list_head *up_list,
7446 struct list_head *down_list,
7447 void *private, bool master)
7451 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7456 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7459 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7466 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7467 struct net_device *upper_dev,
7469 struct list_head *up_list,
7470 struct list_head *down_list)
7472 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7473 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7476 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7477 struct net_device *upper_dev,
7478 void *private, bool master)
7480 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7481 &dev->adj_list.upper,
7482 &upper_dev->adj_list.lower,
7486 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7487 struct net_device *upper_dev)
7489 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7490 &dev->adj_list.upper,
7491 &upper_dev->adj_list.lower);
7494 static int __netdev_upper_dev_link(struct net_device *dev,
7495 struct net_device *upper_dev, bool master,
7496 void *upper_priv, void *upper_info,
7497 struct netdev_nested_priv *priv,
7498 struct netlink_ext_ack *extack)
7500 struct netdev_notifier_changeupper_info changeupper_info = {
7505 .upper_dev = upper_dev,
7508 .upper_info = upper_info,
7510 struct net_device *master_dev;
7515 if (dev == upper_dev)
7518 /* To prevent loops, check if dev is not upper device to upper_dev. */
7519 if (__netdev_has_upper_dev(upper_dev, dev))
7522 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7526 if (__netdev_has_upper_dev(dev, upper_dev))
7529 master_dev = __netdev_master_upper_dev_get(dev);
7531 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7534 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7535 &changeupper_info.info);
7536 ret = notifier_to_errno(ret);
7540 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7545 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7546 &changeupper_info.info);
7547 ret = notifier_to_errno(ret);
7551 __netdev_update_upper_level(dev, NULL);
7552 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7554 __netdev_update_lower_level(upper_dev, priv);
7555 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7561 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7567 * netdev_upper_dev_link - Add a link to the upper device
7569 * @upper_dev: new upper device
7570 * @extack: netlink extended ack
7572 * Adds a link to device which is upper to this one. The caller must hold
7573 * the RTNL lock. On a failure a negative errno code is returned.
7574 * On success the reference counts are adjusted and the function
7577 int netdev_upper_dev_link(struct net_device *dev,
7578 struct net_device *upper_dev,
7579 struct netlink_ext_ack *extack)
7581 struct netdev_nested_priv priv = {
7582 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7586 return __netdev_upper_dev_link(dev, upper_dev, false,
7587 NULL, NULL, &priv, extack);
7589 EXPORT_SYMBOL(netdev_upper_dev_link);
7592 * netdev_master_upper_dev_link - Add a master link to the upper device
7594 * @upper_dev: new upper device
7595 * @upper_priv: upper device private
7596 * @upper_info: upper info to be passed down via notifier
7597 * @extack: netlink extended ack
7599 * Adds a link to device which is upper to this one. In this case, only
7600 * one master upper device can be linked, although other non-master devices
7601 * might be linked as well. The caller must hold the RTNL lock.
7602 * On a failure a negative errno code is returned. On success the reference
7603 * counts are adjusted and the function returns zero.
7605 int netdev_master_upper_dev_link(struct net_device *dev,
7606 struct net_device *upper_dev,
7607 void *upper_priv, void *upper_info,
7608 struct netlink_ext_ack *extack)
7610 struct netdev_nested_priv priv = {
7611 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7615 return __netdev_upper_dev_link(dev, upper_dev, true,
7616 upper_priv, upper_info, &priv, extack);
7618 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7620 static void __netdev_upper_dev_unlink(struct net_device *dev,
7621 struct net_device *upper_dev,
7622 struct netdev_nested_priv *priv)
7624 struct netdev_notifier_changeupper_info changeupper_info = {
7628 .upper_dev = upper_dev,
7634 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7636 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7637 &changeupper_info.info);
7639 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7641 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7642 &changeupper_info.info);
7644 __netdev_update_upper_level(dev, NULL);
7645 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7647 __netdev_update_lower_level(upper_dev, priv);
7648 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7653 * netdev_upper_dev_unlink - Removes a link to upper device
7655 * @upper_dev: new upper device
7657 * Removes a link to device which is upper to this one. The caller must hold
7660 void netdev_upper_dev_unlink(struct net_device *dev,
7661 struct net_device *upper_dev)
7663 struct netdev_nested_priv priv = {
7664 .flags = NESTED_SYNC_TODO,
7668 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
7670 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7672 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7673 struct net_device *lower_dev,
7676 struct netdev_adjacent *adj;
7678 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
7682 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
7687 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
7688 struct net_device *lower_dev)
7690 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
7693 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
7694 struct net_device *lower_dev)
7696 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
7699 int netdev_adjacent_change_prepare(struct net_device *old_dev,
7700 struct net_device *new_dev,
7701 struct net_device *dev,
7702 struct netlink_ext_ack *extack)
7704 struct netdev_nested_priv priv = {
7713 if (old_dev && new_dev != old_dev)
7714 netdev_adjacent_dev_disable(dev, old_dev);
7715 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
7718 if (old_dev && new_dev != old_dev)
7719 netdev_adjacent_dev_enable(dev, old_dev);
7725 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
7727 void netdev_adjacent_change_commit(struct net_device *old_dev,
7728 struct net_device *new_dev,
7729 struct net_device *dev)
7731 struct netdev_nested_priv priv = {
7732 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7736 if (!new_dev || !old_dev)
7739 if (new_dev == old_dev)
7742 netdev_adjacent_dev_enable(dev, old_dev);
7743 __netdev_upper_dev_unlink(old_dev, dev, &priv);
7745 EXPORT_SYMBOL(netdev_adjacent_change_commit);
7747 void netdev_adjacent_change_abort(struct net_device *old_dev,
7748 struct net_device *new_dev,
7749 struct net_device *dev)
7751 struct netdev_nested_priv priv = {
7759 if (old_dev && new_dev != old_dev)
7760 netdev_adjacent_dev_enable(dev, old_dev);
7762 __netdev_upper_dev_unlink(new_dev, dev, &priv);
7764 EXPORT_SYMBOL(netdev_adjacent_change_abort);
7767 * netdev_bonding_info_change - Dispatch event about slave change
7769 * @bonding_info: info to dispatch
7771 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
7772 * The caller must hold the RTNL lock.
7774 void netdev_bonding_info_change(struct net_device *dev,
7775 struct netdev_bonding_info *bonding_info)
7777 struct netdev_notifier_bonding_info info = {
7781 memcpy(&info.bonding_info, bonding_info,
7782 sizeof(struct netdev_bonding_info));
7783 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
7786 EXPORT_SYMBOL(netdev_bonding_info_change);
7788 static int netdev_offload_xstats_enable_l3(struct net_device *dev,
7789 struct netlink_ext_ack *extack)
7791 struct netdev_notifier_offload_xstats_info info = {
7793 .info.extack = extack,
7794 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
7799 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
7801 if (!dev->offload_xstats_l3)
7804 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
7805 NETDEV_OFFLOAD_XSTATS_DISABLE,
7807 err = notifier_to_errno(rc);
7814 kfree(dev->offload_xstats_l3);
7815 dev->offload_xstats_l3 = NULL;
7819 int netdev_offload_xstats_enable(struct net_device *dev,
7820 enum netdev_offload_xstats_type type,
7821 struct netlink_ext_ack *extack)
7825 if (netdev_offload_xstats_enabled(dev, type))
7829 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
7830 return netdev_offload_xstats_enable_l3(dev, extack);
7836 EXPORT_SYMBOL(netdev_offload_xstats_enable);
7838 static void netdev_offload_xstats_disable_l3(struct net_device *dev)
7840 struct netdev_notifier_offload_xstats_info info = {
7842 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
7845 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
7847 kfree(dev->offload_xstats_l3);
7848 dev->offload_xstats_l3 = NULL;
7851 int netdev_offload_xstats_disable(struct net_device *dev,
7852 enum netdev_offload_xstats_type type)
7856 if (!netdev_offload_xstats_enabled(dev, type))
7860 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
7861 netdev_offload_xstats_disable_l3(dev);
7868 EXPORT_SYMBOL(netdev_offload_xstats_disable);
7870 static void netdev_offload_xstats_disable_all(struct net_device *dev)
7872 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
7875 static struct rtnl_hw_stats64 *
7876 netdev_offload_xstats_get_ptr(const struct net_device *dev,
7877 enum netdev_offload_xstats_type type)
7880 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
7881 return dev->offload_xstats_l3;
7888 bool netdev_offload_xstats_enabled(const struct net_device *dev,
7889 enum netdev_offload_xstats_type type)
7893 return netdev_offload_xstats_get_ptr(dev, type);
7895 EXPORT_SYMBOL(netdev_offload_xstats_enabled);
7897 struct netdev_notifier_offload_xstats_ru {
7901 struct netdev_notifier_offload_xstats_rd {
7902 struct rtnl_hw_stats64 stats;
7906 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
7907 const struct rtnl_hw_stats64 *src)
7909 dest->rx_packets += src->rx_packets;
7910 dest->tx_packets += src->tx_packets;
7911 dest->rx_bytes += src->rx_bytes;
7912 dest->tx_bytes += src->tx_bytes;
7913 dest->rx_errors += src->rx_errors;
7914 dest->tx_errors += src->tx_errors;
7915 dest->rx_dropped += src->rx_dropped;
7916 dest->tx_dropped += src->tx_dropped;
7917 dest->multicast += src->multicast;
7920 static int netdev_offload_xstats_get_used(struct net_device *dev,
7921 enum netdev_offload_xstats_type type,
7923 struct netlink_ext_ack *extack)
7925 struct netdev_notifier_offload_xstats_ru report_used = {};
7926 struct netdev_notifier_offload_xstats_info info = {
7928 .info.extack = extack,
7930 .report_used = &report_used,
7934 WARN_ON(!netdev_offload_xstats_enabled(dev, type));
7935 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
7937 *p_used = report_used.used;
7938 return notifier_to_errno(rc);
7941 static int netdev_offload_xstats_get_stats(struct net_device *dev,
7942 enum netdev_offload_xstats_type type,
7943 struct rtnl_hw_stats64 *p_stats,
7945 struct netlink_ext_ack *extack)
7947 struct netdev_notifier_offload_xstats_rd report_delta = {};
7948 struct netdev_notifier_offload_xstats_info info = {
7950 .info.extack = extack,
7952 .report_delta = &report_delta,
7954 struct rtnl_hw_stats64 *stats;
7957 stats = netdev_offload_xstats_get_ptr(dev, type);
7958 if (WARN_ON(!stats))
7961 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
7964 /* Cache whatever we got, even if there was an error, otherwise the
7965 * successful stats retrievals would get lost.
7967 netdev_hw_stats64_add(stats, &report_delta.stats);
7971 *p_used = report_delta.used;
7973 return notifier_to_errno(rc);
7976 int netdev_offload_xstats_get(struct net_device *dev,
7977 enum netdev_offload_xstats_type type,
7978 struct rtnl_hw_stats64 *p_stats, bool *p_used,
7979 struct netlink_ext_ack *extack)
7984 return netdev_offload_xstats_get_stats(dev, type, p_stats,
7987 return netdev_offload_xstats_get_used(dev, type, p_used,
7990 EXPORT_SYMBOL(netdev_offload_xstats_get);
7993 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
7994 const struct rtnl_hw_stats64 *stats)
7996 report_delta->used = true;
7997 netdev_hw_stats64_add(&report_delta->stats, stats);
7999 EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
8002 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
8004 report_used->used = true;
8006 EXPORT_SYMBOL(netdev_offload_xstats_report_used);
8008 void netdev_offload_xstats_push_delta(struct net_device *dev,
8009 enum netdev_offload_xstats_type type,
8010 const struct rtnl_hw_stats64 *p_stats)
8012 struct rtnl_hw_stats64 *stats;
8016 stats = netdev_offload_xstats_get_ptr(dev, type);
8017 if (WARN_ON(!stats))
8020 netdev_hw_stats64_add(stats, p_stats);
8022 EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
8025 * netdev_get_xmit_slave - Get the xmit slave of master device
8028 * @all_slaves: assume all the slaves are active
8030 * The reference counters are not incremented so the caller must be
8031 * careful with locks. The caller must hold RCU lock.
8032 * %NULL is returned if no slave is found.
8035 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8036 struct sk_buff *skb,
8039 const struct net_device_ops *ops = dev->netdev_ops;
8041 if (!ops->ndo_get_xmit_slave)
8043 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8045 EXPORT_SYMBOL(netdev_get_xmit_slave);
8047 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
8050 const struct net_device_ops *ops = dev->netdev_ops;
8052 if (!ops->ndo_sk_get_lower_dev)
8054 return ops->ndo_sk_get_lower_dev(dev, sk);
8058 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
8062 * %NULL is returned if no lower device is found.
8065 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
8068 struct net_device *lower;
8070 lower = netdev_sk_get_lower_dev(dev, sk);
8073 lower = netdev_sk_get_lower_dev(dev, sk);
8078 EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
8080 static void netdev_adjacent_add_links(struct net_device *dev)
8082 struct netdev_adjacent *iter;
8084 struct net *net = dev_net(dev);
8086 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8087 if (!net_eq(net, dev_net(iter->dev)))
8089 netdev_adjacent_sysfs_add(iter->dev, dev,
8090 &iter->dev->adj_list.lower);
8091 netdev_adjacent_sysfs_add(dev, iter->dev,
8092 &dev->adj_list.upper);
8095 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8096 if (!net_eq(net, dev_net(iter->dev)))
8098 netdev_adjacent_sysfs_add(iter->dev, dev,
8099 &iter->dev->adj_list.upper);
8100 netdev_adjacent_sysfs_add(dev, iter->dev,
8101 &dev->adj_list.lower);
8105 static void netdev_adjacent_del_links(struct net_device *dev)
8107 struct netdev_adjacent *iter;
8109 struct net *net = dev_net(dev);
8111 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8112 if (!net_eq(net, dev_net(iter->dev)))
8114 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8115 &iter->dev->adj_list.lower);
8116 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8117 &dev->adj_list.upper);
8120 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8121 if (!net_eq(net, dev_net(iter->dev)))
8123 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8124 &iter->dev->adj_list.upper);
8125 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8126 &dev->adj_list.lower);
8130 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8132 struct netdev_adjacent *iter;
8134 struct net *net = dev_net(dev);
8136 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8137 if (!net_eq(net, dev_net(iter->dev)))
8139 netdev_adjacent_sysfs_del(iter->dev, oldname,
8140 &iter->dev->adj_list.lower);
8141 netdev_adjacent_sysfs_add(iter->dev, dev,
8142 &iter->dev->adj_list.lower);
8145 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8146 if (!net_eq(net, dev_net(iter->dev)))
8148 netdev_adjacent_sysfs_del(iter->dev, oldname,
8149 &iter->dev->adj_list.upper);
8150 netdev_adjacent_sysfs_add(iter->dev, dev,
8151 &iter->dev->adj_list.upper);
8155 void *netdev_lower_dev_get_private(struct net_device *dev,
8156 struct net_device *lower_dev)
8158 struct netdev_adjacent *lower;
8162 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8166 return lower->private;
8168 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8172 * netdev_lower_state_changed - Dispatch event about lower device state change
8173 * @lower_dev: device
8174 * @lower_state_info: state to dispatch
8176 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8177 * The caller must hold the RTNL lock.
8179 void netdev_lower_state_changed(struct net_device *lower_dev,
8180 void *lower_state_info)
8182 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8183 .info.dev = lower_dev,
8187 changelowerstate_info.lower_state_info = lower_state_info;
8188 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8189 &changelowerstate_info.info);
8191 EXPORT_SYMBOL(netdev_lower_state_changed);
8193 static void dev_change_rx_flags(struct net_device *dev, int flags)
8195 const struct net_device_ops *ops = dev->netdev_ops;
8197 if (ops->ndo_change_rx_flags)
8198 ops->ndo_change_rx_flags(dev, flags);
8201 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8203 unsigned int old_flags = dev->flags;
8209 dev->flags |= IFF_PROMISC;
8210 dev->promiscuity += inc;
8211 if (dev->promiscuity == 0) {
8214 * If inc causes overflow, untouch promisc and return error.
8217 dev->flags &= ~IFF_PROMISC;
8219 dev->promiscuity -= inc;
8220 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
8224 if (dev->flags != old_flags) {
8225 pr_info("device %s %s promiscuous mode\n",
8227 dev->flags & IFF_PROMISC ? "entered" : "left");
8228 if (audit_enabled) {
8229 current_uid_gid(&uid, &gid);
8230 audit_log(audit_context(), GFP_ATOMIC,
8231 AUDIT_ANOM_PROMISCUOUS,
8232 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8233 dev->name, (dev->flags & IFF_PROMISC),
8234 (old_flags & IFF_PROMISC),
8235 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8236 from_kuid(&init_user_ns, uid),
8237 from_kgid(&init_user_ns, gid),
8238 audit_get_sessionid(current));
8241 dev_change_rx_flags(dev, IFF_PROMISC);
8244 __dev_notify_flags(dev, old_flags, IFF_PROMISC);
8249 * dev_set_promiscuity - update promiscuity count on a device
8253 * Add or remove promiscuity from a device. While the count in the device
8254 * remains above zero the interface remains promiscuous. Once it hits zero
8255 * the device reverts back to normal filtering operation. A negative inc
8256 * value is used to drop promiscuity on the device.
8257 * Return 0 if successful or a negative errno code on error.
8259 int dev_set_promiscuity(struct net_device *dev, int inc)
8261 unsigned int old_flags = dev->flags;
8264 err = __dev_set_promiscuity(dev, inc, true);
8267 if (dev->flags != old_flags)
8268 dev_set_rx_mode(dev);
8271 EXPORT_SYMBOL(dev_set_promiscuity);
8273 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8275 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8279 dev->flags |= IFF_ALLMULTI;
8280 dev->allmulti += inc;
8281 if (dev->allmulti == 0) {
8284 * If inc causes overflow, untouch allmulti and return error.
8287 dev->flags &= ~IFF_ALLMULTI;
8289 dev->allmulti -= inc;
8290 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
8294 if (dev->flags ^ old_flags) {
8295 dev_change_rx_flags(dev, IFF_ALLMULTI);
8296 dev_set_rx_mode(dev);
8298 __dev_notify_flags(dev, old_flags,
8299 dev->gflags ^ old_gflags);
8305 * dev_set_allmulti - update allmulti count on a device
8309 * Add or remove reception of all multicast frames to a device. While the
8310 * count in the device remains above zero the interface remains listening
8311 * to all interfaces. Once it hits zero the device reverts back to normal
8312 * filtering operation. A negative @inc value is used to drop the counter
8313 * when releasing a resource needing all multicasts.
8314 * Return 0 if successful or a negative errno code on error.
8317 int dev_set_allmulti(struct net_device *dev, int inc)
8319 return __dev_set_allmulti(dev, inc, true);
8321 EXPORT_SYMBOL(dev_set_allmulti);
8324 * Upload unicast and multicast address lists to device and
8325 * configure RX filtering. When the device doesn't support unicast
8326 * filtering it is put in promiscuous mode while unicast addresses
8329 void __dev_set_rx_mode(struct net_device *dev)
8331 const struct net_device_ops *ops = dev->netdev_ops;
8333 /* dev_open will call this function so the list will stay sane. */
8334 if (!(dev->flags&IFF_UP))
8337 if (!netif_device_present(dev))
8340 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8341 /* Unicast addresses changes may only happen under the rtnl,
8342 * therefore calling __dev_set_promiscuity here is safe.
8344 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8345 __dev_set_promiscuity(dev, 1, false);
8346 dev->uc_promisc = true;
8347 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8348 __dev_set_promiscuity(dev, -1, false);
8349 dev->uc_promisc = false;
8353 if (ops->ndo_set_rx_mode)
8354 ops->ndo_set_rx_mode(dev);
8357 void dev_set_rx_mode(struct net_device *dev)
8359 netif_addr_lock_bh(dev);
8360 __dev_set_rx_mode(dev);
8361 netif_addr_unlock_bh(dev);
8365 * dev_get_flags - get flags reported to userspace
8368 * Get the combination of flag bits exported through APIs to userspace.
8370 unsigned int dev_get_flags(const struct net_device *dev)
8374 flags = (dev->flags & ~(IFF_PROMISC |
8379 (dev->gflags & (IFF_PROMISC |
8382 if (netif_running(dev)) {
8383 if (netif_oper_up(dev))
8384 flags |= IFF_RUNNING;
8385 if (netif_carrier_ok(dev))
8386 flags |= IFF_LOWER_UP;
8387 if (netif_dormant(dev))
8388 flags |= IFF_DORMANT;
8393 EXPORT_SYMBOL(dev_get_flags);
8395 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8396 struct netlink_ext_ack *extack)
8398 unsigned int old_flags = dev->flags;
8404 * Set the flags on our device.
8407 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8408 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8410 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8414 * Load in the correct multicast list now the flags have changed.
8417 if ((old_flags ^ flags) & IFF_MULTICAST)
8418 dev_change_rx_flags(dev, IFF_MULTICAST);
8420 dev_set_rx_mode(dev);
8423 * Have we downed the interface. We handle IFF_UP ourselves
8424 * according to user attempts to set it, rather than blindly
8429 if ((old_flags ^ flags) & IFF_UP) {
8430 if (old_flags & IFF_UP)
8433 ret = __dev_open(dev, extack);
8436 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8437 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8438 unsigned int old_flags = dev->flags;
8440 dev->gflags ^= IFF_PROMISC;
8442 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8443 if (dev->flags != old_flags)
8444 dev_set_rx_mode(dev);
8447 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8448 * is important. Some (broken) drivers set IFF_PROMISC, when
8449 * IFF_ALLMULTI is requested not asking us and not reporting.
8451 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8452 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8454 dev->gflags ^= IFF_ALLMULTI;
8455 __dev_set_allmulti(dev, inc, false);
8461 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8462 unsigned int gchanges)
8464 unsigned int changes = dev->flags ^ old_flags;
8467 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
8469 if (changes & IFF_UP) {
8470 if (dev->flags & IFF_UP)
8471 call_netdevice_notifiers(NETDEV_UP, dev);
8473 call_netdevice_notifiers(NETDEV_DOWN, dev);
8476 if (dev->flags & IFF_UP &&
8477 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8478 struct netdev_notifier_change_info change_info = {
8482 .flags_changed = changes,
8485 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8490 * dev_change_flags - change device settings
8492 * @flags: device state flags
8493 * @extack: netlink extended ack
8495 * Change settings on device based state flags. The flags are
8496 * in the userspace exported format.
8498 int dev_change_flags(struct net_device *dev, unsigned int flags,
8499 struct netlink_ext_ack *extack)
8502 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8504 ret = __dev_change_flags(dev, flags, extack);
8508 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8509 __dev_notify_flags(dev, old_flags, changes);
8512 EXPORT_SYMBOL(dev_change_flags);
8514 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8516 const struct net_device_ops *ops = dev->netdev_ops;
8518 if (ops->ndo_change_mtu)
8519 return ops->ndo_change_mtu(dev, new_mtu);
8521 /* Pairs with all the lockless reads of dev->mtu in the stack */
8522 WRITE_ONCE(dev->mtu, new_mtu);
8525 EXPORT_SYMBOL(__dev_set_mtu);
8527 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8528 struct netlink_ext_ack *extack)
8530 /* MTU must be positive, and in range */
8531 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8532 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8536 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8537 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8544 * dev_set_mtu_ext - Change maximum transfer unit
8546 * @new_mtu: new transfer unit
8547 * @extack: netlink extended ack
8549 * Change the maximum transfer size of the network device.
8551 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8552 struct netlink_ext_ack *extack)
8556 if (new_mtu == dev->mtu)
8559 err = dev_validate_mtu(dev, new_mtu, extack);
8563 if (!netif_device_present(dev))
8566 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8567 err = notifier_to_errno(err);
8571 orig_mtu = dev->mtu;
8572 err = __dev_set_mtu(dev, new_mtu);
8575 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8577 err = notifier_to_errno(err);
8579 /* setting mtu back and notifying everyone again,
8580 * so that they have a chance to revert changes.
8582 __dev_set_mtu(dev, orig_mtu);
8583 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8590 int dev_set_mtu(struct net_device *dev, int new_mtu)
8592 struct netlink_ext_ack extack;
8595 memset(&extack, 0, sizeof(extack));
8596 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8597 if (err && extack._msg)
8598 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8601 EXPORT_SYMBOL(dev_set_mtu);
8604 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8606 * @new_len: new tx queue length
8608 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8610 unsigned int orig_len = dev->tx_queue_len;
8613 if (new_len != (unsigned int)new_len)
8616 if (new_len != orig_len) {
8617 dev->tx_queue_len = new_len;
8618 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8619 res = notifier_to_errno(res);
8622 res = dev_qdisc_change_tx_queue_len(dev);
8630 netdev_err(dev, "refused to change device tx_queue_len\n");
8631 dev->tx_queue_len = orig_len;
8636 * dev_set_group - Change group this device belongs to
8638 * @new_group: group this device should belong to
8640 void dev_set_group(struct net_device *dev, int new_group)
8642 dev->group = new_group;
8644 EXPORT_SYMBOL(dev_set_group);
8647 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8649 * @addr: new address
8650 * @extack: netlink extended ack
8652 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8653 struct netlink_ext_ack *extack)
8655 struct netdev_notifier_pre_changeaddr_info info = {
8657 .info.extack = extack,
8662 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8663 return notifier_to_errno(rc);
8665 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8668 * dev_set_mac_address - Change Media Access Control Address
8671 * @extack: netlink extended ack
8673 * Change the hardware (MAC) address of the device
8675 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8676 struct netlink_ext_ack *extack)
8678 const struct net_device_ops *ops = dev->netdev_ops;
8681 if (!ops->ndo_set_mac_address)
8683 if (sa->sa_family != dev->type)
8685 if (!netif_device_present(dev))
8687 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8690 err = ops->ndo_set_mac_address(dev, sa);
8693 dev->addr_assign_type = NET_ADDR_SET;
8694 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8695 add_device_randomness(dev->dev_addr, dev->addr_len);
8698 EXPORT_SYMBOL(dev_set_mac_address);
8700 static DECLARE_RWSEM(dev_addr_sem);
8702 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
8703 struct netlink_ext_ack *extack)
8707 down_write(&dev_addr_sem);
8708 ret = dev_set_mac_address(dev, sa, extack);
8709 up_write(&dev_addr_sem);
8712 EXPORT_SYMBOL(dev_set_mac_address_user);
8714 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
8716 size_t size = sizeof(sa->sa_data);
8717 struct net_device *dev;
8720 down_read(&dev_addr_sem);
8723 dev = dev_get_by_name_rcu(net, dev_name);
8729 memset(sa->sa_data, 0, size);
8731 memcpy(sa->sa_data, dev->dev_addr,
8732 min_t(size_t, size, dev->addr_len));
8733 sa->sa_family = dev->type;
8737 up_read(&dev_addr_sem);
8740 EXPORT_SYMBOL(dev_get_mac_address);
8743 * dev_change_carrier - Change device carrier
8745 * @new_carrier: new value
8747 * Change device carrier
8749 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8751 const struct net_device_ops *ops = dev->netdev_ops;
8753 if (!ops->ndo_change_carrier)
8755 if (!netif_device_present(dev))
8757 return ops->ndo_change_carrier(dev, new_carrier);
8759 EXPORT_SYMBOL(dev_change_carrier);
8762 * dev_get_phys_port_id - Get device physical port ID
8766 * Get device physical port ID
8768 int dev_get_phys_port_id(struct net_device *dev,
8769 struct netdev_phys_item_id *ppid)
8771 const struct net_device_ops *ops = dev->netdev_ops;
8773 if (!ops->ndo_get_phys_port_id)
8775 return ops->ndo_get_phys_port_id(dev, ppid);
8777 EXPORT_SYMBOL(dev_get_phys_port_id);
8780 * dev_get_phys_port_name - Get device physical port name
8783 * @len: limit of bytes to copy to name
8785 * Get device physical port name
8787 int dev_get_phys_port_name(struct net_device *dev,
8788 char *name, size_t len)
8790 const struct net_device_ops *ops = dev->netdev_ops;
8793 if (ops->ndo_get_phys_port_name) {
8794 err = ops->ndo_get_phys_port_name(dev, name, len);
8795 if (err != -EOPNOTSUPP)
8798 return devlink_compat_phys_port_name_get(dev, name, len);
8800 EXPORT_SYMBOL(dev_get_phys_port_name);
8803 * dev_get_port_parent_id - Get the device's port parent identifier
8804 * @dev: network device
8805 * @ppid: pointer to a storage for the port's parent identifier
8806 * @recurse: allow/disallow recursion to lower devices
8808 * Get the devices's port parent identifier
8810 int dev_get_port_parent_id(struct net_device *dev,
8811 struct netdev_phys_item_id *ppid,
8814 const struct net_device_ops *ops = dev->netdev_ops;
8815 struct netdev_phys_item_id first = { };
8816 struct net_device *lower_dev;
8817 struct list_head *iter;
8820 if (ops->ndo_get_port_parent_id) {
8821 err = ops->ndo_get_port_parent_id(dev, ppid);
8822 if (err != -EOPNOTSUPP)
8826 err = devlink_compat_switch_id_get(dev, ppid);
8827 if (!recurse || err != -EOPNOTSUPP)
8830 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8831 err = dev_get_port_parent_id(lower_dev, ppid, true);
8836 else if (memcmp(&first, ppid, sizeof(*ppid)))
8842 EXPORT_SYMBOL(dev_get_port_parent_id);
8845 * netdev_port_same_parent_id - Indicate if two network devices have
8846 * the same port parent identifier
8847 * @a: first network device
8848 * @b: second network device
8850 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
8852 struct netdev_phys_item_id a_id = { };
8853 struct netdev_phys_item_id b_id = { };
8855 if (dev_get_port_parent_id(a, &a_id, true) ||
8856 dev_get_port_parent_id(b, &b_id, true))
8859 return netdev_phys_item_id_same(&a_id, &b_id);
8861 EXPORT_SYMBOL(netdev_port_same_parent_id);
8864 * dev_change_proto_down - set carrier according to proto_down.
8867 * @proto_down: new value
8869 int dev_change_proto_down(struct net_device *dev, bool proto_down)
8871 if (!(dev->priv_flags & IFF_CHANGE_PROTO_DOWN))
8873 if (!netif_device_present(dev))
8876 netif_carrier_off(dev);
8878 netif_carrier_on(dev);
8879 dev->proto_down = proto_down;
8882 EXPORT_SYMBOL(dev_change_proto_down);
8885 * dev_change_proto_down_reason - proto down reason
8888 * @mask: proto down mask
8889 * @value: proto down value
8891 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
8897 dev->proto_down_reason = value;
8899 for_each_set_bit(b, &mask, 32) {
8900 if (value & (1 << b))
8901 dev->proto_down_reason |= BIT(b);
8903 dev->proto_down_reason &= ~BIT(b);
8907 EXPORT_SYMBOL(dev_change_proto_down_reason);
8909 struct bpf_xdp_link {
8910 struct bpf_link link;
8911 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
8915 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
8917 if (flags & XDP_FLAGS_HW_MODE)
8919 if (flags & XDP_FLAGS_DRV_MODE)
8920 return XDP_MODE_DRV;
8921 if (flags & XDP_FLAGS_SKB_MODE)
8922 return XDP_MODE_SKB;
8923 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
8926 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
8930 return generic_xdp_install;
8933 return dev->netdev_ops->ndo_bpf;
8939 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
8940 enum bpf_xdp_mode mode)
8942 return dev->xdp_state[mode].link;
8945 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
8946 enum bpf_xdp_mode mode)
8948 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
8951 return link->link.prog;
8952 return dev->xdp_state[mode].prog;
8955 u8 dev_xdp_prog_count(struct net_device *dev)
8960 for (i = 0; i < __MAX_XDP_MODE; i++)
8961 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
8965 EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
8967 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
8969 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
8971 return prog ? prog->aux->id : 0;
8974 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
8975 struct bpf_xdp_link *link)
8977 dev->xdp_state[mode].link = link;
8978 dev->xdp_state[mode].prog = NULL;
8981 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
8982 struct bpf_prog *prog)
8984 dev->xdp_state[mode].link = NULL;
8985 dev->xdp_state[mode].prog = prog;
8988 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
8989 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
8990 u32 flags, struct bpf_prog *prog)
8992 struct netdev_bpf xdp;
8995 memset(&xdp, 0, sizeof(xdp));
8996 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
8997 xdp.extack = extack;
9001 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
9002 * "moved" into driver), so they don't increment it on their own, but
9003 * they do decrement refcnt when program is detached or replaced.
9004 * Given net_device also owns link/prog, we need to bump refcnt here
9005 * to prevent drivers from underflowing it.
9009 err = bpf_op(dev, &xdp);
9016 if (mode != XDP_MODE_HW)
9017 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9022 static void dev_xdp_uninstall(struct net_device *dev)
9024 struct bpf_xdp_link *link;
9025 struct bpf_prog *prog;
9026 enum bpf_xdp_mode mode;
9031 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9032 prog = dev_xdp_prog(dev, mode);
9036 bpf_op = dev_xdp_bpf_op(dev, mode);
9040 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9042 /* auto-detach link from net device */
9043 link = dev_xdp_link(dev, mode);
9049 dev_xdp_set_link(dev, mode, NULL);
9053 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9054 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9055 struct bpf_prog *old_prog, u32 flags)
9057 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9058 struct bpf_prog *cur_prog;
9059 struct net_device *upper;
9060 struct list_head *iter;
9061 enum bpf_xdp_mode mode;
9067 /* either link or prog attachment, never both */
9068 if (link && (new_prog || old_prog))
9070 /* link supports only XDP mode flags */
9071 if (link && (flags & ~XDP_FLAGS_MODES)) {
9072 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9075 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9076 if (num_modes > 1) {
9077 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9080 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9081 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9082 NL_SET_ERR_MSG(extack,
9083 "More than one program loaded, unset mode is ambiguous");
9086 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9087 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9088 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9092 mode = dev_xdp_mode(dev, flags);
9093 /* can't replace attached link */
9094 if (dev_xdp_link(dev, mode)) {
9095 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9099 /* don't allow if an upper device already has a program */
9100 netdev_for_each_upper_dev_rcu(dev, upper, iter) {
9101 if (dev_xdp_prog_count(upper) > 0) {
9102 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
9107 cur_prog = dev_xdp_prog(dev, mode);
9108 /* can't replace attached prog with link */
9109 if (link && cur_prog) {
9110 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9113 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9114 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9118 /* put effective new program into new_prog */
9120 new_prog = link->link.prog;
9123 bool offload = mode == XDP_MODE_HW;
9124 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9125 ? XDP_MODE_DRV : XDP_MODE_SKB;
9127 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9128 NL_SET_ERR_MSG(extack, "XDP program already attached");
9131 if (!offload && dev_xdp_prog(dev, other_mode)) {
9132 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9135 if (!offload && bpf_prog_is_dev_bound(new_prog->aux)) {
9136 NL_SET_ERR_MSG(extack, "Using device-bound program without HW_MODE flag is not supported");
9139 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9140 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9143 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9144 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9149 /* don't call drivers if the effective program didn't change */
9150 if (new_prog != cur_prog) {
9151 bpf_op = dev_xdp_bpf_op(dev, mode);
9153 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9157 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9163 dev_xdp_set_link(dev, mode, link);
9165 dev_xdp_set_prog(dev, mode, new_prog);
9167 bpf_prog_put(cur_prog);
9172 static int dev_xdp_attach_link(struct net_device *dev,
9173 struct netlink_ext_ack *extack,
9174 struct bpf_xdp_link *link)
9176 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9179 static int dev_xdp_detach_link(struct net_device *dev,
9180 struct netlink_ext_ack *extack,
9181 struct bpf_xdp_link *link)
9183 enum bpf_xdp_mode mode;
9188 mode = dev_xdp_mode(dev, link->flags);
9189 if (dev_xdp_link(dev, mode) != link)
9192 bpf_op = dev_xdp_bpf_op(dev, mode);
9193 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9194 dev_xdp_set_link(dev, mode, NULL);
9198 static void bpf_xdp_link_release(struct bpf_link *link)
9200 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9204 /* if racing with net_device's tear down, xdp_link->dev might be
9205 * already NULL, in which case link was already auto-detached
9207 if (xdp_link->dev) {
9208 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9209 xdp_link->dev = NULL;
9215 static int bpf_xdp_link_detach(struct bpf_link *link)
9217 bpf_xdp_link_release(link);
9221 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9223 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9228 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9229 struct seq_file *seq)
9231 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9236 ifindex = xdp_link->dev->ifindex;
9239 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9242 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9243 struct bpf_link_info *info)
9245 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9250 ifindex = xdp_link->dev->ifindex;
9253 info->xdp.ifindex = ifindex;
9257 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9258 struct bpf_prog *old_prog)
9260 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9261 enum bpf_xdp_mode mode;
9267 /* link might have been auto-released already, so fail */
9268 if (!xdp_link->dev) {
9273 if (old_prog && link->prog != old_prog) {
9277 old_prog = link->prog;
9278 if (old_prog->type != new_prog->type ||
9279 old_prog->expected_attach_type != new_prog->expected_attach_type) {
9284 if (old_prog == new_prog) {
9285 /* no-op, don't disturb drivers */
9286 bpf_prog_put(new_prog);
9290 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9291 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9292 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9293 xdp_link->flags, new_prog);
9297 old_prog = xchg(&link->prog, new_prog);
9298 bpf_prog_put(old_prog);
9305 static const struct bpf_link_ops bpf_xdp_link_lops = {
9306 .release = bpf_xdp_link_release,
9307 .dealloc = bpf_xdp_link_dealloc,
9308 .detach = bpf_xdp_link_detach,
9309 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9310 .fill_link_info = bpf_xdp_link_fill_link_info,
9311 .update_prog = bpf_xdp_link_update,
9314 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9316 struct net *net = current->nsproxy->net_ns;
9317 struct bpf_link_primer link_primer;
9318 struct bpf_xdp_link *link;
9319 struct net_device *dev;
9323 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9329 link = kzalloc(sizeof(*link), GFP_USER);
9335 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9337 link->flags = attr->link_create.flags;
9339 err = bpf_link_prime(&link->link, &link_primer);
9345 err = dev_xdp_attach_link(dev, NULL, link);
9350 bpf_link_cleanup(&link_primer);
9354 fd = bpf_link_settle(&link_primer);
9355 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9368 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9370 * @extack: netlink extended ack
9371 * @fd: new program fd or negative value to clear
9372 * @expected_fd: old program fd that userspace expects to replace or clear
9373 * @flags: xdp-related flags
9375 * Set or clear a bpf program for a device
9377 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9378 int fd, int expected_fd, u32 flags)
9380 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9381 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9387 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9388 mode != XDP_MODE_SKB);
9389 if (IS_ERR(new_prog))
9390 return PTR_ERR(new_prog);
9393 if (expected_fd >= 0) {
9394 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9395 mode != XDP_MODE_SKB);
9396 if (IS_ERR(old_prog)) {
9397 err = PTR_ERR(old_prog);
9403 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9406 if (err && new_prog)
9407 bpf_prog_put(new_prog);
9409 bpf_prog_put(old_prog);
9414 * dev_new_index - allocate an ifindex
9415 * @net: the applicable net namespace
9417 * Returns a suitable unique value for a new device interface
9418 * number. The caller must hold the rtnl semaphore or the
9419 * dev_base_lock to be sure it remains unique.
9421 static int dev_new_index(struct net *net)
9423 int ifindex = net->ifindex;
9428 if (!__dev_get_by_index(net, ifindex))
9429 return net->ifindex = ifindex;
9433 /* Delayed registration/unregisteration */
9434 static LIST_HEAD(net_todo_list);
9435 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9437 static void net_set_todo(struct net_device *dev)
9439 list_add_tail(&dev->todo_list, &net_todo_list);
9440 atomic_inc(&dev_net(dev)->dev_unreg_count);
9443 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9444 struct net_device *upper, netdev_features_t features)
9446 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9447 netdev_features_t feature;
9450 for_each_netdev_feature(upper_disables, feature_bit) {
9451 feature = __NETIF_F_BIT(feature_bit);
9452 if (!(upper->wanted_features & feature)
9453 && (features & feature)) {
9454 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9455 &feature, upper->name);
9456 features &= ~feature;
9463 static void netdev_sync_lower_features(struct net_device *upper,
9464 struct net_device *lower, netdev_features_t features)
9466 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9467 netdev_features_t feature;
9470 for_each_netdev_feature(upper_disables, feature_bit) {
9471 feature = __NETIF_F_BIT(feature_bit);
9472 if (!(features & feature) && (lower->features & feature)) {
9473 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9474 &feature, lower->name);
9475 lower->wanted_features &= ~feature;
9476 __netdev_update_features(lower);
9478 if (unlikely(lower->features & feature))
9479 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9480 &feature, lower->name);
9482 netdev_features_change(lower);
9487 static netdev_features_t netdev_fix_features(struct net_device *dev,
9488 netdev_features_t features)
9490 /* Fix illegal checksum combinations */
9491 if ((features & NETIF_F_HW_CSUM) &&
9492 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9493 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9494 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9497 /* TSO requires that SG is present as well. */
9498 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9499 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9500 features &= ~NETIF_F_ALL_TSO;
9503 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9504 !(features & NETIF_F_IP_CSUM)) {
9505 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9506 features &= ~NETIF_F_TSO;
9507 features &= ~NETIF_F_TSO_ECN;
9510 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9511 !(features & NETIF_F_IPV6_CSUM)) {
9512 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9513 features &= ~NETIF_F_TSO6;
9516 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9517 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9518 features &= ~NETIF_F_TSO_MANGLEID;
9520 /* TSO ECN requires that TSO is present as well. */
9521 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9522 features &= ~NETIF_F_TSO_ECN;
9524 /* Software GSO depends on SG. */
9525 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9526 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9527 features &= ~NETIF_F_GSO;
9530 /* GSO partial features require GSO partial be set */
9531 if ((features & dev->gso_partial_features) &&
9532 !(features & NETIF_F_GSO_PARTIAL)) {
9534 "Dropping partially supported GSO features since no GSO partial.\n");
9535 features &= ~dev->gso_partial_features;
9538 if (!(features & NETIF_F_RXCSUM)) {
9539 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9540 * successfully merged by hardware must also have the
9541 * checksum verified by hardware. If the user does not
9542 * want to enable RXCSUM, logically, we should disable GRO_HW.
9544 if (features & NETIF_F_GRO_HW) {
9545 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9546 features &= ~NETIF_F_GRO_HW;
9550 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9551 if (features & NETIF_F_RXFCS) {
9552 if (features & NETIF_F_LRO) {
9553 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9554 features &= ~NETIF_F_LRO;
9557 if (features & NETIF_F_GRO_HW) {
9558 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9559 features &= ~NETIF_F_GRO_HW;
9563 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
9564 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
9565 features &= ~NETIF_F_LRO;
9568 if (features & NETIF_F_HW_TLS_TX) {
9569 bool ip_csum = (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) ==
9570 (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
9571 bool hw_csum = features & NETIF_F_HW_CSUM;
9573 if (!ip_csum && !hw_csum) {
9574 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
9575 features &= ~NETIF_F_HW_TLS_TX;
9579 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
9580 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
9581 features &= ~NETIF_F_HW_TLS_RX;
9587 int __netdev_update_features(struct net_device *dev)
9589 struct net_device *upper, *lower;
9590 netdev_features_t features;
9591 struct list_head *iter;
9596 features = netdev_get_wanted_features(dev);
9598 if (dev->netdev_ops->ndo_fix_features)
9599 features = dev->netdev_ops->ndo_fix_features(dev, features);
9601 /* driver might be less strict about feature dependencies */
9602 features = netdev_fix_features(dev, features);
9604 /* some features can't be enabled if they're off on an upper device */
9605 netdev_for_each_upper_dev_rcu(dev, upper, iter)
9606 features = netdev_sync_upper_features(dev, upper, features);
9608 if (dev->features == features)
9611 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9612 &dev->features, &features);
9614 if (dev->netdev_ops->ndo_set_features)
9615 err = dev->netdev_ops->ndo_set_features(dev, features);
9619 if (unlikely(err < 0)) {
9621 "set_features() failed (%d); wanted %pNF, left %pNF\n",
9622 err, &features, &dev->features);
9623 /* return non-0 since some features might have changed and
9624 * it's better to fire a spurious notification than miss it
9630 /* some features must be disabled on lower devices when disabled
9631 * on an upper device (think: bonding master or bridge)
9633 netdev_for_each_lower_dev(dev, lower, iter)
9634 netdev_sync_lower_features(dev, lower, features);
9637 netdev_features_t diff = features ^ dev->features;
9639 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9640 /* udp_tunnel_{get,drop}_rx_info both need
9641 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9642 * device, or they won't do anything.
9643 * Thus we need to update dev->features
9644 * *before* calling udp_tunnel_get_rx_info,
9645 * but *after* calling udp_tunnel_drop_rx_info.
9647 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9648 dev->features = features;
9649 udp_tunnel_get_rx_info(dev);
9651 udp_tunnel_drop_rx_info(dev);
9655 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9656 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9657 dev->features = features;
9658 err |= vlan_get_rx_ctag_filter_info(dev);
9660 vlan_drop_rx_ctag_filter_info(dev);
9664 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9665 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9666 dev->features = features;
9667 err |= vlan_get_rx_stag_filter_info(dev);
9669 vlan_drop_rx_stag_filter_info(dev);
9673 dev->features = features;
9676 return err < 0 ? 0 : 1;
9680 * netdev_update_features - recalculate device features
9681 * @dev: the device to check
9683 * Recalculate dev->features set and send notifications if it
9684 * has changed. Should be called after driver or hardware dependent
9685 * conditions might have changed that influence the features.
9687 void netdev_update_features(struct net_device *dev)
9689 if (__netdev_update_features(dev))
9690 netdev_features_change(dev);
9692 EXPORT_SYMBOL(netdev_update_features);
9695 * netdev_change_features - recalculate device features
9696 * @dev: the device to check
9698 * Recalculate dev->features set and send notifications even
9699 * if they have not changed. Should be called instead of
9700 * netdev_update_features() if also dev->vlan_features might
9701 * have changed to allow the changes to be propagated to stacked
9704 void netdev_change_features(struct net_device *dev)
9706 __netdev_update_features(dev);
9707 netdev_features_change(dev);
9709 EXPORT_SYMBOL(netdev_change_features);
9712 * netif_stacked_transfer_operstate - transfer operstate
9713 * @rootdev: the root or lower level device to transfer state from
9714 * @dev: the device to transfer operstate to
9716 * Transfer operational state from root to device. This is normally
9717 * called when a stacking relationship exists between the root
9718 * device and the device(a leaf device).
9720 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9721 struct net_device *dev)
9723 if (rootdev->operstate == IF_OPER_DORMANT)
9724 netif_dormant_on(dev);
9726 netif_dormant_off(dev);
9728 if (rootdev->operstate == IF_OPER_TESTING)
9729 netif_testing_on(dev);
9731 netif_testing_off(dev);
9733 if (netif_carrier_ok(rootdev))
9734 netif_carrier_on(dev);
9736 netif_carrier_off(dev);
9738 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9740 static int netif_alloc_rx_queues(struct net_device *dev)
9742 unsigned int i, count = dev->num_rx_queues;
9743 struct netdev_rx_queue *rx;
9744 size_t sz = count * sizeof(*rx);
9749 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9755 for (i = 0; i < count; i++) {
9758 /* XDP RX-queue setup */
9759 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
9766 /* Rollback successful reg's and free other resources */
9768 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9774 static void netif_free_rx_queues(struct net_device *dev)
9776 unsigned int i, count = dev->num_rx_queues;
9778 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9782 for (i = 0; i < count; i++)
9783 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9788 static void netdev_init_one_queue(struct net_device *dev,
9789 struct netdev_queue *queue, void *_unused)
9791 /* Initialize queue lock */
9792 spin_lock_init(&queue->_xmit_lock);
9793 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
9794 queue->xmit_lock_owner = -1;
9795 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
9798 dql_init(&queue->dql, HZ);
9802 static void netif_free_tx_queues(struct net_device *dev)
9807 static int netif_alloc_netdev_queues(struct net_device *dev)
9809 unsigned int count = dev->num_tx_queues;
9810 struct netdev_queue *tx;
9811 size_t sz = count * sizeof(*tx);
9813 if (count < 1 || count > 0xffff)
9816 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9822 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
9823 spin_lock_init(&dev->tx_global_lock);
9828 void netif_tx_stop_all_queues(struct net_device *dev)
9832 for (i = 0; i < dev->num_tx_queues; i++) {
9833 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
9835 netif_tx_stop_queue(txq);
9838 EXPORT_SYMBOL(netif_tx_stop_all_queues);
9841 * register_netdevice - register a network device
9842 * @dev: device to register
9844 * Take a completed network device structure and add it to the kernel
9845 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9846 * chain. 0 is returned on success. A negative errno code is returned
9847 * on a failure to set up the device, or if the name is a duplicate.
9849 * Callers must hold the rtnl semaphore. You may want
9850 * register_netdev() instead of this.
9853 * The locking appears insufficient to guarantee two parallel registers
9854 * will not get the same name.
9857 int register_netdevice(struct net_device *dev)
9860 struct net *net = dev_net(dev);
9862 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
9863 NETDEV_FEATURE_COUNT);
9864 BUG_ON(dev_boot_phase);
9869 /* When net_device's are persistent, this will be fatal. */
9870 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
9873 ret = ethtool_check_ops(dev->ethtool_ops);
9877 spin_lock_init(&dev->addr_list_lock);
9878 netdev_set_addr_lockdep_class(dev);
9880 ret = dev_get_valid_name(net, dev, dev->name);
9885 dev->name_node = netdev_name_node_head_alloc(dev);
9886 if (!dev->name_node)
9889 /* Init, if this function is available */
9890 if (dev->netdev_ops->ndo_init) {
9891 ret = dev->netdev_ops->ndo_init(dev);
9899 if (((dev->hw_features | dev->features) &
9900 NETIF_F_HW_VLAN_CTAG_FILTER) &&
9901 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
9902 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
9903 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
9910 dev->ifindex = dev_new_index(net);
9911 else if (__dev_get_by_index(net, dev->ifindex))
9914 /* Transfer changeable features to wanted_features and enable
9915 * software offloads (GSO and GRO).
9917 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
9918 dev->features |= NETIF_F_SOFT_FEATURES;
9920 if (dev->udp_tunnel_nic_info) {
9921 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9922 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9925 dev->wanted_features = dev->features & dev->hw_features;
9927 if (!(dev->flags & IFF_LOOPBACK))
9928 dev->hw_features |= NETIF_F_NOCACHE_COPY;
9930 /* If IPv4 TCP segmentation offload is supported we should also
9931 * allow the device to enable segmenting the frame with the option
9932 * of ignoring a static IP ID value. This doesn't enable the
9933 * feature itself but allows the user to enable it later.
9935 if (dev->hw_features & NETIF_F_TSO)
9936 dev->hw_features |= NETIF_F_TSO_MANGLEID;
9937 if (dev->vlan_features & NETIF_F_TSO)
9938 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
9939 if (dev->mpls_features & NETIF_F_TSO)
9940 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
9941 if (dev->hw_enc_features & NETIF_F_TSO)
9942 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
9944 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
9946 dev->vlan_features |= NETIF_F_HIGHDMA;
9948 /* Make NETIF_F_SG inheritable to tunnel devices.
9950 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
9952 /* Make NETIF_F_SG inheritable to MPLS.
9954 dev->mpls_features |= NETIF_F_SG;
9956 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
9957 ret = notifier_to_errno(ret);
9961 ret = netdev_register_kobject(dev);
9963 dev->reg_state = NETREG_UNREGISTERED;
9966 dev->reg_state = NETREG_REGISTERED;
9968 __netdev_update_features(dev);
9971 * Default initial state at registry is that the
9972 * device is present.
9975 set_bit(__LINK_STATE_PRESENT, &dev->state);
9977 linkwatch_init_dev(dev);
9979 dev_init_scheduler(dev);
9981 dev_hold_track(dev, &dev->dev_registered_tracker, GFP_KERNEL);
9982 list_netdevice(dev);
9984 add_device_randomness(dev->dev_addr, dev->addr_len);
9986 /* If the device has permanent device address, driver should
9987 * set dev_addr and also addr_assign_type should be set to
9988 * NET_ADDR_PERM (default value).
9990 if (dev->addr_assign_type == NET_ADDR_PERM)
9991 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
9993 /* Notify protocols, that a new device appeared. */
9994 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
9995 ret = notifier_to_errno(ret);
9997 /* Expect explicit free_netdev() on failure */
9998 dev->needs_free_netdev = false;
9999 unregister_netdevice_queue(dev, NULL);
10003 * Prevent userspace races by waiting until the network
10004 * device is fully setup before sending notifications.
10006 if (!dev->rtnl_link_ops ||
10007 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10008 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10014 if (dev->netdev_ops->ndo_uninit)
10015 dev->netdev_ops->ndo_uninit(dev);
10016 if (dev->priv_destructor)
10017 dev->priv_destructor(dev);
10019 netdev_name_node_free(dev->name_node);
10022 EXPORT_SYMBOL(register_netdevice);
10025 * init_dummy_netdev - init a dummy network device for NAPI
10026 * @dev: device to init
10028 * This takes a network device structure and initialize the minimum
10029 * amount of fields so it can be used to schedule NAPI polls without
10030 * registering a full blown interface. This is to be used by drivers
10031 * that need to tie several hardware interfaces to a single NAPI
10032 * poll scheduler due to HW limitations.
10034 int init_dummy_netdev(struct net_device *dev)
10036 /* Clear everything. Note we don't initialize spinlocks
10037 * are they aren't supposed to be taken by any of the
10038 * NAPI code and this dummy netdev is supposed to be
10039 * only ever used for NAPI polls
10041 memset(dev, 0, sizeof(struct net_device));
10043 /* make sure we BUG if trying to hit standard
10044 * register/unregister code path
10046 dev->reg_state = NETREG_DUMMY;
10048 /* NAPI wants this */
10049 INIT_LIST_HEAD(&dev->napi_list);
10051 /* a dummy interface is started by default */
10052 set_bit(__LINK_STATE_PRESENT, &dev->state);
10053 set_bit(__LINK_STATE_START, &dev->state);
10055 /* napi_busy_loop stats accounting wants this */
10056 dev_net_set(dev, &init_net);
10058 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10059 * because users of this 'device' dont need to change
10065 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10069 * register_netdev - register a network device
10070 * @dev: device to register
10072 * Take a completed network device structure and add it to the kernel
10073 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10074 * chain. 0 is returned on success. A negative errno code is returned
10075 * on a failure to set up the device, or if the name is a duplicate.
10077 * This is a wrapper around register_netdevice that takes the rtnl semaphore
10078 * and expands the device name if you passed a format string to
10081 int register_netdev(struct net_device *dev)
10085 if (rtnl_lock_killable())
10087 err = register_netdevice(dev);
10091 EXPORT_SYMBOL(register_netdev);
10093 int netdev_refcnt_read(const struct net_device *dev)
10095 #ifdef CONFIG_PCPU_DEV_REFCNT
10098 for_each_possible_cpu(i)
10099 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10102 return refcount_read(&dev->dev_refcnt);
10105 EXPORT_SYMBOL(netdev_refcnt_read);
10107 int netdev_unregister_timeout_secs __read_mostly = 10;
10109 #define WAIT_REFS_MIN_MSECS 1
10110 #define WAIT_REFS_MAX_MSECS 250
10112 * netdev_wait_allrefs_any - wait until all references are gone.
10113 * @list: list of net_devices to wait on
10115 * This is called when unregistering network devices.
10117 * Any protocol or device that holds a reference should register
10118 * for netdevice notification, and cleanup and put back the
10119 * reference if they receive an UNREGISTER event.
10120 * We can get stuck here if buggy protocols don't correctly
10123 static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
10125 unsigned long rebroadcast_time, warning_time;
10126 struct net_device *dev;
10129 rebroadcast_time = warning_time = jiffies;
10131 list_for_each_entry(dev, list, todo_list)
10132 if (netdev_refcnt_read(dev) == 1)
10136 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10139 /* Rebroadcast unregister notification */
10140 list_for_each_entry(dev, list, todo_list)
10141 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10147 list_for_each_entry(dev, list, todo_list)
10148 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10150 /* We must not have linkwatch events
10151 * pending on unregister. If this
10152 * happens, we simply run the queue
10153 * unscheduled, resulting in a noop
10156 linkwatch_run_queue();
10162 rebroadcast_time = jiffies;
10167 wait = WAIT_REFS_MIN_MSECS;
10170 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10173 list_for_each_entry(dev, list, todo_list)
10174 if (netdev_refcnt_read(dev) == 1)
10177 if (time_after(jiffies, warning_time +
10178 netdev_unregister_timeout_secs * HZ)) {
10179 list_for_each_entry(dev, list, todo_list) {
10180 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10181 dev->name, netdev_refcnt_read(dev));
10182 ref_tracker_dir_print(&dev->refcnt_tracker, 10);
10185 warning_time = jiffies;
10190 /* The sequence is:
10194 * register_netdevice(x1);
10195 * register_netdevice(x2);
10197 * unregister_netdevice(y1);
10198 * unregister_netdevice(y2);
10204 * We are invoked by rtnl_unlock().
10205 * This allows us to deal with problems:
10206 * 1) We can delete sysfs objects which invoke hotplug
10207 * without deadlocking with linkwatch via keventd.
10208 * 2) Since we run with the RTNL semaphore not held, we can sleep
10209 * safely in order to wait for the netdev refcnt to drop to zero.
10211 * We must not return until all unregister events added during
10212 * the interval the lock was held have been completed.
10214 void netdev_run_todo(void)
10216 struct net_device *dev, *tmp;
10217 struct list_head list;
10218 #ifdef CONFIG_LOCKDEP
10219 struct list_head unlink_list;
10221 list_replace_init(&net_unlink_list, &unlink_list);
10223 while (!list_empty(&unlink_list)) {
10224 struct net_device *dev = list_first_entry(&unlink_list,
10227 list_del_init(&dev->unlink_list);
10228 dev->nested_level = dev->lower_level - 1;
10232 /* Snapshot list, allow later requests */
10233 list_replace_init(&net_todo_list, &list);
10237 /* Wait for rcu callbacks to finish before next phase */
10238 if (!list_empty(&list))
10241 list_for_each_entry_safe(dev, tmp, &list, todo_list) {
10242 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10243 netdev_WARN(dev, "run_todo but not unregistering\n");
10244 list_del(&dev->todo_list);
10248 dev->reg_state = NETREG_UNREGISTERED;
10249 linkwatch_forget_dev(dev);
10252 while (!list_empty(&list)) {
10253 dev = netdev_wait_allrefs_any(&list);
10254 list_del(&dev->todo_list);
10257 BUG_ON(netdev_refcnt_read(dev) != 1);
10258 BUG_ON(!list_empty(&dev->ptype_all));
10259 BUG_ON(!list_empty(&dev->ptype_specific));
10260 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10261 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10262 #if IS_ENABLED(CONFIG_DECNET)
10263 WARN_ON(dev->dn_ptr);
10265 if (dev->priv_destructor)
10266 dev->priv_destructor(dev);
10267 if (dev->needs_free_netdev)
10270 if (atomic_dec_and_test(&dev_net(dev)->dev_unreg_count))
10271 wake_up(&netdev_unregistering_wq);
10273 /* Free network device */
10274 kobject_put(&dev->dev.kobj);
10278 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10279 * all the same fields in the same order as net_device_stats, with only
10280 * the type differing, but rtnl_link_stats64 may have additional fields
10281 * at the end for newer counters.
10283 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10284 const struct net_device_stats *netdev_stats)
10286 #if BITS_PER_LONG == 64
10287 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
10288 memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
10289 /* zero out counters that only exist in rtnl_link_stats64 */
10290 memset((char *)stats64 + sizeof(*netdev_stats), 0,
10291 sizeof(*stats64) - sizeof(*netdev_stats));
10293 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
10294 const unsigned long *src = (const unsigned long *)netdev_stats;
10295 u64 *dst = (u64 *)stats64;
10297 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10298 for (i = 0; i < n; i++)
10300 /* zero out counters that only exist in rtnl_link_stats64 */
10301 memset((char *)stats64 + n * sizeof(u64), 0,
10302 sizeof(*stats64) - n * sizeof(u64));
10305 EXPORT_SYMBOL(netdev_stats_to_stats64);
10307 struct net_device_core_stats __percpu *netdev_core_stats_alloc(struct net_device *dev)
10309 struct net_device_core_stats __percpu *p;
10311 p = alloc_percpu_gfp(struct net_device_core_stats,
10312 GFP_ATOMIC | __GFP_NOWARN);
10314 if (p && cmpxchg(&dev->core_stats, NULL, p))
10317 /* This READ_ONCE() pairs with the cmpxchg() above */
10318 return READ_ONCE(dev->core_stats);
10320 EXPORT_SYMBOL(netdev_core_stats_alloc);
10323 * dev_get_stats - get network device statistics
10324 * @dev: device to get statistics from
10325 * @storage: place to store stats
10327 * Get network statistics from device. Return @storage.
10328 * The device driver may provide its own method by setting
10329 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10330 * otherwise the internal statistics structure is used.
10332 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10333 struct rtnl_link_stats64 *storage)
10335 const struct net_device_ops *ops = dev->netdev_ops;
10336 const struct net_device_core_stats __percpu *p;
10338 if (ops->ndo_get_stats64) {
10339 memset(storage, 0, sizeof(*storage));
10340 ops->ndo_get_stats64(dev, storage);
10341 } else if (ops->ndo_get_stats) {
10342 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10344 netdev_stats_to_stats64(storage, &dev->stats);
10347 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10348 p = READ_ONCE(dev->core_stats);
10350 const struct net_device_core_stats *core_stats;
10353 for_each_possible_cpu(i) {
10354 core_stats = per_cpu_ptr(p, i);
10355 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
10356 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
10357 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
10362 EXPORT_SYMBOL(dev_get_stats);
10365 * dev_fetch_sw_netstats - get per-cpu network device statistics
10366 * @s: place to store stats
10367 * @netstats: per-cpu network stats to read from
10369 * Read per-cpu network statistics and populate the related fields in @s.
10371 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10372 const struct pcpu_sw_netstats __percpu *netstats)
10376 for_each_possible_cpu(cpu) {
10377 const struct pcpu_sw_netstats *stats;
10378 struct pcpu_sw_netstats tmp;
10379 unsigned int start;
10381 stats = per_cpu_ptr(netstats, cpu);
10383 start = u64_stats_fetch_begin_irq(&stats->syncp);
10384 tmp.rx_packets = stats->rx_packets;
10385 tmp.rx_bytes = stats->rx_bytes;
10386 tmp.tx_packets = stats->tx_packets;
10387 tmp.tx_bytes = stats->tx_bytes;
10388 } while (u64_stats_fetch_retry_irq(&stats->syncp, start));
10390 s->rx_packets += tmp.rx_packets;
10391 s->rx_bytes += tmp.rx_bytes;
10392 s->tx_packets += tmp.tx_packets;
10393 s->tx_bytes += tmp.tx_bytes;
10396 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10399 * dev_get_tstats64 - ndo_get_stats64 implementation
10400 * @dev: device to get statistics from
10401 * @s: place to store stats
10403 * Populate @s from dev->stats and dev->tstats. Can be used as
10404 * ndo_get_stats64() callback.
10406 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
10408 netdev_stats_to_stats64(s, &dev->stats);
10409 dev_fetch_sw_netstats(s, dev->tstats);
10411 EXPORT_SYMBOL_GPL(dev_get_tstats64);
10413 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10415 struct netdev_queue *queue = dev_ingress_queue(dev);
10417 #ifdef CONFIG_NET_CLS_ACT
10420 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10423 netdev_init_one_queue(dev, queue, NULL);
10424 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10425 queue->qdisc_sleeping = &noop_qdisc;
10426 rcu_assign_pointer(dev->ingress_queue, queue);
10431 static const struct ethtool_ops default_ethtool_ops;
10433 void netdev_set_default_ethtool_ops(struct net_device *dev,
10434 const struct ethtool_ops *ops)
10436 if (dev->ethtool_ops == &default_ethtool_ops)
10437 dev->ethtool_ops = ops;
10439 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10441 void netdev_freemem(struct net_device *dev)
10443 char *addr = (char *)dev - dev->padded;
10449 * alloc_netdev_mqs - allocate network device
10450 * @sizeof_priv: size of private data to allocate space for
10451 * @name: device name format string
10452 * @name_assign_type: origin of device name
10453 * @setup: callback to initialize device
10454 * @txqs: the number of TX subqueues to allocate
10455 * @rxqs: the number of RX subqueues to allocate
10457 * Allocates a struct net_device with private data area for driver use
10458 * and performs basic initialization. Also allocates subqueue structs
10459 * for each queue on the device.
10461 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10462 unsigned char name_assign_type,
10463 void (*setup)(struct net_device *),
10464 unsigned int txqs, unsigned int rxqs)
10466 struct net_device *dev;
10467 unsigned int alloc_size;
10468 struct net_device *p;
10470 BUG_ON(strlen(name) >= sizeof(dev->name));
10473 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10478 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10482 alloc_size = sizeof(struct net_device);
10484 /* ensure 32-byte alignment of private area */
10485 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10486 alloc_size += sizeof_priv;
10488 /* ensure 32-byte alignment of whole construct */
10489 alloc_size += NETDEV_ALIGN - 1;
10491 p = kvzalloc(alloc_size, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10495 dev = PTR_ALIGN(p, NETDEV_ALIGN);
10496 dev->padded = (char *)dev - (char *)p;
10498 ref_tracker_dir_init(&dev->refcnt_tracker, 128);
10499 #ifdef CONFIG_PCPU_DEV_REFCNT
10500 dev->pcpu_refcnt = alloc_percpu(int);
10501 if (!dev->pcpu_refcnt)
10505 refcount_set(&dev->dev_refcnt, 1);
10508 if (dev_addr_init(dev))
10514 dev_net_set(dev, &init_net);
10516 dev->gso_max_size = GSO_MAX_SIZE;
10517 dev->gso_max_segs = GSO_MAX_SEGS;
10518 dev->gro_max_size = GRO_MAX_SIZE;
10519 dev->upper_level = 1;
10520 dev->lower_level = 1;
10521 #ifdef CONFIG_LOCKDEP
10522 dev->nested_level = 0;
10523 INIT_LIST_HEAD(&dev->unlink_list);
10526 INIT_LIST_HEAD(&dev->napi_list);
10527 INIT_LIST_HEAD(&dev->unreg_list);
10528 INIT_LIST_HEAD(&dev->close_list);
10529 INIT_LIST_HEAD(&dev->link_watch_list);
10530 INIT_LIST_HEAD(&dev->adj_list.upper);
10531 INIT_LIST_HEAD(&dev->adj_list.lower);
10532 INIT_LIST_HEAD(&dev->ptype_all);
10533 INIT_LIST_HEAD(&dev->ptype_specific);
10534 INIT_LIST_HEAD(&dev->net_notifier_list);
10535 #ifdef CONFIG_NET_SCHED
10536 hash_init(dev->qdisc_hash);
10538 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10541 if (!dev->tx_queue_len) {
10542 dev->priv_flags |= IFF_NO_QUEUE;
10543 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10546 dev->num_tx_queues = txqs;
10547 dev->real_num_tx_queues = txqs;
10548 if (netif_alloc_netdev_queues(dev))
10551 dev->num_rx_queues = rxqs;
10552 dev->real_num_rx_queues = rxqs;
10553 if (netif_alloc_rx_queues(dev))
10556 strcpy(dev->name, name);
10557 dev->name_assign_type = name_assign_type;
10558 dev->group = INIT_NETDEV_GROUP;
10559 if (!dev->ethtool_ops)
10560 dev->ethtool_ops = &default_ethtool_ops;
10562 nf_hook_netdev_init(dev);
10571 #ifdef CONFIG_PCPU_DEV_REFCNT
10572 free_percpu(dev->pcpu_refcnt);
10575 netdev_freemem(dev);
10578 EXPORT_SYMBOL(alloc_netdev_mqs);
10581 * free_netdev - free network device
10584 * This function does the last stage of destroying an allocated device
10585 * interface. The reference to the device object is released. If this
10586 * is the last reference then it will be freed.Must be called in process
10589 void free_netdev(struct net_device *dev)
10591 struct napi_struct *p, *n;
10595 /* When called immediately after register_netdevice() failed the unwind
10596 * handling may still be dismantling the device. Handle that case by
10597 * deferring the free.
10599 if (dev->reg_state == NETREG_UNREGISTERING) {
10601 dev->needs_free_netdev = true;
10605 netif_free_tx_queues(dev);
10606 netif_free_rx_queues(dev);
10608 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10610 /* Flush device addresses */
10611 dev_addr_flush(dev);
10613 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10616 ref_tracker_dir_exit(&dev->refcnt_tracker);
10617 #ifdef CONFIG_PCPU_DEV_REFCNT
10618 free_percpu(dev->pcpu_refcnt);
10619 dev->pcpu_refcnt = NULL;
10621 free_percpu(dev->core_stats);
10622 dev->core_stats = NULL;
10623 free_percpu(dev->xdp_bulkq);
10624 dev->xdp_bulkq = NULL;
10626 /* Compatibility with error handling in drivers */
10627 if (dev->reg_state == NETREG_UNINITIALIZED) {
10628 netdev_freemem(dev);
10632 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
10633 dev->reg_state = NETREG_RELEASED;
10635 /* will free via device release */
10636 put_device(&dev->dev);
10638 EXPORT_SYMBOL(free_netdev);
10641 * synchronize_net - Synchronize with packet receive processing
10643 * Wait for packets currently being received to be done.
10644 * Does not block later packets from starting.
10646 void synchronize_net(void)
10649 if (rtnl_is_locked())
10650 synchronize_rcu_expedited();
10654 EXPORT_SYMBOL(synchronize_net);
10657 * unregister_netdevice_queue - remove device from the kernel
10661 * This function shuts down a device interface and removes it
10662 * from the kernel tables.
10663 * If head not NULL, device is queued to be unregistered later.
10665 * Callers must hold the rtnl semaphore. You may want
10666 * unregister_netdev() instead of this.
10669 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
10674 list_move_tail(&dev->unreg_list, head);
10678 list_add(&dev->unreg_list, &single);
10679 unregister_netdevice_many(&single);
10682 EXPORT_SYMBOL(unregister_netdevice_queue);
10685 * unregister_netdevice_many - unregister many devices
10686 * @head: list of devices
10688 * Note: As most callers use a stack allocated list_head,
10689 * we force a list_del() to make sure stack wont be corrupted later.
10691 void unregister_netdevice_many(struct list_head *head)
10693 struct net_device *dev, *tmp;
10694 LIST_HEAD(close_head);
10696 BUG_ON(dev_boot_phase);
10699 if (list_empty(head))
10702 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
10703 /* Some devices call without registering
10704 * for initialization unwind. Remove those
10705 * devices and proceed with the remaining.
10707 if (dev->reg_state == NETREG_UNINITIALIZED) {
10708 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
10712 list_del(&dev->unreg_list);
10715 dev->dismantle = true;
10716 BUG_ON(dev->reg_state != NETREG_REGISTERED);
10719 /* If device is running, close it first. */
10720 list_for_each_entry(dev, head, unreg_list)
10721 list_add_tail(&dev->close_list, &close_head);
10722 dev_close_many(&close_head, true);
10724 list_for_each_entry(dev, head, unreg_list) {
10725 /* And unlink it from device chain. */
10726 unlist_netdevice(dev);
10728 dev->reg_state = NETREG_UNREGISTERING;
10730 flush_all_backlogs();
10734 list_for_each_entry(dev, head, unreg_list) {
10735 struct sk_buff *skb = NULL;
10737 /* Shutdown queueing discipline. */
10740 dev_xdp_uninstall(dev);
10742 netdev_offload_xstats_disable_all(dev);
10744 /* Notify protocols, that we are about to destroy
10745 * this device. They should clean all the things.
10747 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10749 if (!dev->rtnl_link_ops ||
10750 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10751 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
10752 GFP_KERNEL, NULL, 0);
10755 * Flush the unicast and multicast chains
10760 netdev_name_node_alt_flush(dev);
10761 netdev_name_node_free(dev->name_node);
10763 if (dev->netdev_ops->ndo_uninit)
10764 dev->netdev_ops->ndo_uninit(dev);
10767 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
10769 /* Notifier chain MUST detach us all upper devices. */
10770 WARN_ON(netdev_has_any_upper_dev(dev));
10771 WARN_ON(netdev_has_any_lower_dev(dev));
10773 /* Remove entries from kobject tree */
10774 netdev_unregister_kobject(dev);
10776 /* Remove XPS queueing entries */
10777 netif_reset_xps_queues_gt(dev, 0);
10783 list_for_each_entry(dev, head, unreg_list) {
10784 dev_put_track(dev, &dev->dev_registered_tracker);
10790 EXPORT_SYMBOL(unregister_netdevice_many);
10793 * unregister_netdev - remove device from the kernel
10796 * This function shuts down a device interface and removes it
10797 * from the kernel tables.
10799 * This is just a wrapper for unregister_netdevice that takes
10800 * the rtnl semaphore. In general you want to use this and not
10801 * unregister_netdevice.
10803 void unregister_netdev(struct net_device *dev)
10806 unregister_netdevice(dev);
10809 EXPORT_SYMBOL(unregister_netdev);
10812 * __dev_change_net_namespace - move device to different nethost namespace
10814 * @net: network namespace
10815 * @pat: If not NULL name pattern to try if the current device name
10816 * is already taken in the destination network namespace.
10817 * @new_ifindex: If not zero, specifies device index in the target
10820 * This function shuts down a device interface and moves it
10821 * to a new network namespace. On success 0 is returned, on
10822 * a failure a netagive errno code is returned.
10824 * Callers must hold the rtnl semaphore.
10827 int __dev_change_net_namespace(struct net_device *dev, struct net *net,
10828 const char *pat, int new_ifindex)
10830 struct net *net_old = dev_net(dev);
10835 /* Don't allow namespace local devices to be moved. */
10837 if (dev->features & NETIF_F_NETNS_LOCAL)
10840 /* Ensure the device has been registrered */
10841 if (dev->reg_state != NETREG_REGISTERED)
10844 /* Get out if there is nothing todo */
10846 if (net_eq(net_old, net))
10849 /* Pick the destination device name, and ensure
10850 * we can use it in the destination network namespace.
10853 if (netdev_name_in_use(net, dev->name)) {
10854 /* We get here if we can't use the current device name */
10857 err = dev_get_valid_name(net, dev, pat);
10862 /* Check that new_ifindex isn't used yet. */
10864 if (new_ifindex && __dev_get_by_index(net, new_ifindex))
10868 * And now a mini version of register_netdevice unregister_netdevice.
10871 /* If device is running close it first. */
10874 /* And unlink it from device chain */
10875 unlist_netdevice(dev);
10879 /* Shutdown queueing discipline. */
10882 /* Notify protocols, that we are about to destroy
10883 * this device. They should clean all the things.
10885 * Note that dev->reg_state stays at NETREG_REGISTERED.
10886 * This is wanted because this way 8021q and macvlan know
10887 * the device is just moving and can keep their slaves up.
10889 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10892 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
10893 /* If there is an ifindex conflict assign a new one */
10894 if (!new_ifindex) {
10895 if (__dev_get_by_index(net, dev->ifindex))
10896 new_ifindex = dev_new_index(net);
10898 new_ifindex = dev->ifindex;
10901 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
10905 * Flush the unicast and multicast chains
10910 /* Send a netdev-removed uevent to the old namespace */
10911 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
10912 netdev_adjacent_del_links(dev);
10914 /* Move per-net netdevice notifiers that are following the netdevice */
10915 move_netdevice_notifiers_dev_net(dev, net);
10917 /* Actually switch the network namespace */
10918 dev_net_set(dev, net);
10919 dev->ifindex = new_ifindex;
10921 /* Send a netdev-add uevent to the new namespace */
10922 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
10923 netdev_adjacent_add_links(dev);
10925 /* Fixup kobjects */
10926 err = device_rename(&dev->dev, dev->name);
10929 /* Adapt owner in case owning user namespace of target network
10930 * namespace is different from the original one.
10932 err = netdev_change_owner(dev, net_old, net);
10935 /* Add the device back in the hashes */
10936 list_netdevice(dev);
10938 /* Notify protocols, that a new device appeared. */
10939 call_netdevice_notifiers(NETDEV_REGISTER, dev);
10942 * Prevent userspace races by waiting until the network
10943 * device is fully setup before sending notifications.
10945 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10952 EXPORT_SYMBOL_GPL(__dev_change_net_namespace);
10954 static int dev_cpu_dead(unsigned int oldcpu)
10956 struct sk_buff **list_skb;
10957 struct sk_buff *skb;
10959 struct softnet_data *sd, *oldsd, *remsd = NULL;
10961 local_irq_disable();
10962 cpu = smp_processor_id();
10963 sd = &per_cpu(softnet_data, cpu);
10964 oldsd = &per_cpu(softnet_data, oldcpu);
10966 /* Find end of our completion_queue. */
10967 list_skb = &sd->completion_queue;
10969 list_skb = &(*list_skb)->next;
10970 /* Append completion queue from offline CPU. */
10971 *list_skb = oldsd->completion_queue;
10972 oldsd->completion_queue = NULL;
10974 /* Append output queue from offline CPU. */
10975 if (oldsd->output_queue) {
10976 *sd->output_queue_tailp = oldsd->output_queue;
10977 sd->output_queue_tailp = oldsd->output_queue_tailp;
10978 oldsd->output_queue = NULL;
10979 oldsd->output_queue_tailp = &oldsd->output_queue;
10981 /* Append NAPI poll list from offline CPU, with one exception :
10982 * process_backlog() must be called by cpu owning percpu backlog.
10983 * We properly handle process_queue & input_pkt_queue later.
10985 while (!list_empty(&oldsd->poll_list)) {
10986 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
10987 struct napi_struct,
10990 list_del_init(&napi->poll_list);
10991 if (napi->poll == process_backlog)
10994 ____napi_schedule(sd, napi);
10997 raise_softirq_irqoff(NET_TX_SOFTIRQ);
10998 local_irq_enable();
11001 remsd = oldsd->rps_ipi_list;
11002 oldsd->rps_ipi_list = NULL;
11004 /* send out pending IPI's on offline CPU */
11005 net_rps_send_ipi(remsd);
11007 /* Process offline CPU's input_pkt_queue */
11008 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
11010 input_queue_head_incr(oldsd);
11012 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
11014 input_queue_head_incr(oldsd);
11021 * netdev_increment_features - increment feature set by one
11022 * @all: current feature set
11023 * @one: new feature set
11024 * @mask: mask feature set
11026 * Computes a new feature set after adding a device with feature set
11027 * @one to the master device with current feature set @all. Will not
11028 * enable anything that is off in @mask. Returns the new feature set.
11030 netdev_features_t netdev_increment_features(netdev_features_t all,
11031 netdev_features_t one, netdev_features_t mask)
11033 if (mask & NETIF_F_HW_CSUM)
11034 mask |= NETIF_F_CSUM_MASK;
11035 mask |= NETIF_F_VLAN_CHALLENGED;
11037 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11038 all &= one | ~NETIF_F_ALL_FOR_ALL;
11040 /* If one device supports hw checksumming, set for all. */
11041 if (all & NETIF_F_HW_CSUM)
11042 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11046 EXPORT_SYMBOL(netdev_increment_features);
11048 static struct hlist_head * __net_init netdev_create_hash(void)
11051 struct hlist_head *hash;
11053 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11055 for (i = 0; i < NETDEV_HASHENTRIES; i++)
11056 INIT_HLIST_HEAD(&hash[i]);
11061 /* Initialize per network namespace state */
11062 static int __net_init netdev_init(struct net *net)
11064 BUILD_BUG_ON(GRO_HASH_BUCKETS >
11065 8 * sizeof_field(struct napi_struct, gro_bitmask));
11067 INIT_LIST_HEAD(&net->dev_base_head);
11069 net->dev_name_head = netdev_create_hash();
11070 if (net->dev_name_head == NULL)
11073 net->dev_index_head = netdev_create_hash();
11074 if (net->dev_index_head == NULL)
11077 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11082 kfree(net->dev_name_head);
11088 * netdev_drivername - network driver for the device
11089 * @dev: network device
11091 * Determine network driver for device.
11093 const char *netdev_drivername(const struct net_device *dev)
11095 const struct device_driver *driver;
11096 const struct device *parent;
11097 const char *empty = "";
11099 parent = dev->dev.parent;
11103 driver = parent->driver;
11104 if (driver && driver->name)
11105 return driver->name;
11109 static void __netdev_printk(const char *level, const struct net_device *dev,
11110 struct va_format *vaf)
11112 if (dev && dev->dev.parent) {
11113 dev_printk_emit(level[1] - '0',
11116 dev_driver_string(dev->dev.parent),
11117 dev_name(dev->dev.parent),
11118 netdev_name(dev), netdev_reg_state(dev),
11121 printk("%s%s%s: %pV",
11122 level, netdev_name(dev), netdev_reg_state(dev), vaf);
11124 printk("%s(NULL net_device): %pV", level, vaf);
11128 void netdev_printk(const char *level, const struct net_device *dev,
11129 const char *format, ...)
11131 struct va_format vaf;
11134 va_start(args, format);
11139 __netdev_printk(level, dev, &vaf);
11143 EXPORT_SYMBOL(netdev_printk);
11145 #define define_netdev_printk_level(func, level) \
11146 void func(const struct net_device *dev, const char *fmt, ...) \
11148 struct va_format vaf; \
11151 va_start(args, fmt); \
11156 __netdev_printk(level, dev, &vaf); \
11160 EXPORT_SYMBOL(func);
11162 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11163 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11164 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11165 define_netdev_printk_level(netdev_err, KERN_ERR);
11166 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11167 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11168 define_netdev_printk_level(netdev_info, KERN_INFO);
11170 static void __net_exit netdev_exit(struct net *net)
11172 kfree(net->dev_name_head);
11173 kfree(net->dev_index_head);
11174 if (net != &init_net)
11175 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11178 static struct pernet_operations __net_initdata netdev_net_ops = {
11179 .init = netdev_init,
11180 .exit = netdev_exit,
11183 static void __net_exit default_device_exit_net(struct net *net)
11185 struct net_device *dev, *aux;
11187 * Push all migratable network devices back to the
11188 * initial network namespace
11191 for_each_netdev_safe(net, dev, aux) {
11193 char fb_name[IFNAMSIZ];
11195 /* Ignore unmoveable devices (i.e. loopback) */
11196 if (dev->features & NETIF_F_NETNS_LOCAL)
11199 /* Leave virtual devices for the generic cleanup */
11200 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11203 /* Push remaining network devices to init_net */
11204 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11205 if (netdev_name_in_use(&init_net, fb_name))
11206 snprintf(fb_name, IFNAMSIZ, "dev%%d");
11207 err = dev_change_net_namespace(dev, &init_net, fb_name);
11209 pr_emerg("%s: failed to move %s to init_net: %d\n",
11210 __func__, dev->name, err);
11216 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11218 /* At exit all network devices most be removed from a network
11219 * namespace. Do this in the reverse order of registration.
11220 * Do this across as many network namespaces as possible to
11221 * improve batching efficiency.
11223 struct net_device *dev;
11225 LIST_HEAD(dev_kill_list);
11228 list_for_each_entry(net, net_list, exit_list) {
11229 default_device_exit_net(net);
11233 list_for_each_entry(net, net_list, exit_list) {
11234 for_each_netdev_reverse(net, dev) {
11235 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11236 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11238 unregister_netdevice_queue(dev, &dev_kill_list);
11241 unregister_netdevice_many(&dev_kill_list);
11245 static struct pernet_operations __net_initdata default_device_ops = {
11246 .exit_batch = default_device_exit_batch,
11250 * Initialize the DEV module. At boot time this walks the device list and
11251 * unhooks any devices that fail to initialise (normally hardware not
11252 * present) and leaves us with a valid list of present and active devices.
11257 * This is called single threaded during boot, so no need
11258 * to take the rtnl semaphore.
11260 static int __init net_dev_init(void)
11262 int i, rc = -ENOMEM;
11264 BUG_ON(!dev_boot_phase);
11266 if (dev_proc_init())
11269 if (netdev_kobject_init())
11272 INIT_LIST_HEAD(&ptype_all);
11273 for (i = 0; i < PTYPE_HASH_SIZE; i++)
11274 INIT_LIST_HEAD(&ptype_base[i]);
11276 if (register_pernet_subsys(&netdev_net_ops))
11280 * Initialise the packet receive queues.
11283 for_each_possible_cpu(i) {
11284 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
11285 struct softnet_data *sd = &per_cpu(softnet_data, i);
11287 INIT_WORK(flush, flush_backlog);
11289 skb_queue_head_init(&sd->input_pkt_queue);
11290 skb_queue_head_init(&sd->process_queue);
11291 #ifdef CONFIG_XFRM_OFFLOAD
11292 skb_queue_head_init(&sd->xfrm_backlog);
11294 INIT_LIST_HEAD(&sd->poll_list);
11295 sd->output_queue_tailp = &sd->output_queue;
11297 INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
11301 init_gro_hash(&sd->backlog);
11302 sd->backlog.poll = process_backlog;
11303 sd->backlog.weight = weight_p;
11306 dev_boot_phase = 0;
11308 /* The loopback device is special if any other network devices
11309 * is present in a network namespace the loopback device must
11310 * be present. Since we now dynamically allocate and free the
11311 * loopback device ensure this invariant is maintained by
11312 * keeping the loopback device as the first device on the
11313 * list of network devices. Ensuring the loopback devices
11314 * is the first device that appears and the last network device
11317 if (register_pernet_device(&loopback_net_ops))
11320 if (register_pernet_device(&default_device_ops))
11323 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11324 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11326 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11327 NULL, dev_cpu_dead);
11334 subsys_initcall(net_dev_init);